aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/Web/ProtoWebClient.cs
blob: 7f8beef0476accf1a50e4521ef1c851e1bb9f7f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Tango.PMR.Synchronization;

namespace Tango.Transport.Web
{
    public class ProtoWebClient : ITransportWebClient
    {
        private HttpClient _httpClient;

        public ProtoWebClient()
        {
            _httpClient = new HttpClient();
        }

        public Task<Response> Post<Request, Response>(String url, Request request) where Request : class, IMessage where Response : class, IMessage
        {
            return Task.Factory.StartNew<Response>(() =>
            {

                var req = new ByteArrayContent(request.ToByteArray());
                req.Headers.Add("Content-Type", "application/x-protobuf");

                var response = _httpClient.PostAsync(url, req).Result;

                var data = response.Content.ReadAsByteArrayAsync().Result;

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    HttpProtoException exception = HttpProtoException.Parser.ParseFrom(data);
                    throw new HttpException(exception.StatusCode, exception.Message);
                }

                Response dummy = Activator.CreateInstance<Response>() as Response;

                return dummy.GetParser().ParseFrom(data) as Response;
            });
        }

        public void Dispose()
        {
            _httpClient.Dispose();
        }
    }
}