Example #1
0
        public async Task WhenGetXmlWithCallbackReturnsErrorHttpStatusCode_CodeIsAccessibleViaResponseParameter()
        {
            var expectedString = "<root><foo>Foo</foo><bar>Bar</bar></root>";
            var expected       = new XmlDocument();

            expected.LoadXml(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            var callback = false;
            await http.GetXml((err, res, body) =>
            {
                callback = true;
                Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
            });

            Assert.True(callback);
        }
Example #2
0
        public IActionResult QueryWorkFlows()
        {
            var certification = HttpContext.Request.Headers["certification"];
            var success       = UserRoleCache.TryGetUserRole(certification, out var userRole);

            if (!success)
            {
                return(NotFound("try again"));
            }
            int userId = userRole.User.UserId;

            try
            {
                var response = HttpWrapper.CallServiceByGet("/api/entity/workflows", $"id={userId}", $"type=userid");
                if (!response.IsSuccessCode)
                {
                    return(NotFound("try again"));
                }
                var res = JsonSerializer.Deserialize <List <WorkFlow> >(response.Body);
                return(Ok(res));
            }
            catch (JsonException)
            {
                return(BadRequest("internal error"));
            }
            catch (Exception)
            {
                return(NotFound("try again"));
            }
        }
Example #3
0
 public CredentialsProvider(
     IOptions <ApplicationOptions> options,
     HttpWrapper httpWrapper)
 {
     m_HttpWrapper = httpWrapper;
     Options       = options;
 }
Example #4
0
        public IActionResult QueryUserChemicals()
        {
            var certification = HttpContext.Request.Headers["certification"];
            var success       = UserRoleCache.TryGetUserRole(certification, out var userRole);

            if (!success)
            {
                return(NotFound("try again"));
            }
            int userid = userRole.User.UserId;

            _logger.LogInformation("query chemicals of user id: {1}", userid);
            try
            {
                var response = HttpWrapper.CallServiceByGet("/api/entity/user/chemicals", $"userid={userid}");
                if (!response.IsSuccessCode)
                {
                    return(NotFound("try again"));
                }
                var res = JsonSerializer.Deserialize <List <Chemical> >(response.Body);
                return(Ok(res));
            }
            catch (JsonException)
            {
                return(BadRequest("internal error"));
            }
            catch (Exception)
            {
                return(NotFound("try again"));
            }
        }
Example #5
0
    // Use this for initialization
    void Start()
    {
        this.onSuccess += this.SuccessMethod;
        HttpWrapper hw = GetComponent <HttpWrapper>();

        hw.GET("http://img.juimg.com/tuku/yulantu/140703/330746-140F302191731.jpg", this.onSuccess);
    }
Example #6
0
    void Start()
    {
//        StartCoroutine(ScreenShotPNG());

//        IEnumerator ienmuertor = NextHaveData();
//        bool hasNext=ienmuertor.MoveNext();
//        print("第一次调用");
//        print("是否有数据:"+hasNext);
//        hasNext = ienmuertor.MoveNext();
//        print("第二次调用");
//        print("是否有数据:"+hasNext);
//        hasNext = ienmuertor.MoveNext();
//        print("第三次调用");
//        print("是否有数据:"+hasNext+"current:"+ienmuertor.Current);
        mr = this.GetComponent <MeshRenderer>();

        onSuccess += this.OnSuccessFuc;
        HttpWrapper hw = GetComponent <HttpWrapper>();

        hw.Get(@"http://www.bz55.com/uploads/allimg/160601/140-1606010R501.jpg", onSuccess);

        Int32?testNull = null;
        Int32?testInt  = testNull ?? 99;

        Debug.Log(testInt.HasValue + "  " + testInt.Value);
        Debug.Log(testNull.HasValue + "  " + testNull.GetValueOrDefault());
    }
Example #7
0
 public NetatmoRepository(
     ICredentials credentials,
     IOptions <ApplicationOptions> options,
     HttpWrapper httpWrapper)
 {
     Options       = options;
     m_HttpWrapper = httpWrapper;
     m_Credentials = credentials;
 }
Example #8
0
 public WunderlistRepository(
     IOptions <ApplicationOptions> options,
     HttpWrapper httpWrapper,
     ICredentials credentials)
 {
     Options       = options;
     m_HttpWrapper = httpWrapper;
     m_Credentials = credentials;
 }
Example #9
0
    private void Start()
    {
        this.onSuccess += this.SuccessMethod;
        HttpWrapper hw = GetComponent <HttpWrapper>();

        // hw.GET("http://www.baidu.com", this.onSuccess);
        //hw.POST("http://www.baidu.com",null,this.onSuccess);
        hw.Put("http://www.baidu.com", "Chinar的测试数据", this.onSuccess);
    }
Example #10
0
        IEnumerator FetchPlayLists()
        {
            List <StreamInfo> streamPlayList = new List <StreamInfo>();
            List <AudioInfo>  audioPlayList  = new List <AudioInfo>();

            if (!string.IsNullOrEmpty(m_StreamPlayListName))
            {
                HttpWrapper wrapper = new HttpWrapper();
                wrapper.RequestPlaylistDiff <StreamInfo>(GetAbsoluteURL(m_StreamPlayListName), m_CurrentStreamPlaylistData, (list, newData) => {
                    if (list != null)
                    {
                        streamPlayList.AddRange(list);
                        m_CurrentStreamPlaylistData = newData;
                    }
                });
                yield return(new WaitUntil(wrapper.RequestFinished));
            }

            if (!string.IsNullOrEmpty(m_AudioPlayListName))
            {
                HttpWrapper wrapper = new HttpWrapper();
                wrapper.RequestPlaylistDiff <AudioInfo>(GetAbsoluteURL(m_AudioPlayListName), m_CurrentAudioPlayListData, (list, newData) => {
                    if (list != null)
                    {
                        audioPlayList.AddRange(list);
                        m_CurrentAudioPlayListData = newData;
                    }
                });
                yield return(new WaitUntil(wrapper.RequestFinished));
            }

            int length = (streamPlayList.Count > audioPlayList.Count) ? streamPlayList.Count : audioPlayList.Count;

            for (int i = 0; i < length; i++)
            {
                if (i <= streamPlayList.Count - 1 && m_MeshRenderer != null)
                {
                    HttpWrapper wrapper = new HttpWrapper();
                    wrapper.RequestBinary(GetAbsoluteURL(streamPlayList[i].video), data => {
                        m_MeshRenderer.AddVertexData(Path.GetFileNameWithoutExtension(streamPlayList[i].video), data, streamPlayList[i].startTicks);
                    });
                    yield return(new WaitUntil(wrapper.RequestFinished));
                }
                if (i <= audioPlayList.Count - 1 && m_AudioRenderer != null)
                {
                    HttpWrapper wrapper = new HttpWrapper();
                    wrapper.RequestAudio(GetAbsoluteURL(audioPlayList[i].audio), audio => {
                        m_AudioRenderer.AddAudioData(Path.GetFileNameWithoutExtension(audioPlayList[i].audio), audio);
                    });
                    yield return(new WaitUntil(wrapper.RequestFinished));
                }
            }
        }
Example #11
0
        public async Task WhenQueryParametersAreAddedViaDictionary_UrlIsCorrectlyConstructed()
        {
            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK));
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            http.Query(new Dictionary<string, string>{{"foo", "Foo"}, {"bar", "Bar"}});
            
            await http.Get();

            Assert.AreEqual("http://foo.com/?foo=Foo&bar=Bar", stubHandler.LastRequest.RequestUri.ToString());
        }
Example #12
0
 public IActionResult Destroy([FromBody] Chemical chemical)
 {
     _logger.LogInformation("destroy chemical id: {1}", chemical.ChemicalId);
     try
     {
         var response = HttpWrapper.CallServiceByPost("/api/entity/chemical/discard",
                                                      JsonSerializer.Serialize(chemical));
         return(Ok());
     }
     catch (Exception)
     {
         return(NotFound("try again"));
     }
 }
Example #13
0
 public IActionResult RejectFinancial([FromBody] SolveFormParam param)
 {
     try
     {
         HttpWrapper.CallServiceByPost("/api/financial/reject",
                                       JsonSerializer.Serialize(param));
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #14
0
 public IActionResult ReturnChemicals([FromBody] ReturnChemicalParam param)
 {
     try
     {
         HttpWrapper.CallServiceByPost("/api/claim/return",
                                       JsonSerializer.Serialize(param));
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #15
0
        public async Task WhenQueryParametersAreAddedindividually_UrlIsCorrectlyConstructed()
        {
            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK));
            var http        = new HttpWrapper("http://foo.com/",
                                              new TestLogger(),
                                              new Envelope(new TextMessage(CreateTestUser(), "test")),
                                              stubHandler);

            http.Query("foo", "Foo");
            http.Query("bar", "Bar");

            await http.Get();

            Assert.Equal("http://foo.com/?foo=Foo&bar=Bar", stubHandler.LastRequest.RequestUri.ToString());
        }
Example #16
0
        public async Task WhenGetJson_AndContentContainsGarbage_ThrowsException()
        {
            var expected = "dfsgsdf%#@$%^&*()";

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expected)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            Assert.Throws <AggregateException>(() => http.GetJson().Result);
        }
Example #17
0
        public async Task WhenGetXmlIsCalled_AndContentIsGarbage_ExceptionIsThrown()
        {
            var expectedString = "!@#$%^&*()_+<root><foo@#$%^&*()_>$%^&*(OP)_Foo</foo><bar>Bar</bar></root>";

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            Assert.Throws <AggregateException>(() => http.GetXml().Result);
        }
Example #18
0
 public IActionResult Declear([FromBody] PostDeclarationFormParam param)
 {
     try
     {
         param.Form.SubmitTime = DateTime.Now;
         HttpWrapper.CallServiceByPost("/api/declaration/apply",
                                       JsonSerializer.Serialize(param));
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #19
0
 public IActionResult Purchase([FromQuery] int workflowid)
 {
     try
     {
         var response = HttpWrapper.CallServiceByGet("/api/entity/purchase",
                                                     $"workflowid={workflowid}");
         if (!response.IsSuccessCode)
         {
             return(NotFound("internal error"));
         }
         return(Ok());
     }
     catch (Exception)
     {
         return(NotFound("try again"));
     }
 }
Example #20
0
 public IActionResult Claim([FromBody] PostClaimFormParam param)
 {
     _logger.LogInformation("Post claim form. formid: {formid}", param.Form.Id);
     _logger.LogInformation("With {count} chemicals.", param.Chemicals.Count);
     try
     {
         param.Form.SubmitTime = DateTime.Now;
         HttpWrapper.CallServiceByPost("/api/claim/apply",
                                       JsonSerializer.Serialize(param));
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #21
0
 public WebImageItem(string Url, Vector2 ExpectedSize)
 {
     this.Url       = Url;
     this.Texture2d = new Texture2D((int)ExpectedSize.x, (int)ExpectedSize.y);
     this.Loader    = new HttpWrapper();
     this.Loader.GET
     (
         this.Url,
         (WWW www) =>
     {
         if (string.IsNullOrEmpty(www.error))
         {
             this.Texture2d = www.texture;
         }
     }
     );
 }
Example #22
0
 public IActionResult GetClaimDetail([FromQuery] int formid)
 {
     try
     {
         var response = HttpWrapper.CallServiceByGet("/api/claim", $"formid={formid}");
         if (!response.IsSuccessCode)
         {
             return(NotFound("try again"));
         }
         var res = JsonSerializer.Deserialize <PostClaimFormParam>(response.Body);
         return(Ok(res));
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #23
0
        public async Task WhenQueryParametersAreAddedByAnonymousType_UrlIsCorrectlyConstructed()
        {
            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK));
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(), 
                new Envelope(new TextMessage(CreateTestUser(), "test")),
                stubHandler);

            http.Query(new
            {
                foo = "Foo",
                bar = "Bar"
            });

            await http.Get();

            Assert.Equal("http://foo.com/?foo=Foo&bar=Bar", stubHandler.LastRequest.RequestUri.ToString());
        }
Example #24
0
        /// <summary>
        /// Launch the scanning process.
        /// </summary>
        public void LaunchScanningProcess(bool ConsoleOutput, string EditorPlayerPrefKey = "")
        {
            OutputInConsole = ConsoleOutput;

            _editorPlayerPrefKey = EditorPlayerPrefKey;

            if (OutputInConsole)
            {
                Debug.Log("Project Scanner: Downloading Assets Description");
            }

            _hasError   = false;
            _isScanning = true;
            AssetsList  = new SortedDictionary <string, AssetItem>();

            _wwwWrapper = new HttpWrapper();

            WWWForm _form = new WWWForm();

            _form.AddField("UnityVersion", Application.unityVersion);
            _form.AddField("PlayMakerVersion", MyUtils.GetPlayMakerVersion());

            _wwwWrapper.GET
            (
                "http://www.fabrejean.net/projects/playmaker_ecosystem/assetsDescription"
                ,
                _form
                ,
                (WWW www) =>
            {
                if (!string.IsNullOrEmpty(www.error))
                {
                    Debug.LogError("Project Scanner: Error downloading assets definition :" + www.error);

                    _isScanning = false;
                    _hasError   = true;
                }
                else
                {
                    EditorCoroutine.start(DoScanProject(www.text));
                }
            }
            );
        }
Example #25
0
        public async Task WhenGetJsonIsCalled_ResponseContentIsDeserialized()
        {
            var expectedString = JsonConvert.SerializeObject(new { Id = 4, Foo = "Foo", Bar = "Bar", Date = DateTime.Now });
            var expected       = JsonConvert.DeserializeObject(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            var actual = await http.GetJson();


            Assert.True(new JTokenEqualityComparer().Equals((JToken)expected, (JToken)actual));
        }
Example #26
0
 public static string GetPersonaName(this HttpWrapper httpWrapper, ulong personaID)
 {
     if (httpWrapper.FailureCount >= httpWrapper.MaxConnections)
     {
         return(null);
     }
     httpWrapper.HttpSem.Wait();
     try {
         string url  = $@"https://steamcommunity.com/profiles/{personaID}";
         var    http = httpWrapper.HttpClient.GetStringAsync(url).Result;
         var    ret  = ExtractPersonaNameFromHTML(http);
         httpWrapper.FailureCount = 0; // hope is restored!
         return(ret);
     } catch (Exception ex) {
         httpWrapper.FailureCount++; // hope is fading!
         throw new Exception($"GetPersonaName({personaID}) failed", ex);
     } finally {
         httpWrapper.HttpSem.Release();
     }
 }
Example #27
0
        public IActionResult ReadStatusChange([FromBody] NotifyUpdateParam param)
        {
            var certification = HttpContext.Request.Headers["certification"];

            if (UserRoleCache.TryGetUserRole(certification, out var userRole))
            {
                param.UserId = userRole.User.UserId;
                try
                {
                    var response = HttpWrapper.CallServiceByPost("/api/entity/notify",
                                                                 JsonSerializer.Serialize(param));
                    return(Ok());
                }
                catch (Exception)
                {
                    return(NotFound("try again"));
                }
            }
            return(Unauthorized());
        }
Example #28
0
        public async Task WhenGetXmlIsCalled_ResponseContentIsDeserialized()
        {
            var expectedString = "<root><foo>Foo</foo><bar>Bar</bar></root>";
            var expected       = new XmlDocument();

            expected.LoadXml(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            var actual = await http.GetXml();

            Assert.Equal(expected.ToString(), actual.ToString());
        }
Example #29
0
 public IActionResult RejectDeclear([FromBody] SolveFormParam param)
 {
     if (UserRoleCache.TryGetUserRole(HttpContext.Request.Headers["certification"], out UserRoleResult result))
     {
         if (!result.Roles.Exists(r => r.LabId == param.LabId))
         {
             return(Unauthorized());
         }
     }
     try
     {
         HttpWrapper.CallServiceByPost("/api/declaration/reject",
                                       JsonSerializer.Serialize(param));
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(NotFound(e.Message));
     }
 }
Example #30
0
 public IActionResult QueryWorkFlowById([FromQuery] int workflowId)
 {
     try
     {
         var response = HttpWrapper.CallServiceByGet("/api/entity/workflow", $"workflowid={workflowId}");
         if (!response.IsSuccessCode)
         {
             return(NotFound("try again"));
         }
         var res = JsonSerializer.Deserialize <WorkFlow>(response.Body);
         return(Ok(res));
     }
     catch (JsonException)
     {
         return(BadRequest("internal error"));
     }
     catch (Exception)
     {
         return(NotFound("try again"));
     }
 }
Example #31
0
 public IActionResult QueryClaimChemicals([FromQuery] long formid)
 {
     try
     {
         var response = HttpWrapper.CallServiceByGet("/api/entity/chemicals", $"labId={formid}");
         if (!response.IsSuccessCode)
         {
             return(NotFound("try again"));
         }
         var res = JsonSerializer.Deserialize <List <Chemical> >(response.Body);
         return(Ok(res));
     }
     catch (JsonException)
     {
         return(BadRequest("internal error"));
     }
     catch (Exception)
     {
         return(NotFound("try again"));
     }
 }
Example #32
0
        public async Task WhenGetJsonWithCallbackReturnsErrorHttpStatusCode_CodeIsAccessibleViaResponseParameter()
        {
            var expectedString = JsonConvert.SerializeObject(new { Id = 4, Foo = "Foo", Bar = "Bar", Date = DateTime.Now });
            var expected       = JsonConvert.DeserializeObject(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                                       new TestLogger(),
                                       new Envelope(new TextMessage(CreateTestUser(), "test")),
                                       stubHandler);

            var callback = false;
            await http.GetJson((err, res, body) =>
            {
                callback = true;
                Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
            });

            Assert.True(callback);
        }
Example #33
0
        public async Task WhenGetJsonWithCallback_AndContentContainsGarbage_ThrowsException()
        {
            var expected = "dfsgsdf%#@$%^&*()";

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expected)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var callback = false;
            await http.GetJson((err, res, body) =>
            {
                callback = true;
                Assert.IsNotNull(err);
                Assert.IsInstanceOfType(err, typeof(Exception));
                
            });

            Assert.IsTrue(callback);
        }
Example #34
0
        public async Task WhenGetJson_AndContentContainsGarbage_ThrowsException()
        {
            var expected = "dfsgsdf%#@$%^&*()";

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expected)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            await http.GetJson();
            Assert.Fail("Should have thrown");
            
        }
Example #35
0
        public async Task WhenGetXmlWithCallbackReturnsErrorHttpStatusCode_CodeIsAccessibleViaResponseParameter()
        {
            var expectedString = "<root><foo>Foo</foo><bar>Bar</bar></root>";
            var expected = new XmlDocument();
            expected.LoadXml(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var callback = false;
            await http.GetXml((err, res, body) =>
            {
                callback = true;
                Assert.AreEqual(HttpStatusCode.NotFound, res.StatusCode);
            });
            Assert.IsTrue(callback);

        }
Example #36
0
        public async Task WhenGetXmlIsCalled_ResponseContentIsDeserialized()
        {
            var expectedString = "<root><foo>Foo</foo><bar>Bar</bar></root>";
            var expected = new XmlDocument();
            expected.LoadXml(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var actual = await http.GetXml();

            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Example #37
0
        public async Task WhenGetXmlIsCalled_AndContentIsGarbage_ExceptionIsThrown()
        {
            var expectedString = "!@#$%^&*()_+<root><foo@#$%^&*()_>$%^&*(OP)_Foo</foo><bar>Bar</bar></root>";
            
            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            await http.GetXml();

            Assert.Fail("Should have thrown");
        }
Example #38
0
        public async Task WhenGetXmlWithCallback_AndContentIsGarbage_ErrContainsException()
        {
            var expectedString = "!@#$%^&*()_+<root><foo@#$%^&*()_>$%^&*(OP)_Foo</foo><bar>Bar</bar></root>";

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var callback = false;
            await http.GetXml((err, res, body) =>
            {
                callback = true;
                Assert.IsNotNull(err);
                Assert.IsInstanceOfType(err, typeof(Exception));
            });
            Assert.IsTrue(callback);

        }
Example #39
0
        public async Task WhenGetJsonIsCalled_ResponseContentIsDeserialized()
        {
            var expectedString = JsonConvert.SerializeObject(new {Id=4, Foo = "Foo", Bar = "Bar", Date = DateTime.Now});
            var expected = JsonConvert.DeserializeObject(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var actual = await http.GetJson();


            Assert.IsTrue(new JTokenEqualityComparer().Equals((JToken)expected, (JToken)actual));
        }
Example #40
0
        public async Task WhenGetJsonWithCallbackReturnsErrorHttpStatusCode_CodeIsAccessibleViaResponseParameter()
        {
            var expectedString = JsonConvert.SerializeObject(new { Id = 4, Foo = "Foo", Bar = "Bar", Date = DateTime.Now });
            var expected = JsonConvert.DeserializeObject(expectedString);

            var stubHandler = new FakeHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(expectedString)
            });
            var http = new HttpWrapper("http://foo.com/",
                new TestLogger(),
                new Envelope(new TextMessage(CreateTestUser(), "test", "id")),
                stubHandler);

            var callback = false;
            await http.GetJson((err, res, body) =>
            {
                callback = true;
                Assert.AreEqual(HttpStatusCode.NotFound, res.StatusCode);
            });
            Assert.IsTrue(callback);

        }
Example #41
0
 public GoApi(Credentials credentials, GoUrls urls)
 {
     _credentials = credentials;
     _httpWrapper = new HttpWrapper(credentials);
     this.Urls = urls;
 }