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

            return client;
        }
        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;
            }
        }         
Example #3
0
        /// <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;
        }
Example #4
0
 public Populator(string url, double latitude, double longitude)
 {
     Url = url;
     Latitude = latitude;
     Longitude = longitude;
     _client = new JsonServiceClient(Url);
 }
 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;
 }
Example #6
0
        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;
            }
        }
Example #7
0
        // 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;
        }
 void Test12(JsonServiceClient client)
 {
     Console.WriteLine("~~~~~ DeleteUser (newuser3) ~~~~~~~~~");
     UserResponse response = client.Delete<XamarinEvolveSSLibrary.UserResponse>("User/newuser3");
     Console.WriteLine("Expected null: " + response.Exception);
     Console.WriteLine();
 }
Example #9
0
        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();
                    });
                }
            });
        }
 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);
 }
Example #11
0
 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();
 }
Example #12
0
        public void OnTestFixtureSetUp()
        {
            Client = new JsonServiceClient(BaseUri);
            var response = Client.Post<AuthenticateResponse>("/auth",
                new Authenticate { UserName = "test1", Password = "test1" });

        }
        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;
        }
        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);
        }
Example #15
0
        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.
                }
            }
        }
Example #16
0
        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));
        }
Example #17
0
        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);
            }
        }
Example #18
0
        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));
        }
        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();
        }
Example #20
0
        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);
            }
        }
 public static void ClassInitialize(TestContext context)
 {
     TestHelper.ResetDatabase();
     Client = new JsonServiceClient(ServiceUrl) {
         StoreCookies = true,
     };
 }
        public void Can_Send_Encrypted_Message()
        {
            var client = new JsonServiceClient(Config.AbsoluteBaseUri);

            var request = new HelloSecure { Name = "World" };

            var aes = new AesManaged { KeySize = AesUtils.KeySize };

            var aesKeyBytes = aes.Key.Combine(aes.IV);
            var rsaEncAesKeyBytes = RsaUtils.Encrypt(aesKeyBytes, SecureConfig.PublicKeyXml);

            var requestBody = typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedMessage = new EncryptedMessage
            {
                SymmetricKeyEncrypted = Convert.ToBase64String(rsaEncAesKeyBytes),
                EncryptedBody = AesUtils.Encrypt(requestBody, aes.Key, aes.IV)
            };
            var encResponse = client.Post(encryptedMessage);

            var responseJson = AesUtils.Decrypt(encResponse.EncryptedBody, aes.Key, aes.IV);
            var response = responseJson.FromJson<HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
 static void Main(string[] args)
 {
     var client = new JsonServiceClient("http://localhost:48048/");
     //TestFMUSimulateGet(client);
     //TestFMUSimulatePost(client);
     TestFMUSimulatePostTimePoints(client);
 }
Example #24
0
 private void Initialize(string serviceUrl, Action<Message> messageHandler,
     Action<ProgressMessage> progressHandler)
 {
     SendMessage = messageHandler ?? (m => { });
     SendProgress = progressHandler ?? (m => { });
     Client = new JsonServiceClient(serviceUrl) {Timeout = TimeSpan.FromMinutes(15)};
 }
Example #25
0
        /// <summary>
        /// Register the runner with the coordinator
        /// </summary>
        /// <param name="sPubKey">SSH Public Key</param>
        /// <param name="sToken">Token</param>
        /// <returns>Token</returns>
        public static string registerRunner(String sPubKey, String sToken)
        {
			var client = new JsonServiceClient (apiurl);
			try
			{
				var authToken = client.Post (new RegisterRunner
				{
					token = Uri.EscapeDataString (sToken),
					public_key = Uri.EscapeDataString (sPubKey)
				});

				if (!authToken.token.IsNullOrEmpty ())
				{
						Console.WriteLine ("Runner registered with id {0}", authToken.id);
						return authToken.token;
				}
				else
				{
					return null;
				}
			}
			catch(WebException ex)
			{
				Console.WriteLine ("Error while registering runner :", ex.Message);
				return null;
			}          
        }
		public void TearDown()
		{
			HTTPClientHelpers.Logout(_client);

			_client.Dispose();
			_client = null;
		}
Example #27
0
        public MainPage()
        {
            this.InitializeComponent();

//            WinStorePclExportClient.Configure();
            client = new JsonServiceClient("http://localhost:81/");
        }
        public void Populate()
        {
            ////var svc = new KnockKnockMongo();
            //var db = svc.Database<PotatoKnock>();
            //db.DeleteMany(Builders<PotatoKnock>.Filter.Empty);
            
            var knock = new KnockDto {
                FeedId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Location = new LocationDto
                {
                    Latitude = 45,
                    Longitude = 60
                },
                Message = "Turn me into a french fry?"
            };
            using (var svc = new JsonServiceClient("http://localhost:40300/"))
            {
                var knockstr = knock.SerializeToString();
                svc.Post(new KnockPost { Knock = knock });
            }
            //svc.Any(new KnockPost {Knock = knock});

            Console.WriteLine(knock.Id);
        }
        public void GetBicyclesWithSeedData()
        {
            List<Bicycle> bicycles = null;
            "Given the seed data is created"
                .Given(() => { });

            "When a GET bicycles request is made using admin credentials"
                .When(() =>
                {
                    var restClient = new JsonServiceClient(BaseUrl);

                    restClient.Send(new Auth
                    {
                        provider = CredentialsAuthProvider.Name,
                        UserName = "[email protected]",
                        Password = "admin",
                        RememberMe = true,
                    });

                    bicycles = restClient.Get(new GetBicycles());
                });

            "Then the response is not null."
                .Then(() =>
                {
                    Assert.NotNull(bicycles);
                });

            "And 4 bicycles are returned."
                .Then(() =>
                {
                    Assert.Equal(4, bicycles.Count);
                });
        }
Example #30
0
        private void getResourceButton_Click(object sender, EventArgs e) {
            var sb = new StringBuilder();

            // Create the ServiceStack API client and the request DTO
            var apiClient = new JsonServiceClient(resourceUriTextBox.Text);
            var apiRequestDto = new Users { Username = usernameTextBox.Text };

            // Wire up the ServiceStack client filter so that DotNetOpenAuth can 
            // add the authorization header before the request is sent
            // to the API server
            apiClient.LocalHttpWebRequestFilter = request => {

                // This is the magic line that makes all the client-side magic work :)
                ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text);

                LogStuff(request, sb);
            };
            // This filter is used only for logging the response output. The code will work without it.
            apiClient.LocalHttpWebResponseFilter += response => LogStuff(response, sb);

            try {
                // Send the API request and dump the response to our output TextBox
                var response = apiClient.Get(apiRequestDto);
                LogStuff(response, sb);
            } catch (WebServiceException ex) {
                sb.AppendLine(ex.Dump());
                sb.AppendLine(ex.ResponseBody.Replace(" at ", Environment.NewLine + "   at "));
            } catch (Exception ex) {
                sb.AppendLine(ex.Message);
            }
            outputTextBox.Text = sb.ToString();
        }