• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# JsonServiceClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: HyperCommand

        public HyperCommand(JsonServiceClient client ,Grandsys.Wfm.Services.Outsource.ServiceModel.Link link)
        {
            Content = link.Name;
            Command = new ReactiveAsyncCommand();
            Method = link.Method;
            Request = link.Request;
            Response = Command.RegisterAsyncFunction(_ => {

                Model.EvaluationItem response;
                if (string.IsNullOrEmpty(Method))
                    return null;

                switch (Method)
                {
                    default:
                        response = client.Send<Model.EvaluationItem>(Method, Request.ToUrl(Method), _ ?? Request);
                        break;
                    case "GET":
                        response = client.Get<Model.EvaluationItem>(Request.ToUrl(Method));
                        break;
                }
                return response;
            });
            Command.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex.Message));
        }
开发者ID:jaohaohsuan,项目名称:master-detail,代码行数:25,代码来源:HyperCommand.cs


示例17: DeployApp

        public static void DeployApp(string endpoint, string appName)
        {
            try
            {
                JsonServiceClient client = new JsonServiceClient(endpoint);

                Console.WriteLine("----> Compressing files");
                byte[] folder = CompressionHelper.CompressFolderToBytes(Environment.CurrentDirectory);

                Console.WriteLine("----> Uploading files (" + ((float)folder.Length / (1024.0f*1024.0f)) + " MB)");

                File.WriteAllBytes("deploy.gzip", folder);
                client.PostFile<int>("/API/Deploy/" + appName, new FileInfo("deploy.gzip"), "multipart/form-data");
                File.Delete("deploy.gzip");

                DeployAppStatusRequest request = new DeployAppStatusRequest() { AppName = appName };
                DeployAppStatusResponse response = client.Get(request);
                while (!response.Completed)
                {
                    Console.Write(response.Log);
                    response = client.Get(request);
                }
            }
            catch (WebServiceException e)
            {
                Console.WriteLine(e.ResponseBody);
                Console.WriteLine(e.ErrorMessage);
                Console.WriteLine(e.ServerStackTrace);
            }
        }
开发者ID:zanders3,项目名称:katla,代码行数:30,代码来源:DeployAppClient.cs


示例18: TestCanUpdateCustomer

        public void TestCanUpdateCustomer()
        {
            JsonServiceClient client = new JsonServiceClient("http://localhost:2337/");
            //Force cache
            client.Get(new GetCustomer { Id = 1 });
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var cachedResponse = client.Get(new GetCustomer { Id = 1 });
            stopwatch.Stop();
            var cachedTime = stopwatch.ElapsedTicks;
            stopwatch.Reset();

            client.Put(new UpdateCustomer { Id = 1, Name = "Johno" });

            stopwatch.Start();
            var nonCachedResponse = client.Get(new GetCustomer { Id = 1 });
            stopwatch.Stop();
            var nonCacheTime = stopwatch.ElapsedTicks;

            Assert.That(cachedResponse.Result, Is.Not.Null);
            Assert.That(cachedResponse.Result.Orders.Count, Is.EqualTo(5));

            Assert.That(nonCachedResponse.Result, Is.Not.Null);
            Assert.That(nonCachedResponse.Result.Orders.Count, Is.EqualTo(5));
            Assert.That(nonCachedResponse.Result.Name, Is.EqualTo("Johno"));

            Assert.That(cachedTime, Is.LessThan(nonCacheTime));
        }
开发者ID:quyenbc,项目名称:AwsGettingStarted,代码行数:28,代码来源:UnitTest1.cs


示例19: Calls_ProductsService_with_JsonServiceClient

        public void Calls_ProductsService_with_JsonServiceClient()
        {
            IRestClient client = new JsonServiceClient(BaseUri);

            "\nAll Products:".Print();
            client.Get(new FindProducts()).PrintDump();

            List<Product> toyProducts = client.Get(new FindProducts { Category = "Toys" });
            "\nToy Products:".Print();
            toyProducts.PrintDump();

            List<Product> productsOver2Bucks = client.Get(new FindProducts { PriceGreaterThan = 2 });
            "\nProducts over $2:".Print();
            productsOver2Bucks.PrintDump();

            List<Product> hardwareOver2Bucks = client.Get(new FindProducts { PriceGreaterThan = 2, Category = "Hardware" });
            "\nHardware over $2:".Print();
            hardwareOver2Bucks.PrintDump();

            Product product1 = client.Get(new GetProduct { Id = 1 });
            "\nProduct with Id = 1:".Print();
            product1.PrintDump();

            "\nIt's Hammer Time!".Print();
            Product productHammer = client.Get(new GetProduct { Name = "Hammer" });
            productHammer.PrintDump();
        }
开发者ID:Eugene-Arutchev,项目名称:ServiceStack.UseCases,代码行数:27,代码来源:ProductsServiceTests.cs


示例20: CreateApp

        public static void CreateApp(string endpoint, string appName)
        {
            JsonServiceClient client = new JsonServiceClient(endpoint);
            client.Post(new Server.CreateAppRequest()
            {
                AppName = appName
            });

            try
            {
                Server.CreateAppStatus status;
                do
                {
                    status = client.Get(new Server.CreateAppStatusRequest() { AppName = appName });
                    if (status == null) break;
                    Console.Write(status.Log);
                    Thread.Sleep(200);
                }
                while (!status.Completed);
            }
            catch (WebServiceException e)
            {
                Console.WriteLine(e.ResponseBody);
                Console.WriteLine(e.ErrorMessage);
                Console.WriteLine(e.ServerStackTrace);
            }
        }
开发者ID:zanders3,项目名称:katla,代码行数:27,代码来源:CreateAppClient.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# JsonTextReader类代码示例发布时间:2022-05-24
下一篇:
C# JsonSerializerSettings类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap