private void FillUserInfo() { JsonServiceClient client = new JsonServiceClient(ConfigurationManager.AppSettings["Client"]); var cafes = client.Get(new UserRequest { Id = 1 }); foreach (var item in cafes.Result) { txtUserName.Text = $"{item.FullName}"; txtUserPhoneNo.Text = $"{item.PhoneNo}"; txtUserEmail.Text = $"{item.Email}"; txtUpdateUserName.Text = $"{item.FullName}"; txtUpdateUserPhoneNo.Text = $"{item.PhoneNo}"; txtUpdateEmail.Text = $"{item.Email}"; } }
public void InitFromDataBase(JsonServiceClient ServiceClient) { ////query is directly written- table, column namesa are given explicitly in query (only for postgre) var result = ServiceClient.Get <GetQuestionsBankResponse>(new GetQuestionsBankRequest { }); if (result.Questionlst.Count > 0) { this.OptionHtml = string.Empty; foreach (var dct in result.Questionlst) { EbQuestion qstn = EbSerializers.Json_Deserialize <EbQuestion>(dct.Value); var ctlHtml = qstn.GetHtml(); this.QuestionBankList.Add(dct.Key, qstn); this.QuestionBankCtlHtmlList.Add(dct.Key, ctlHtml); this.OptionHtml += $"<option value='{dct.Key}'>{qstn.Name}</option>"; } } }
// Call: /Archives/edgar/data/<CIK>/<Submission Access Number>/<File Name> public SubmissionFile ArchivesEdgarDataCIKSubmissionFile(string cik, string accessNumber, string fileName) { AvoidBlocking(); string Command = "/Archives/edgar/data/{0}/{1}/{2}"; SubmissionFile submission = null; using (var client = new JsonServiceClient(BaseURL)) { string request = string.Format(Command, cik, accessNumber, fileName); byte[] fileContent = client.Get <byte[]>(request); submission = Convert(fileName, fileContent); } return(submission); }
public void Login_ThrowsException_When_InvalidPassword() { try { var client = new JsonServiceClient(ListeningOn); var saltResponse = client.Get(new SaltRequest { Username = Username }); client.Post(new LoginRequest { Username = Username, Password = HashUtility.Hash("Wrong", saltResponse.Salt) }); Assert.Fail("Shouldn't come here"); } catch (WebServiceException webEx) { Assert.That((HttpStatusCode)webEx.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); } }
public IHttpResult Get(DiagnosticoInfoPdf request) { using (var client = new JsonServiceClient(AppConfig.PhantonjApiUrl)){ try{ var httpResponse = client.Get <HttpWebResponse>(new OpenShift.Model.DiagnosticoInfoPdf { Id = request.Id, Norma = request.Norma }); var responseStream = httpResponse.GetResponseStream(); var cd = new System.Net.Mime.ContentDisposition { Inline = true }; Response.AddHeader("Content-Disposition", cd.ToString()); return(new HttpResult(responseStream, httpResponse.ContentType)); } catch (Exception e) { return(new HttpError(e.Message)); } } }
public void WhenGetDoctorAfterAddingToClinic_ThenReturnsDoctor() { var client = new JsonServiceClient(ServiceUrl); var clinic = RegisterClinic(client); var doctor = client.Post(new RegisterDoctorRequest { ClinicId = clinic.Id, FirstName = "afirstname", LastName = "alastname" }).Doctor; var doctors = client.Get(new SearchAvailableDoctorsRequest()).Doctors; doctors.First().Id.Should().Be(doctor.Id); doctors.First().Name.FirstName.Should().Be("afirstname"); doctors.First().Name.LastName.Should().Be("alastname"); }
public override List <PatientNote> Visit(ref List <PatientNote> result) { //[Route("/{Context}/{Version}/{ContractNumber}/Patient/{PatientId}/Notes/{Count}", "GET")] IRestClient client = new JsonServiceClient(); var url = Helper.BuildURL(string.Format("{0}/{1}/{2}/{3}/Patient/{4}/Notes/{5}", DDPatientNoteUrl, "NG", Version, ContractNumber, PatientId, Count), UserId); GetAllPatientNotesDataResponse ddResponse = client.Get <GetAllPatientNotesDataResponse>(url); if (ddResponse == null || ddResponse.PatientNotes == null || ddResponse.PatientNotes.Count <= 0) { return(result); } List <PatientNoteData> dataList = ddResponse.PatientNotes; result = dataList.Select(n => new PatientNote { Id = n.Id, PatientId = n.PatientId, Text = n.Text, ProgramIds = n.ProgramIds, CreatedOn = n.CreatedOn, CreatedById = n.CreatedById, TypeId = n.TypeId, MethodId = n.MethodId, OutcomeId = n.OutcomeId, WhoId = n.WhoId, SourceId = n.SourceId, Duration = n.Duration, ValidatedIdentity = n.ValidatedIdentity, ContactedOn = n.ContactedOn, UpdatedById = n.UpdatedById, UpdatedOn = n.UpdatedOn, DataSource = n.DataSource }).ToList(); return(result); }
public void GetRecentPatientsForAContact_Test() { string contractNumber = "InHealth001"; double version = 1.0; string token = "53750ca2d6a4850854d33c42"; string contactId = "5325c821072ef705080d3488"; JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("Token: {0}", token)); IRestClient client = new JsonServiceClient(); //[Route("/{Version}/{ContractNumber}/Patient/{Id}/Delete", "POST")] GetRecentPatientsResponse response = client.Get <GetRecentPatientsResponse>( string.Format(@"http://localhost:888/Nightingale/{0}/{1}/Contact/{2}/RecentPatients", version, contractNumber, contactId)); Assert.IsNotNull(response.Limit); }
public void Get_PatientProblems() { string url = "http://localhost:8888/PatientObservation"; string patientId = "5325da6fd6a4850adcbba63e"; string contractNumber = "InHealth001"; string context = "NG"; double version = 1.0; string userId = "531f2df9072ef727c4d2a3df"; IRestClient client = new JsonServiceClient(); JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("{0}: {1}", "x-Phytel-UserID", userId)); // /{Context}/{Version}/{ContractNumber}/Patient/{PatientId}/Observation// GetPatientProblemsSummaryResponse response = client.Get <GetPatientProblemsSummaryResponse>( string.Format("{0}/{1}/{2}/{3}/Patient/{4}/Observation/Problems?UserId={5}", url, context, version, contractNumber, patientId, userId)); Assert.AreEqual(string.Empty, string.Empty); }
public void Does_log_Service_request() { var client = new JsonServiceClient(Config.ListeningOn) { RequestFilter = req => req.Referer = Config.ListeningOn }; var response = client.Get(new RequestLogsTest { Name = "foo1" }); var json = Config.ListeningOn.CombineWith("requestlogs").GetJsonFromUrl(); var requestLogs = json.FromJson <RequestLogsResponse>(); var requestLog = requestLogs.Results.First(); var request = (RequestLogsTest)requestLog.RequestDto; Assert.That(request.Name, Is.EqualTo("foo1")); Assert.That(requestLog.Referer, Is.EqualTo(Config.ListeningOn)); }
public void Get_PatientObservationByID() { string url = "http://localhost:8888/PatientObservation"; string ObservationID = "533ed16ed4332307bc592bb8"; string patientId = "5325da03d6a4850adcbba4fe"; string contractNumber = "InHealth001"; string context = "NG"; double version = 1.0; string userId = "531f2df9072ef727c4d2a3df"; IRestClient client = new JsonServiceClient(); JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("{0}: {1}", "x-Phytel-UserID", userId)); GetPatientObservationResponse response = client.Get <GetPatientObservationResponse>( string.Format("{0}/{1}/{2}/{3}/Patient/{4}/Observation/{5}?UserId={6}", url, context, version, contractNumber, patientId, ObservationID, userId)); Assert.AreEqual(string.Empty, string.Empty); }
public void GetAllCohorts_Test() { // Arrange double version = 1.0; string contractNumber = "InHealth001"; string context = "NG"; IRestClient client = new JsonServiceClient(); JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("{0}: {1}", "x-Phytel-UserID", "531f2df9072ef727c4d2a3df")); // Act GetAllCohortsDataResponse response = client.Get <GetAllCohortsDataResponse> (string.Format("{0}/{1}/{2}/{3}/cohorts", "http://localhost:8888/Cohort/", context, version, contractNumber)); // Assert Assert.AreNotEqual(0, response.Cohorts.Count); }
private void PopulateDataSources() { IServiceClient client = new JsonServiceClient(CacheHelper.SERVICESTACK_URL).WithCache(); var fr = client.Get <EbObjectResponse>(string.Format("{0}/ebo?format=json", CacheHelper.SERVICESTACK_URL)); cmbEbDataSource.DisplayMember = "Name"; cmbEbDataSource.ValueMember = "Id"; cmbEbDataSource.BeginUpdate(); foreach (EbObjectWrapper dr in fr.Data) { if (dr.EbObjectType == EbObjectType.DataSource) { cmbEbDataSource.Items.Add(dr); } } cmbEbDataSource.EndUpdate(); }
public ActionResult Display(string reportNum, string customId) { tab_xc_reportModel model = new tab_xc_reportModel(); var client = new JsonServiceClient(GetSceneDataUrl); var response = client.Get(new XCGetSysprimaryByReportNum() { customId = customId, reportNum = reportNum }); if (response.IsSucc) { model.sysprimarykey = response.SysPrimaryKey; } return(Content(model.ToJson())); }
private static void Main() { var client = new JsonServiceClient("http://localhost:9090/requests"); var presentRequest = new PresentRequest { Id = Guid.NewGuid(), Address = new Address { Country = "sheldonopolis", }, Wish = "Could you please help developers to understand, " + "WCF is awesome only with Nelibur" }; client.Post(presentRequest); var requestQuery = new PresentRequestQuery { Country = "sheldonopolis", Status = PresentRequestStatus.Pending.ToString() }; List <PresentRequest> pendingRequests = client.Get <List <PresentRequest> >(requestQuery); Console.WriteLine("Pending present requests count: {0}", pendingRequests.Count); var updatePresentRequestStatus = new UpdatePresentRequestStatus { Status = PresentRequestStatus.Accepted.ToString() }; client.Post(updatePresentRequestStatus); var deleteByStatus = new DeletePresentRequestsByStatus { Status = PresentRequestStatus.Accepted.ToString() }; client.Delete(deleteByStatus); Console.WriteLine("Press any key for Exit"); Console.ReadKey(); }
public void Login_Succeed_When_CorrectCredentials() { try { var client = new JsonServiceClient(ListeningOn); var saltResponse = client.Get(new SaltRequest { Username = Username }); var loginResponse = client.Post(new LoginRequest { Username = Username, Password = HashUtility.Hash(Password, saltResponse.Salt) }); Assert.That(loginResponse.Result, Is.Not.Empty); } catch (WebServiceException webEx) { Assert.Fail("Shouldn't come here"); } }
static void Main(string[] args) { var appHost = new AppHost(); appHost.Init(); Console.WriteLine("JSON"); using (var client = new JsonServiceClient("http://localhost:1337/")) { var request = new GetAdvertisements { Skip = 0, Take = 7, }; var response = client.Get(request); Console.WriteLine(response.Items.Dump()); } Console.WriteLine("MsgPack"); using (var client = HostContext.Resolve <IMsgPackBackendServiceClient>()) { var request = new GetAdvertisements { Skip = 0, Take = 7 }; var response = client.Get(request); Console.WriteLine(response.Items.Dump()); } Console.WriteLine("Wire"); using (var client = HostContext.Resolve <IWireBackendServiceClient>()) { var request = new GetAdvertisements { Skip = 0, Take = 7 }; var response = client.Get(request); Console.WriteLine(response.Items.Dump()); } Console.ReadKey(); }
public void Can_return_response_when_no_failed_validations_and_TreatInfoAndWarningsAsErrors_set_false() { using (var appHost = new TestAppHost()) { appHost.Plugins.Add(new ValidationFeature { TreatInfoAndWarningsAsErrors = false }); appHost.Init(); appHost.Start(Urlbase); var sc = new JsonServiceClient(Urlbase); var resp = sc.Get(new EchoRequest { Day = "Monday", Word = "Word" }); Assert.That(resp.ResponseStatus, Is.Null); } }
public void Get_Additional_PatientObservation_Systolic_BP_Test() { string contractNumber = "InHealth001"; string context = "NG"; double version = 1.0; string token = "5317440bd6a4850c20c998a2"; string patientId = "52f5586e072ef709f84e65fd"; string typeId = "53067453fe7a591a348e1b66"; string observationId = "530c270afe7a592f64473e38"; // diastolic BP IRestClient client = new JsonServiceClient(); GetAdditionalObservationItemResponse response = client.Get <GetAdditionalObservationItemResponse>( string.Format(@"http://localhost:888/Nightingale/{0}/{1}/Patient/{2}/Observation/{3}?Token={4}", version, contractNumber, patientId, observationId, token)); }
public PatientGoal GetOpenNotMetPatientGoalByTemplateId(string sid, string patientId, string userId, IAppDomainRequest req) { //PatientGoal pg = new PatientGoal //{ // StatusId = 1, // Name = "test patient goal", // Id = "123456789012345612345678", // PatientId = "5325da9ed6a4850adcbba6ce" //}; //return pg; try { var request = new GetGoalDataRequest(); IRestClient client = new JsonServiceClient(); //"/{Context}/{Version}/{ContractNumber}/Patient/{PatientId}/Goal/" var url = Helper.BuildURL(string.Format(@"{0}/{1}/{2}/{3}/Patient/{4}/Goal/?TemplateId={5}", "http://localhost:8888/PatientGoal", "NG", req.Version, req.ContractNumber, "5424628084ac050e3806e8e2", "545a91a1fe7a59218cef2d6d"), userId); var response = client.Get <GetPatientGoalByTemplateIdResponse>(url); if (response == null) { throw new Exception("Patient goal was not found."); } var goal = Mapper.Map <PatientGoal>(response.GoalData); //var patientGoal = Mapper.Map<Goal>(response.GoalData); //new Goal(); return(goal); } catch (Exception ex) { throw new Exception("AD:PlanElementEndpointUtil:GetGoalById()::" + ex.Message, ex.InnerException); } }
private static void Main() { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; // PerformanceTest(); var client = new JsonServiceClient(Settings.Default.ServiceAddress); var createRequest = new CreateClientRequest { Email = "*****@*****.**" }; var response = client.Post <ClientResponse>(createRequest); Console.WriteLine("POST Response: {0}\n", response); var updateRequest = new UpdateClientRequest { Email = "*****@*****.**", Id = response.Id }; response = client.Put <ClientResponse>(updateRequest); Console.WriteLine("PUT Response: {0}\n", response); var getClientRequest = new GetClientRequest { Id = response.Id, Date = DateTime.Now.Date }; response = client.Get <ClientResponse>(getClientRequest); Console.WriteLine("GET Response: {0}\n", response); var deleteRequest = new DeleteClientRequest { Id = response.Id }; client.Delete(deleteRequest); Console.ReadKey(); }
/// <summary> /// 获取桩基检测方案信息 /// </summary> /// <param name="request"></param> /// <returns></returns> public GetZJCheckListResponse GetZJCheck(GetZJCheckList model) { var client = new JsonServiceClient(GetSceneDataUrl); GetZJCheckList request = new GetZJCheckList() { CheckUnitName = model.CheckUnitName, CheckEquip = model.CheckEquip, CheckPeople = model.CheckPeople, Area = model.Area, Report = model.Report, ZX = model.ZX, posStart = model.posStart, count = model.count, ProjectName = model.ProjectName, StartDate = model.StartDate, EndDate = model.EndDate }; return(client.Get(request)); }
public override Gateway.GetPartnerInfoResponse GetPartnerInfo(Gateway.GetPartnerInfoRequest request) { Logger.BeginRequest("GetPartnerInfo sent to " + name, request); JsonServiceClient client = new JsonServiceClient(RootUrl); GatewayService.PartnersResponse resp = client.Get <GatewayService.PartnersResponse>(new GatewayService.Partners { access_token = AccessToken, }); Gateway.GetPartnerInfoResponse response = new Gateway.GetPartnerInfoResponse { fleets = resp.Fleets, vehicleTypes = resp.VehicleTypes, result = resp.ResultCode }; Logger.EndRequest(response); return(response); }
private void cbxId_SelectionChanged(object sender, SelectionChangedEventArgs e) { JsonServiceClient client = new JsonServiceClient(ConfigurationManager.AppSettings["Client"]); var cafes = client.Get(new CafeRequest { Id = (int)cbxId.SelectedItem }); foreach (var item in cafes.Result) { txtName.Text = item.Name; txtPhoneNo.Text = item.PhoneNo; cbxZipCode.SelectedValue = item.Zip; txtAddress.Text = item.Address; txtDescription.Text = item.Description; cbxType.SelectedValue = item.Type; cbxOpenTime.SelectedValue = item.OpenTime; cbxCloseTime.SelectedValue = item.CloseTime; } }
public ActionResult GetSysPrimaryKey(string customId, string reportNum) { LiftingEquipmentGetSysPrimaryKeyModel model = new LiftingEquipmentGetSysPrimaryKeyModel(); var client = new JsonServiceClient(GetSceneDataUrl); var response = client.Get(new GetSysprimaryByReportNum() { customId = customId, reportNum = reportNum }); if (response.IsSucc) { model.sysPrimaryKey = response.SysPrimaryKey; } return(Content(model.ToJson())); }
public void Action_Get_Performance() { var client = new JsonServiceClient(AcDomain.NodeHost.Nodes.ThisNode.Node.AnycmdApiAddress); for (int i = 0; i < 1000; i++) { var request = new Message { MessageId = System.Guid.NewGuid().ToString(), Version = "v1", Verb = "Get", MessageType = "action", IsDumb = false, Ontology = "JS", Body = new BodyData(new KeyValueBuilder().Append("Id", Guid.NewGuid().ToString()).ToArray(), null), TimeStamp = DateTime.UtcNow.Ticks }.JspxToken(); var response = client.Get(request); } }
public void GetAllowedObservationStates_Test() { string contractNumber = "InHealth001"; string context = "NG"; double version = 1.0; string token = "534406e6d6a48508c45b62e0"; string type = "Lab"; IRestClient client = new JsonServiceClient(); JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("Token: {0}", token)); //GET /{Version}/{ContractNumber}/Observation/States/{TypeName} GetAllowedStatesResponse response = client.Get <GetAllowedStatesResponse>( string.Format(@"http://localhost:888/Nightingale/{0}/{1}/Observation/States/{2}?Context={3}", version, contractNumber, type, context)); Assert.IsNotNull(response.States); }
public void Does_handle_304_NotModified_Response() { var client = new JsonServiceClient(BaseUrl); try { var response = client.Get(new EchoCustomResponse { StatusCode = (int)HttpStatusCode.NotModified, StatusDescription = "NotModified", Body = "NOT MODIFIED" }); Assert.Fail("304 Throws"); } catch (WebServiceException ex) { Assert.That(ex.ErrorCode, Is.EqualTo("NotModified")); } }
public void Get_AllActivePrograms() { string url = "http://localhost:8888/Program"; string contractNumber = "InHealth001"; string context = "NG"; double version = 1.0; IRestClient client = new JsonServiceClient(); JsonServiceClient.HttpWebRequestFilter = x => x.Headers.Add(string.Format("{0}: {1}", "x-Phytel-UserID", "531f2df9072ef727c4d2a3df")); GetAllActiveProgramsResponse response = client.Get <GetAllActiveProgramsResponse>( string.Format("{0}/{1}/{2}/{3}/Programs/Active", url, context, version, contractNumber)); //Assert.AreEqual(ProgramID, response.Program.ProgramID); }
public void Does_call_OnExceptionAsync_on_Error() { var client = new JsonServiceClient(Config.ListeningOn); var request = new HelloFilter { Name = nameof(HelloFilter), Throw = true, }; try { var response = client.Get(request); Assert.Fail("Should throw"); } catch (WebServiceException webEx) { Assert.That(webEx.Message, Is.EqualTo($"{request.Name} OnBeforeExecute OnExceptionAsync")); } }
public void RunTests() { string username = "******"; string passHash = MD5Helper.CalculateMD5Hash("password"); JsonServiceClient client = new JsonServiceClient(SystemConstants.WebServiceBaseURL); Login(client, username, passHash); client.Get<XamarinEvolveSSLibrary.UserResponse>("User"); Logout(client); client.Get<XamarinEvolveSSLibrary.UserResponse>("User"); Login(client, username, passHash); User user = new User() { UserName = username, City = "changedtown", Email = "*****@*****.**" }; client.Post<XamarinEvolveSSLibrary.UserResponse>("User", user); Logout(client); client.Post<XamarinEvolveSSLibrary.UserResponse>("User", user); }
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 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); } }
public void UseSameRestClientError() { var restClient = new JsonServiceClient(BaseUrl); var errorList = restClient.Get<ErrorCollectionResponse>("error"); Assert.That(errorList.Result.Count, Is.EqualTo(1)); var error = restClient.Get<ErrorResponse>("error/Test"); Assert.That(error, !Is.Null); }
private static void Main() { const string serverPath = "http://localhost/"; var client = new JsonServiceClient(serverPath); var regions = client.Get(new Distilleries()); var distilleries = client.Get(new Distilleries {Region = regions[0].Region}); }
public void Does_create_correct_instances_per_scope() { var restClient = new JsonServiceClient(ListeningOn); var response1 = restClient.Get<IocScopeResponse>("iocscope"); var response2 = restClient.Get<IocScopeResponse>("iocscope"); Console.WriteLine(response2.Dump()); Assert.That(response2.Results[typeof(FunqSingletonScope).Name], Is.EqualTo(1)); Assert.That(response2.Results[typeof(FunqRequestScope).Name], Is.EqualTo(2)); Assert.That(response2.Results[typeof(FunqNoneScope).Name], Is.EqualTo(4)); }
public void Does_create_correct_instances_per_scope_with_exception() { FunqRequestScopeDepDisposableProperty.DisposeCount = 0; AltRequestScopeDepDisposableProperty.DisposeCount = 0; var restClient = new JsonServiceClient(ListeningOn); try { restClient.Get<IocScopeResponse>("iocscope?Throw=true"); } catch { } try { restClient.Get<IocScopeResponse>("iocscope?Throw=true"); } catch { } Assert.That(FunqRequestScopeDepDisposableProperty.DisposeCount, Is.EqualTo(2)); Assert.That(AltRequestScopeDepDisposableProperty.DisposeCount, Is.EqualTo(2)); }
private IEnumerable<SelectListItem> getCountries(JsonServiceClient client, Uri countriesEn) { var countriesResponse = client.Get<Api.Messages.CountriesResponse>(countriesEn.ToString()); return (countriesResponse != null && countriesResponse.ResponseStatus == null) ? countriesResponse.Countries.Select(c => new SelectListItem { Value = c.Alpha2_Code, Text = c.Name }) : Enumerable.Empty<SelectListItem>(); }
public void check_secured_get_requires_credentials() { var restClient = new JsonServiceClient(WebServerUrl); var error = Assert.Throws<WebServiceException>(() => restClient.Get<SecuredResponse>("/Secured/Ryan")); Assert.AreEqual("Unauthorized", error.Message); Assert.AreEqual((int)HttpStatusCode.Unauthorized, error.StatusCode); }
void Test11(JsonServiceClient client) { Console.WriteLine("~~~~~ FindUser (newuser3) ~~~~~~~~~"); UserResponse response = client.Get<XamarinEvolveSSLibrary.UserResponse>("User/newuser3"); Console.WriteLine("Expected null: " + response.Exception); Console.WriteLine(); }
// 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; }
public void CanPerform_PartialUpdate() { var client = new JsonServiceClient("http://localhost:53990/api/"); // back date for readability var created = DateTime.Now.AddHours(-2); // Create a record so we can patch it var league = new League() {Name = "BEFORE", Abbreviation = "BEFORE", DateUpdated = created, DateCreated = created}; var newLeague = client.Post<League>(league); // Update Name and DateUpdated fields. Notice I don't want to update DateCreatedField. // I also added a fake field to show it does not cause any errors var updated = DateTime.Now; newLeague.Name = "AFTER"; newLeague.Abbreviation = "AFTER"; // setting to after but it should not get updated newLeague.DateUpdated = updated; client.Patch<League>("http://localhost:53990/api/leagues/" + newLeague.Id + "?fields=Name,DateUpdated,thisFieldDoesNotExist", newLeague); var updatedLeague = client.Get<League>(newLeague); Assert.AreEqual(updatedLeague.Name, "AFTER"); Assert.AreEqual(updatedLeague.Abbreviation, "BEFORE"); Assert.AreEqual(updatedLeague.DateUpdated.ToString(), updated.ToString(), "update fields don't match"); Assert.AreEqual(updatedLeague.DateCreated.ToString(), created.ToString(), "created fields don't match"); // double check Assert.AreNotEqual(updatedLeague.DateCreated, updatedLeague.DateUpdated); }
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(); }
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); }
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)); }
private string getRawCountry(JsonServiceClient client, Uri countryEn) { // since contryEn does not include language, it is added to the header client.LocalHttpWebRequestFilter = h => h.Headers.Add(HttpRequestHeader.AcceptLanguage, "en"); var countryResponse = client.Get<string>(countryEn.ToString()); return countryResponse; }
public void Test_PostAndGetMessage() { // Create message var postRequest = new CreateMessage { ApplicationId = 1, Bcc = new[] { "*****@*****.**" }, Body = "This is a test email.", Cc = new[] { "*****@*****.**" }, Connection = new Connection { EnableSsl = false, Host = "localhost", Port = 25 }, Credential = new Credential(), From = "*****@*****.**", ReplyTo = new[] { "*****@*****.**" }, Sender = "*****@*****.**", Subject = "Test Message", To = new[] { "*****@*****.**" } }; 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(2, getResponse.Status.TypeMessageStatusId); Assert.Equal(postResponse.Id, getResponse.Id); }
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; } }
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 void do_unsecured_get() { var restClient = new JsonServiceClient(WebServerUrl); var response = restClient.Get<UnsecuredResponse>("/Unsecured/SomeData1"); Assert.IsNotNull(response); Assert.AreEqual("SomeData1", response.Result); }
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; }
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 = "******", Password = "******", 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); }); }
public void Can_call_Cached_WebService_with_JSON() { var client = new JsonServiceClient(Config.NServiceKitBaseUri); var response = client.Get<MoviesResponse>("/cached/movies"); Assert.That(response.Movies.Count, Is.EqualTo(ResetMoviesService.Top5Movies.Count)); }
static void Main(string[] args) { var client = new JsonServiceClient("http://localhost:54114/"); List<Player> players = client.Get(new GetPlayers()); players.ForEach(player => System.Console.WriteLine("Player {0} details: first name - {1}, last name - {2}", player.Id, player.FirstName, player.LastName)); System.Console.WriteLine("Press any key to continue ..."); System.Console.ReadLine(); }
public void Test_GET_empty_PASS() { var restClient = new JsonServiceClient(serviceUrl); var emps = restClient.Get<List<Employee>>("/employees"); Assert.NotNull(emps); Assert.Empty(emps); }
public void Can_call_CachedWithTimeout_and_Redis_WebService_with_JSON() { var client = new JsonServiceClient(Config.ServiceStackBaseUri); var response = client.Get<MoviesResponse>("/cached-timeout-redis/movies"); Assert.That(response.Movies.Count, Is.EqualTo(ResetMoviesService.Top5Movies.Count)); }
public void Can_authenticate_with_WindowsAuth() { var client = new JsonServiceClient(BaseUri); var response = client.Get(new RequiresAuth { Name = "Haz Access!" }); Assert.That(response.Name, Is.EqualTo("Haz Access!")); }
public static void Main(string[] args) { using (var client = new JsonServiceClient(address)) { var response = client.Send<LayerListResponse>(new LayerList() { LayerName = "123" }); var response2 = client.Get(new LayerList() { LayerName = "Abc" }); var response3 = client.Get(new LayerListAll()); } }
public void GetRequest() { var client = new JsonServiceClient(Config.ServiceStackBaseUri); client.Headers.Add("Foo","abc123"); var response = client.Get(new CustomHeaders()); Assert.That(response.Foo, Is.EqualTo("abc123")); Assert.That(response.Bar, Is.Null); }
public void Can_call_Cached_WebService_with_JSON_string() { var client = new JsonServiceClient(Config.ServiceStackBaseUri); var response = client.Get<string>("/cached-string/TEXT"); Assert.That(response, Is.EqualTo("TEXT")); }