当前位置: 首页>>代码示例>>C#>>正文


C# JsonServiceClient类代码示例

本文整理汇总了C#中JsonServiceClient的典型用法代码示例。如果您正苦于以下问题:C# JsonServiceClient类的具体用法?C# JsonServiceClient怎么用?C# JsonServiceClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonServiceClient类属于命名空间,在下文中一共展示了JsonServiceClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateClient

        private static JsonServiceClient CreateClient(string baseUrl, string token)
        {
            var client = new JsonServiceClient(baseUrl.TrimEnd('/'));
            client.AddHeader(HttpHeaders.Authorization, @"Bearer {0}".Fmt(token));

            return client;
        }
开发者ID:dirkrombauts,项目名称:SirenOfShame,代码行数:7,代码来源:AppVeyorService.cs

示例2: Can_report_progress_when_downloading_async

        public async Task Can_report_progress_when_downloading_async()
        {
            var hold = AsyncServiceClient.BufferSize;
            AsyncServiceClient.BufferSize = 100;

            try
            {
                var asyncClient = new JsonServiceClient(ListeningOn);

                var progress = new List<string>();

                //Note: total = -1 when 'Transfer-Encoding: chunked'
                //Available in ASP.NET or in HttpListener when downloading responses with known lengths: 
                //E.g: Strings, Files, etc.
                asyncClient.OnDownloadProgress = (done, total) =>
                    progress.Add("{0}/{1} bytes downloaded".Fmt(done, total));

                var response = await asyncClient.GetAsync(new TestProgress());

                progress.Each(x => x.Print());

                Assert.That(response.Length, Is.GreaterThan(0));
                Assert.That(progress.Count, Is.GreaterThan(0));
                Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded"));
                Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded"));
            }
            finally
            {
                AsyncServiceClient.BufferSize = hold;
            }
        }         
开发者ID:tystol,项目名称:ServiceStack,代码行数:31,代码来源:AsyncProgressTests.cs

示例3: getBuild

        /// <summary>
        /// Get a new build
        /// </summary>
        /// <returns>BuildInfo object or null on error/no build</returns>
        public static BuildInfo getBuild()
        {
            Console.WriteLine("* Checking for builds...");
            var client = new JsonServiceClient (apiurl);
            try
            {
                var buildInfo = client.Post (new CheckForBuild
                {
                    token = Uri.EscapeDataString (Config.token)
                });

                if (buildInfo != null)
                {
                    return buildInfo;
                }
            }
            catch (WebServiceException ex)
            {
                if(ex.StatusCode == 404)
                {
                    Console.WriteLine ("* Nothing");
                }
                else
                {
                    Console.WriteLine ("* Failed");
                }
            }

            return null;
        }
开发者ID:Wolfium,项目名称:gitlab-ci-runner-win,代码行数:34,代码来源:Network.cs

示例4: Populator

 public Populator(string url, double latitude, double longitude)
 {
     Url = url;
     Latitude = latitude;
     Longitude = longitude;
     _client = new JsonServiceClient(Url);
 }
开发者ID:sdmiller7,项目名称:API,代码行数:7,代码来源:Program.cs

示例5: DispatchTrip

 public override Gateway.DispatchTripResponse DispatchTrip(Gateway.DispatchTripRequest request)
 {
     Logger.BeginRequest("DispatchTrip sent to " + name, request);
     GatewayService.Dispatch dispatch = new GatewayService.Dispatch
     {
         access_token = AccessToken,
         PassengerId = request.passengerID,
         PassengerName = request.passengerName,
         Luggage = request.luggage,
         Persons = request.persons,
         PickupLat = request.pickupLocation.Lat,
         PickupLng = request.pickupLocation.Lng,
         PickupTime = request.pickupTime,
         DropoffLat = request.dropoffLocation == null ? (double?) null : request.dropoffLocation.Lat,
         DropoffLng = request.dropoffLocation == null ? (double?) null : request.dropoffLocation.Lng,
         PaymentMethod = request.paymentMethod,
         VehicleType = request.vehicleType,
         MaxPrice = request.maxPrice,
         MinRating = request.minRating,
         PartnerId = request.partnerID,
         FleetId = request.fleetID,
         DriverId = request.driverID,
         TripId = request.tripID
     };
     JsonServiceClient client = new JsonServiceClient(RootUrl);
     GatewayService.DispatchResponse resp = client.Get<GatewayService.DispatchResponse>(dispatch);
     Gateway.DispatchTripResponse response = new Gateway.DispatchTripResponse
     {
         result = resp.ResultCode,
     };
     Logger.EndRequest(response);
     return response;
 }
开发者ID:TripThru,项目名称:Gateway,代码行数:33,代码来源:1396817121$GatewayClient.cs

示例6: Does_AutoWire_ActionLevel_RequestFilters

        public void Does_AutoWire_ActionLevel_RequestFilters()
        {
            try
            {
                var client = new JsonServiceClient(ListeningOn);
                var response = client.Get(new ActionAttr());

                var expected = new List<string> {
                    typeof(FunqDepProperty).Name,
                    typeof(FunqDepDisposableProperty).Name,
                    typeof(AltDepProperty).Name,
                    typeof(AltDepDisposableProperty).Name,
                };

                response.Results.PrintDump();

                Assert.That(expected.EquivalentTo(response.Results));

            }
            catch (Exception ex)
            {
                ex.Message.Print();
                throw;
            }
        }
开发者ID:lysaghtn,项目名称:ServiceStack,代码行数:25,代码来源:IocServiceTests.cs

示例7: GetAccessToken

        // this performs our main OAuth authentication, performing
        // the request token retrieval, authorization, and exchange
        // for an access token
        public IToken GetAccessToken()
        {
            var consumerContext = new OAuthConsumerContext () {
                ConsumerKey = "anyone"
            };

            var rest_client = new JsonServiceClient (BaseUri);
            var url = new Rainy.WebService.ApiRequest ().ToUrl("GET");
            var api_ref = rest_client.Get<ApiResponse> (url);

            var session = new OAuthSession (consumerContext, api_ref.OAuthRequestTokenUrl,
                                            api_ref.OAuthAuthorizeUrl, api_ref.OAuthAccessTokenUrl);

            IToken request_token = session.GetRequestToken ();

            // we dont need a callback url
            string link = session.GetUserAuthorizationUrlForToken (request_token, "http://example.com/");

            // visit the link to perform the authorization (no interaction needed)
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create (link);
            // disallow auto redirection, since we are interested in the location header only
            req.AllowAutoRedirect = false;

            // the oauth_verifier we need, is part of the querystring in the (redirection)
            // 'Location:' header
            string location = ((HttpWebResponse)req.GetResponse ()).Headers ["Location"];
            var query = string.Join ("", location.Split ('?').Skip (1));
            var oauth_data = System.Web.HttpUtility.ParseQueryString (query);

            IToken access_token = session.ExchangeRequestTokenForAccessToken (request_token, oauth_data ["oauth_verifier"]);

            return access_token;
        }
开发者ID:BooTeK,项目名称:Rainy,代码行数:36,代码来源:RainyTestServer.cs

示例8: Test12

 void Test12(JsonServiceClient client)
 {
     Console.WriteLine("~~~~~ DeleteUser (newuser3) ~~~~~~~~~");
     UserResponse response = client.Delete<XamarinEvolveSSLibrary.UserResponse>("User/newuser3");
     Console.WriteLine("Expected null: " + response.Exception);
     Console.WriteLine();
 }
开发者ID:bholmes,项目名称:XamarinEvolve2013Project,代码行数:7,代码来源:SSTests.cs

示例9: btnTest_Click

        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
            //Make all access to UI components in UI Thread, i.e. before entering bg thread.
            var name = txtName.Text;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    var client = new JsonServiceClient("http://localhost:2000/")
                    {
                        //this tries to access UI component which is invalid in bg thread
                        ShareCookiesWithBrowser = false
                    };
                    var fileStream = new MemoryStream("content body".ToUtf8Bytes());
                    var response = client.PostFileWithRequest<UploadFileResponse>(
                        fileStream, "file.txt", new UploadFile { Name = name });

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = "File Size: {0} bytes".Fmt(response.FileSize);
                    });
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = ex.ToString();
                    });
                }
            });
        }
开发者ID:phaufe,项目名称:HelloMobile,代码行数:31,代码来源:MainPage.xaml.cs

示例10: JsonClientShouldGetPlacesToVisit

 public void JsonClientShouldGetPlacesToVisit()
 {
     var client = new JsonServiceClient(_listeningOn);
     var testRequest = new AllPlacesToVisitRequest();
     var response = client.Get(testRequest);
     Assert.AreEqual("Capital city of Australia",response.Places.FirstOrDefault().Description);
 }
开发者ID:Reidson-Industries,项目名称:places-to-visit,代码行数:7,代码来源:PlacesToVisitFunctionalTests.cs

示例11: Main

 public static void Main(string[] args)
 {
     JsonServiceClient client = new JsonServiceClient("http://127.0.0.1:8888/");
     client.Timeout = TimeSpan.FromSeconds(60);
     client.ReadWriteTimeout = TimeSpan.FromSeconds(60);
     client.DisableAutoCompression = true;
     int success = 0, error = 0;
     Parallel.For(0, 100, i => {
         try
         {
             Console.WriteLine(i.ToString());
             StatesResult result = client.Get(new GetLastStates());
             if(result.List.Count < 4000)
                 error++;
             Console.WriteLine("Received " + result.List.Count + " items");
             success++;
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
             error++;
         }
     });
     Console.WriteLine(string.Format("Test completed. Success count:{0}; Error count:{1}",success,error));
     client.Dispose();
 }
开发者ID:baurzhan,项目名称:servicestacktest,代码行数:26,代码来源:Program.cs

示例12: OnTestFixtureSetUp

        public void OnTestFixtureSetUp()
        {
            Client = new JsonServiceClient(BaseUri);
            var response = Client.Post<AuthenticateResponse>("/auth",
                new Authenticate { UserName = "test1", Password = "test1" });

        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:7,代码来源:TestBase.cs

示例13: RunTests

        public void RunTests()
        {
            byte[] imageData;

            using (Image srcImage = Image.FromFile(@"D:\Bill\Code\XamarinEvolve2013Project\TestSSAPI\testavatar.jpg"))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    srcImage.Save(m, ImageFormat.Jpeg);
                    imageData = m.ToArray(); //buffers
                }
            }

            JsonServiceClient client = new JsonServiceClient(SystemConstants.WebServiceBaseURL);

            UserAvatar userAvatar = new UserAvatar()
            {
                UserName = "billholmes",
                Data = imageData,
            };

            UserAvatarResponse response = client.Post<UserAvatarResponse>("UserAvatar", userAvatar);

            //response = client.Delete<UserAvatarResponse>("UserAvatar/billholmes");

            return;
        }
开发者ID:bholmes,项目名称:XamarinEvolve2013Project,代码行数:27,代码来源:AvatarTest.cs

示例14: Test_PostWithBadHostnameAndGetMessage_StatusIsFailed

        public void Test_PostWithBadHostnameAndGetMessage_StatusIsFailed()
        {
            // Create message
            var postRequest = new CreateMessage
            {
                ApplicationId = 1,
                Bcc = new[] { "[email protected]" },
                Body = "This is a test email.",
                Cc = new[] { "[email protected]" },
                Connection = new Connection
                {
                    EnableSsl = false,
                    Host = "nonexistant",
                    Port = 25
                },
                Credential = new Credential(),
                From = "[email protected]",
                ReplyTo = new[] { "[email protected]" },
                Sender = "[email protected]",
                Subject = "Test Message",
                To = new[] { "[email protected]" }
            };
            var client = new JsonServiceClient("http://localhost:59200/");
            var postResponse = client.Post(postRequest);

            // Get message
            var getRequest = new GetMessage
            {
                Id = postResponse.Id
            };
            var getResponse = client.Get(getRequest);

            Assert.Equal(3, getResponse.Status.TypeMessageStatusId);
            Assert.Equal(postResponse.Id, getResponse.Id);
        }
开发者ID:rwinte,项目名称:SendEmailHelper,代码行数:35,代码来源:MessageServiceTests.cs

示例15: TryLogin

        public void TryLogin()
        {
            using(var tempDb = new TempFile())
            {
                //GlobalProxySelection.Select = new WebProxy("127.0.0.1", 8888); // proxy via Fiddler2.

                using (var server = new Server()  { Port = 8000, SqliteFile = tempDb.Path })
                {
                    server.Start();

                    // log in
                    var restClient = new JsonServiceClient(FakeServer.BaseUri);
                    var response = restClient.Post<AuthResponseEx>(
                        "/api/auth/credentials?format=json",
                        new Auth()
                        {
                            UserName = "tech",
                            Password = "radar",
                            RememberMe = true
                        });

                    response.SessionId.ShouldMatch(@"[a-zA-Z0-9=+/]{20,100}");
                    response.UserName.ShouldBe("tech");
                    response.UserId.ShouldMatch(@"^[a-zA-Z0-9_-]{8}$");

                    // log out
                    var logoutResponse = restClient.Delete<AuthResponse>("/api/auth/credentials?format=json&UserName=tech");
                    logoutResponse.SessionId.ShouldBe(null);

                    // can't come up with a good way to verify that we logged out.
                }
            }
        }
开发者ID:eteeselink,项目名称:sioux_tech_radar,代码行数:33,代码来源:UsersTest.cs


注:本文中的JsonServiceClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。