protected static void Establish_context() { entity = ExchangeData.CreateBasicEntity(); mapping = new EnergyTrading.Mdm.Contracts.Mapping { SystemName = "Endur", Identifier = "Test", SourceSystemOriginated = false, DefaultReverseInd = true, StartDate = Script.baseDate, EndDate = Script.baseDate.AddDays(2) }; content = HttpContentExtensions.CreateDataContract(mapping); content2 = HttpContentExtensions.CreateDataContract(mapping); client = new HttpClient(); }
protected static void Establish_context() { entity = CurveData.CreateBasicEntityWithOneMapping(); currentTrayportMapping = entity.Mappings[0]; mapping = new Mapping { SystemName = currentTrayportMapping.System.Name, Identifier = currentTrayportMapping.MappingValue, SourceSystemOriginated = currentTrayportMapping.IsMaster, DefaultReverseInd = currentTrayportMapping.IsDefault, StartDate = currentTrayportMapping.Validity.Start, EndDate = currentTrayportMapping.Validity.Finish.AddDays(2) }; content = HttpContentExtensions.CreateDataContract(mapping); client = new HttpClient(); }
public static async Task <HttpResponseMessage> Start( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "StartFanOutFanIn")] HttpRequestMessage req, [DurableClient] IDurableClient starter, ILogger log) { int num = await HttpContentExtensions.ReadAsAsync <int>(req.Content); if (num <= 0) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "A positive integer was expected in the request body.")); } string instanceId = await starter.StartNewAsync("FanOutFanIn", (object)num); log.LogInformation("Started FanOutFanIn orchestration with ID = '" + instanceId + "'."); return(starter.CreateCheckStatusResponse(req, instanceId)); }
static Location UpdateLocation(HttpClient client, Location location) { Console.WriteLine("Updating location '{0}':", location.id); Console.WriteLine(); string updateUri = "Locations/" + location.id.ToString(); HttpContent content = HttpContentExtensions.CreateJsonDataContract(location); Console.WriteLine("Request"); WriteOutContent(content); using (HttpResponseMessage response = client.Put(updateUri, content)) { response.EnsureStatusIsSuccessful(); return(response.Content.ReadAsJsonDataContract <Location>()); } }
public ModelListSelectItemAndDefaultValue GetMoneyTypes(string url, int companyId) { ModelListSelectItemAndDefaultValue result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/moneytypeapi/GetSelect?companyId=" + companyId).Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <ModelListSelectItemAndDefaultValue>(result.Content).Result; return(result2); } catch (Exception) { } result2 = null; return(result2); }
public List <SMoneyType> GetMoneyTypes(string url) { List <SMoneyType> result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/moneytypeapi/GetMoneyTypes").Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <List <SMoneyType> >(result.Content).Result; return(result2); } catch (Exception) { } result2 = null; return(result2); }
public List <SUser> GetListUserWithoutExistsInList(string url, int[] existsUserIds, string keyWord, int searchBy, int startIndexRecord, int pageSize, string sorting, int companyId) { List <SUser> result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); string text = ""; for (int i = 0; i < existsUserIds.Length; i++) { text = text + "existsUserIds=" + existsUserIds[i]; if (i < existsUserIds.Length - 1) { text += "&"; } } object obj = text; text = string.Concat(new object[] { obj, "existsUserIds=0&&keyWord=", keyWord, "&&searchBy=", searchBy, "&&startIndexRecord=", startIndexRecord, "&&pageSize=", pageSize, "&&sorting=", sorting, "&&companyId=", companyId }); HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/AccountApi/GetListUserWithoutExistsInList?" + text).Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <List <SUser> >(result.Content).Result; return(result2); } catch (Exception) { } result2 = null; return(result2); }
public SCompany GetCompany(string url, int userId) { SCompany result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); string str = "userId=" + userId; HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/AccountApi/GetCompany?" + str).Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <SCompany>(result.Content).Result; return(result2); } catch (Exception) { } result2 = null; return(result2); }
static Task UpdateTask(HttpClient client, Task task) { Console.WriteLine("Updating task '{0}':", task.Id); Console.WriteLine(); string updateUri = "Tasks/" + task.Id.ToString(); HttpContent content = HttpContentExtensions.CreateJsonDataContract(task); Console.WriteLine("Request:"); WriteOutContent(content); using (HttpResponseMessage response = client.Put(updateUri, content)) { response.EnsureStatusIsSuccessful(); Console.WriteLine("Response:"); WriteOutContent(response.Content); return(response.Content.ReadAsJsonDataContract <Task>()); } }
public bool CheckStatusLogin(string url, string toKen) { bool result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); string str = "toKen=" + toKen; HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/AccountApi/CheckStatusLogin?" + str).Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <bool>(result.Content).Result; return(result2); } catch (Exception) { } result2 = false; return(result2); }
public List <SUser> GetUsers(string url, int companyId) { List <SUser> result2; try { AccountApi.AccountClient.BaseAddress = new Uri(url); string str = "companyId=" + companyId; HttpResponseMessage result = AccountApi.AccountClient.GetAsync("api/AccountApi/GetUsers?" + str).Result; result.EnsureSuccessStatusCode(); result2 = HttpContentExtensions.ReadAsAsync <List <SUser> >(result.Content).Result; return(result2); } catch (Exception) { } result2 = null; return(result2); }
public void PostMoviesWithInvalidAuth() { string director = "Allen"; string title = "Annie Hall"; DateTime dateReleased = new DateTime(1977, 4, 30); client.DefaultHeaders.Add(psuedoAuthHeaderForPhil); Movie movieToInsert = new Movie() { Director = director, DateReleased = dateReleased, Title = title }; using (HttpResponseMessage response = client.Post("AuthHome/create", HttpContentExtensions.CreateJsonDataContract(movieToInsert))) { Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); } client.DefaultHeaders.Remove(psuedoAuthHeaderForPhil); }
/// <summary> /// Authenticates the by GUID. /// </summary> /// <param name="uri">The URI.</param> /// <param name="securityToken">The security token.</param> private static HttpClient AuthenticateByGuid(string uri, string securityToken) { const string SESSION_ID = "ASP.Net_SessionId"; const string UserGuid = "UserGuid"; //Stores the sessionid generated and returned by the server string sessionId = string.Empty; HttpResponseMessage httpResp = null; HeaderValues <Cookie> myCookies; HttpClient httpClient = new HttpClient(); httpClient.DefaultHeaders.Add(UserGuid, securityToken); httpResp = httpClient.Post(uri, HttpContentExtensions.CreateXmlSerializable(string.Empty)); if (!httpResp.IsStatusIsSuccessful()) { throw new EVException().AddHttpResponse(httpResp); } myCookies = httpResp.Headers.SetCookie; if (myCookies != null) { foreach (Cookie var in myCookies.Where(var => var.ContainsKey(SESSION_ID))) { // -- set the session ID sessionId = var[SESSION_ID]; break; } } Cookie objCookie = new Cookie(); objCookie.Add(Constants.EvolutionCookieName, sessionId); // -- set the cookie in the header httpClient.DefaultHeaders.Cookie.Add(objCookie); //Add authorization header Credential evcredential = new Credential(); evcredential.Parameters.Add(sessionId); httpClient.DefaultHeaders.Authorization = evcredential; httpClient.TransportSettings.ConnectionTimeout = TimeSpan.FromMinutes(60); httpClient.TransportSettings.ReadWriteTimeout = TimeSpan.FromMinutes(60); return(httpClient); }
public Task <string> GetGadosByID(int id) { using (HttpClient cli = new HttpClient()) { String petition = "/Services/CategoriaOficialService.svc/ObterPorEstadoFazenda/2" + id; cli.BaseAddress = new Uri(this.WebApi); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(mediaheader); HttpResponseMessage myObject = await client.GetAsync(petition); if (retorno.IsSuccessStatusCode) { Gados c = await HttpContentExtensions.ReadAsAsync(myObject.Content); return(c); } else { return(null); } } }
protected static void Establish_context() { client = new HttpClient(); entity = Script.PersonData.CreateBasicEntityWithOneMapping(); var getResponse = client.Get(ServiceUrl["Person"] + entity.Id); person = getResponse.Content.ReadAsDataContract <EnergyTrading.MDM.Contracts.Sample.Person>(); mappingId = person.Identifiers.Where(x => !x.IsMdmId).First(); var mappingGetResponse = client.Get(ServiceUrl["Person"] + person.NexusId() + "/mapping/" + mappingId.MappingId); var mapping_etag = mappingGetResponse.Headers.ETag; var mappingFromService = mappingGetResponse.Content.ReadAsDataContract <MappingResponse>(); MdmId postMapping = mappingFromService.Mappings[0]; newEndDate = mappingFromService.Mappings[0].EndDate.Value.AddDays(1); postMapping.EndDate = newEndDate; var content = HttpContentExtensions.CreateDataContract(postMapping); client.DefaultHeaders.Add("If-Match", mapping_etag != null ? mapping_etag.Tag : string.Empty); mappingUpdateResponse = client.Post(ServiceUrl["Person"] + string.Format("{0}/Mapping/{1}", entity.Id, mappingFromService.Mappings[0].MappingId), content); }
public void EnsureKeyCanAccessPackages(IEnumerable <string> packageIds, string key) { using (IHttpClient client = _httpClientAdapter.GetHttpClient(_configSettings.FrontEndWebSiteRoot)) { string uri = string.Format("{0}/{1}", _configSettings.AuthorizePackageIdsUri, key); HttpContent content = HttpContentExtensions.CreateJsonDataContract(packageIds); using (HttpResponseMessage response = client.Post(uri, content)) { if (response.StatusCode != HttpStatusCode.OK) { _logger.Error("External call returned non-OK status of '{0}'. Authorization for Packages failed.", response.StatusCode); throw new Exception("An error occurred when trying to authorize access to PackagesIds."); } bool accessAllowed; if (!bool.TryParse(response.Content.ReadAsString(), out accessAllowed) || !accessAllowed) { _logger.Error("The given userkey was refused access one or more of the given Package IDs."); throw new PackageAuthorizationException(); } } } }
public void EditMoviesWithoutAuth() { string director = "Crichton"; string title = "A Fish Called Wanda"; DateTime dateReleased = new DateTime(1988, 7, 15); Movie movieToEdit; using (HttpResponseMessage response = client.Get("AuthHome/details/1", "application/json")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); movieToEdit = response.Content.ReadAsJsonDataContract <Movie>(); } movieToEdit.DateReleased = dateReleased; movieToEdit.Director = director; movieToEdit.Title = title; using (HttpResponseMessage response = client.Put("AuthHome/edit/1", HttpContentExtensions.CreateJsonDataContract(movieToEdit))) { Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); } }
protected static void Establish_context() { repository = new DbSetRepository(new DbContextProvider(() => new NexusMappingContext())); foreach (var rd in repository.Queryable <MDM.ReferenceData>()) { repository.Delete(rd); } referenceDataList = new List <EnergyTrading.Mdm.Contracts.ReferenceData>() { new EnergyTrading.Mdm.Contracts.ReferenceData() { Value = "test1" }, new EnergyTrading.Mdm.Contracts.ReferenceData() { Value = "test1" } }; content = HttpContentExtensions.CreateDataContract(referenceDataList); client = new HttpClient(); }
public void WhenContentIsNull_ThenThrowException() { Assert.ThrowsAsync <ArgumentNullException>(() => HttpContentExtensions.ReadAsJsonAsync <TestDummy>(null)); }
public void CrudMoviesXml() { string director = "Nichols"; string title = "The Graduate"; DateTime dateReleased = new DateTime(1967, 12, 21); List <Movie> originalMovieList; List <Movie> updatedMovieList; client.DefaultHeaders.Add(psuedoAuthHeaderForBob); using (HttpResponseMessage response = client.Get("AuthHome", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); originalMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie movieToInsert = new Movie() { Director = director, DateReleased = dateReleased, Title = title }; using (HttpResponseMessage response = client.Post("AuthHome/create", HttpContentExtensions.CreateDataContract(movieToInsert))) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.Equals(movieToInsert, insertedMovie)); dateReleased = new DateTime(1997, 2, 14); // US re-release date insertedMovie.DateReleased = dateReleased; using (HttpResponseMessage response = client.Put("AuthHome/Edit/" + insertedMovie.Id.ToString(), HttpContentExtensions.CreateDataContract(insertedMovie))) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie updatedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.Equals(insertedMovie, updatedMovie)); using (HttpResponseMessage response = client.Delete("AuthHome/delete/" + insertedMovie.Id.ToString())) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Assert.IsTrue(updatedMovieList.Union(originalMovieList, moviesComparer).Count() == updatedMovieList.Count()); client.DefaultHeaders.Remove(psuedoAuthHeaderForBob); }
public void CrudMoviesJson() { string director = "Donen"; string title = "Singin' in the Rain"; DateTime dateReleased = new DateTime(1952, 4, 11); List <Movie> originalMovieList; List <Movie> updatedMovieList; client.DefaultHeaders.Add(psuedoAuthHeaderForBob); using (HttpResponseMessage response = client.Get("AuthHome", "application/json")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); originalMovieList = response.Content.ReadAsJsonDataContract <List <Movie> >(); } Movie movieToInsert = new Movie() { Director = director, DateReleased = dateReleased, Title = title }; using (HttpResponseMessage response = client.Post("AuthHome/create", HttpContentExtensions.CreateJsonDataContract(movieToInsert))) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/json")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <Movie> >(); } Movie insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.Equals(movieToInsert, insertedMovie)); director = "Kelly"; // multiple director credits insertedMovie.Director = director; using (HttpResponseMessage response = client.Put("AuthHome/Edit/" + insertedMovie.Id.ToString(), HttpContentExtensions.CreateJsonDataContract(insertedMovie))) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/json")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <Movie> >(); } Movie updatedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.Equals(insertedMovie, updatedMovie)); using (HttpResponseMessage response = client.Delete("AuthHome/delete/" + insertedMovie.Id.ToString())) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("AuthHome", "application/json")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <Movie> >(); } Assert.IsTrue(updatedMovieList.Union(originalMovieList, moviesComparer).Count() == updatedMovieList.Count()); client.DefaultHeaders.Remove(psuedoAuthHeaderForBob); }
public static bool ValidateLicense(License localLicense) { bool flag; try { HttpClient httpClient = LicenseHelper.\u202A(); label_2: int num1 = -1801571015; while (true) { int num2 = -1698105259; uint num3; string str; HttpResponseMessage result1; License result2; int num4; switch ((num3 = (uint)(num1 ^ num2)) % 18U) { case 0: flag = true; num1 = -87800919; continue; case 1: num1 = (int)num3 * 2008935587 ^ 1948716983; continue; case 2: if (result2.DateExpires == localLicense.DateExpires) { num1 = (int)num3 * -928711233 ^ 126615497; continue; } break; case 3: num4 = LicenseHelper.\u206A(result2.RequestToken, localLicense.RequestToken) ? 1 : 0; goto label_7; case 4: flag = false; num1 = (int)num3 * 2103174008 ^ 200965616; continue; case 5: str = LicenseHelper.\u200E(\u003CModule\u003E.\u202A <string>(1955892746U), localLicense.Node); num1 = (int)num3 * -926792795 ^ -593743430; continue; case 6: result1 = LicenseHelper.\u200B(httpClient, str).get_Result(); int num5 = LicenseHelper.\u202B(result1) ? -909136120 : (num5 = -856464655); int num6 = (int)num3 * 572922087; num1 = num5 ^ num6; continue; case 7: result2 = ((Task <License>)HttpContentExtensions.ReadAsAsync <License>(LicenseHelper.\u202A(result1))).get_Result(); num1 = (int)num3 * -521139299 ^ -760603430; continue; case 8: goto label_2; case 9: goto label_14; case 11: if (LicenseHelper.\u206A(result2.Node, localLicense.Node)) { num1 = (int)num3 * -643669904 ^ 2014759194; continue; } break; case 12: if (LicenseHelper.\u206A(result2.Licensee, localLicense.Licensee)) { num1 = (int)num3 * -885431901 ^ 123726838; continue; } break; case 13: LicenseHelper.\u206B(LicenseHelper.\u202D(httpClient)).Add(LicenseHelper.\u200D(\u003CModule\u003E.\u206A <string>(1434096782U))); num1 = (int)num3 * 662115125 ^ -1550653239; continue; case 14: LicenseHelper.\u206D(httpClient, LicenseHelper.\u206E(LicenseHelper.LicenseServer)); num1 = (int)num3 * 1048253767 ^ 370377906; continue; case 15: num1 = -300986361; continue; case 16: num1 = (int)num3 * -751233102 ^ 1134372088; continue; default: goto label_25; } num4 = 0; label_7: int num7; num1 = num7 = num4 != 0 ? -761930627 : (num7 = -1727432170); } label_14: flag = true; } catch (Exception ex) { throw; } label_25: return(flag); }
private RestContent SendHttpRequest <T>( string url, RestRequest request, T objectToSend) where T : class { if (log.IsDebugEnabled) { log.DebugFormat( "Calling OE REST (operation='{0}', url='{1}')", request.Operation, url); } Uri requestUrl = new Uri(url); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = request.Operation.ToString(); webRequest.ContentType = "text/xml"; SetupWebRequest(webRequest); try { if (objectToSend != null) { using (Stream requestStream = webRequest.GetRequestStream()) { using (HttpContent httpContent = HttpContentExtensions.CreateXmlSerializable(objectToSend)) { if (log.IsDebugEnabled) { httpContent.LoadIntoBuffer(); log.DebugFormat("Sending XML: {0}", httpContent.ReadAsString()); } httpContent.WriteTo(requestStream); } } } using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { RaiseOERestExceptionIfNeeded(requestUrl, response); RestContent oecontent; oecontent = new RestContent( ReadResponseAsString(response), requestUrl); if (log.IsDebugEnabled) { log.DebugFormat("Response: '{0}'", oecontent.ContentString); } return(oecontent); } } catch (WebException ex) { if (ex.Response == null) { if (log.IsDebugEnabled) { log.Debug("ex.Response == null"); } string message = string.Format( CultureInfo.InvariantCulture, "The call to '{0}' failed", url); throw new RestException(requestUrl, message, ex); } RaiseOERestExceptionIfNeeded(requestUrl, (HttpWebResponse)ex.Response); throw; } catch (Exception ex) { string message = string.Format( CultureInfo.InvariantCulture, "Exception while calling '{0}'", url); log.Warn(message, ex); throw; } }
public void CrudMoviesXml() { string director = "Nichols"; string title = "The Graduate"; DateTime dateReleased = new DateTime(1967, 12, 21); List <Movie> originalMovieList; List <Movie> updatedMovieList; using (HttpResponseMessage response = client.Get("EdmMovies", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); originalMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie movieToInsert = new Movie() { Director = director, DateReleased = dateReleased, Title = title }; using (HttpResponseMessage response = client.Post("EdmMovies", HttpContentExtensions.CreateDataContract(movieToInsert))) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); Assert.IsTrue(response.Headers.Location.ToString().StartsWith("/MovieApp/EdmMovies/", StringComparison.OrdinalIgnoreCase)); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.EqualsIgnoreTimeSkew(movieToInsert, insertedMovie)); dateReleased = new DateTime(1997, 2, 14); // US re-release date insertedMovie.DateReleased = dateReleased; using (HttpResponseMessage response = client.Put("EdmMovies/" + insertedMovie.Id.ToString(), HttpContentExtensions.CreateDataContract(insertedMovie))) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Movie updatedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.EqualsIgnoreTimeSkew(insertedMovie, updatedMovie)); using (HttpResponseMessage response = client.Delete("EdmMovies/" + insertedMovie.Id.ToString())) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/xml")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >(); } Assert.IsTrue(updatedMovieList.Union(originalMovieList, moviesComparer).Count() == updatedMovieList.Count()); }
public void CrudMoviesJsonDC() { string director = "Donen"; string title = "Singin' in the Rain"; DateTime dateReleased = new DateTime(1952, 4, 11); List <MovieDC> originalMovieList; List <MovieDC> updatedMovieList; MovieDC.MoviesComparerDC moviesComparer = new MovieDC.MoviesComparerDC(); using (HttpResponseMessage response = client.Get("EdmMovies", "application/json2")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); originalMovieList = response.Content.ReadAsJsonDataContract <List <MovieDC> >(); } MovieDC movieToInsert = new MovieDC() { Director = director, DateReleased = dateReleased, Title = title }; using (HttpResponseMessage response = client.Post("EdmMovies", "application/json2", HttpContentExtensions.CreateJsonDataContract(movieToInsert))) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); Assert.IsTrue(response.Headers.Location.ToString().StartsWith("/MovieApp/EdmMovies/", StringComparison.OrdinalIgnoreCase)); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/json2")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <MovieDC> >(); } MovieDC insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.EqualsIgnoreTimeSkew(movieToInsert, insertedMovie)); director = "Kelly"; // multiple director credits insertedMovie.Director = director; using (HttpResponseMessage response = client.Put("EdmMovies/" + insertedMovie.Id.ToString(), "application/json2", HttpContentExtensions.CreateJsonDataContract(insertedMovie))) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/json2")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <MovieDC> >(); } MovieDC updatedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault(); Assert.IsTrue(moviesComparer.EqualsIgnoreTimeSkew(insertedMovie, updatedMovie)); using (HttpResponseMessage response = client.Delete("EdmMovies/" + insertedMovie.Id.ToString())) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } using (HttpResponseMessage response = client.Get("EdmMovies", "application/json2")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); updatedMovieList = response.Content.ReadAsJsonDataContract <List <MovieDC> >(); } Assert.IsTrue(updatedMovieList.Union(originalMovieList, moviesComparer).Count() == updatedMovieList.Count()); }
public async Task <FileAttachment> UploadFile(int serviceRequestId, FileAttachment fileAttachment) { FileAttachment uploadedFileAttachment = null; using (var client = new HttpClient()) { client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("app-jwt", this.jwt); client.DefaultRequestHeaders.TryAddWithoutValidation("api-key", this.api_key); client.BaseAddress = new Uri(this.baseURL); ByteArrayContent content = new ByteArrayContent(fileAttachment.Data); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); string subUrl = "file-attachments?serviceRequestId=" + serviceRequestId + "&filename=" + fileAttachment.EscapedName + "&contentType=application/octet-stream&size=" + fileAttachment.Size; try { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; System.Net.ServicePointManager.Expect100Continue = false; HttpResponseMessage response = client.PostAsync(subUrl, (HttpContent)content).GetAwaiter().GetResult(); if (response.StatusCode == HttpStatusCode.OK) { uploadedFileAttachment = await(Task <FileAttachment>) HttpContentExtensions.ReadAsAsync <FileAttachment>(response.Content); } if (response.StatusCode == HttpStatusCode.BadRequest) { uploadedFileAttachment = await(Task <FileAttachment>) HttpContentExtensions.ReadAsAsync <FileAttachment>(response.Content); uploadedFileAttachment.Name = fileAttachment.Name; uploadedFileAttachment.Id = -1; } response.EnsureSuccessStatusCode(); var status = response.StatusCode; } catch (WebException ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.InnerException); Debug.WriteLine(ex.StackTrace); } catch (HttpRequestException socketException) { Debug.WriteLine(socketException.Message); Debug.WriteLine(socketException.InnerException); Debug.WriteLine(socketException.StackTrace); throw new MtoaConnectionException("Unable to connect to MTOA services.", socketException); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.InnerException); Debug.WriteLine(ex.StackTrace); } return(uploadedFileAttachment); } }
private async Task <T> ReadAsAsyncWithAwaitConfiguration <T>(HttpContent httpContent) { return(await HttpContentExtensions.ReadAsAsync <T>(httpContent, (IEnumerable <MediaTypeFormatter>) _supportedFormatters).ConfigureAwait(false)); }
static async Task Main(string[] args) { args = new[] { "change", "-c", "87911003010" }; //args = new []{"helpDb"}; //args = new[] {"select", "-f", "phoneNumber", "-v", "11111"}; //args = new[] {"sort", "-f", "fullName", "-d", "false"}; //args = new[] {"change", "-p", "11111", "-c", "87911003010"}; //args = new[] {"delete", "-f", "phoneNumber", "-v", "00000"}; //args = new[] {"add", "-p", "00000", "-n", "name", "-e", "*****@*****.**", "--position", "ofdicer", "-a", "77, 733"}; //args = new []{"get"}; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:5479/api/database/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType.ApplicationJson)); await Parser.Default.ParseArguments <HelpOptions, InsertOptions, ChangeOptions, DeleteOptions, SelectOptions, SortOptions, GetOptions>(args) .MapResult(async(HelpOptions opts) => { Console.WriteLine("Database fields:" + Environment.NewLine + "phoneNumber" + Environment.NewLine + "fullName" + Environment.NewLine + "email" + Environment.NewLine + "positionalHeld" + Environment.NewLine + "additionalNumbers"); }, async(InsertOptions opts) => { var userInfo = new UsersInfo() { PhoneNumber = opts.PhoneNumber, FullName = opts.FullName, Email = opts.Email, PositionHeld = opts.PositionHeld, AdditionalNumbers = opts.AdditionalNumbers }; var content = new StringContent(JsonConvert.SerializeObject(userInfo), Encoding.UTF8, MediaType.ApplicationJson); var response = await client.PostAsync("insert-user", content); if (response.IsSuccessStatusCode) { Console.WriteLine("Successfully inserted"); } else { Console.WriteLine("Something went wrong"); } }, async(ChangeOptions opts) => { var userInfo = new UsersInfo() { PhoneNumber = opts.PhoneNumber, FullName = opts.FullName, Email = opts.Email, PositionHeld = opts.PositionHeld, AdditionalNumbers = opts.AdditionalNumbers, UserPhoneToChange = opts.UserPhoneToChange }; var content = new StringContent(JsonConvert.SerializeObject(userInfo), Encoding.UTF8, MediaType.ApplicationJson); var response = await client.PutAsync("change-user", content); if (response.IsSuccessStatusCode) { Console.WriteLine("Successfully changed"); } else { Console.WriteLine("Something went wrong"); } }, async(DeleteOptions opts) => { var deleteInfo = new DeleteInfo() { DeletedField = opts.DeletedField, DeletedValue = opts.DeletedValue }; ///здесь используется костыль(и не только), т.к. я узнал, что плохая практика передовать в deleteAsync тело запоса ///и нужно делать через url, уже когда написал всю логику и времени не осталось сделать нормально var request = new HttpRequestMessage { Method = HttpMethod.Delete, RequestUri = new Uri("delete-user", UriKind.Relative), Content = new StringContent(JsonConvert.SerializeObject(deleteInfo), Encoding.UTF8, MediaType.ApplicationJson) }; var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { Console.WriteLine("Successfully deleted"); } else { Console.WriteLine("Something went wrong"); } }, async(SelectOptions opts) => { var selectInfo = new SelectInfo { SelectConditionField = opts.SelectConditionField, SelectConditionValue = opts.SelectConditionValue }; var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("select-user", UriKind.Relative), Content = new StringContent(JsonConvert.SerializeObject(selectInfo), Encoding.UTF8, MediaType.ApplicationJson) }; var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var user = await HttpContentExtensions.ReadAsAsync <List <UsersInfo> >(response.Content); Console.WriteLine(string.Join(Environment.NewLine, user)); } else { Console.WriteLine("Something went wrong"); } }, async(SortOptions opts) => { var sortInfo = new SortInfo() { SortConditionField = opts.SortConditionField, IsDescending = opts.IsDescending }; var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("sort-user", UriKind.Relative), Content = new StringContent(JsonConvert.SerializeObject(sortInfo), Encoding.UTF8, MediaType.ApplicationJson) }; var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var user = await HttpContentExtensions.ReadAsAsync <List <UsersInfo> >(response.Content); Console.WriteLine(string.Join(Environment.NewLine, user)); } else { Console.WriteLine("Something went wrong"); } }, async(GetOptions opts) => { var response = await client.GetAsync("get-users"); if (response.IsSuccessStatusCode) { var user = await HttpContentExtensions.ReadAsAsync <List <UsersInfo> >(response.Content); Console.WriteLine(string.Join(Environment.NewLine, user)); } else { Console.WriteLine("Something went wrong"); } }, async errs => Console.WriteLine("Hello World!")); } }
/// <summary> /// A Get method to fetch the stream from the URI /// </summary> /// <typeparam name="TRequest">The Request Object to pass to</typeparam> /// <param name="httpMethod">HTTP Method</param> /// <param name="uri">The Source URL from where Stream can be downloaded</param> /// <param name="obj">The input object which should be passed as part of request</param> /// <returns></returns> public Stream GetStream <TRequest>(HttpMethod httpMethod, string uri, TRequest obj) where TRequest : class { HttpResponseMessage httpResp = null; string xml = string.Empty; // -- try to get stub data xml = GetStubData(uri); if (string.IsNullOrEmpty(xml)) { httpResp = obj == null?EVHttpClient.GetHttpClient().Send(httpMethod, uri) : EVHttpClient.GetHttpClient().Send(httpMethod, uri, HttpContentExtensions.CreateXmlSerializable <TRequest>(obj)); if (!httpResp.IsStatusIsSuccessful()) { throw new EVException().AddHttpResponse(httpResp); } // -- get response data return(httpResp.Content.ReadAsStream()); } return(null); }
/// <summary> /// This is a generic Http send method which takes data from /// stub if needed else calls the service and returns the data /// back to the caller /// </summary> /// <typeparam name="TRequest">Request type</typeparam> /// <typeparam name="TResponse">Response type</typeparam> /// <param name="httpMethod">HttpMethod type</param> /// <param name="uri">Uri of stubbed filename/Rest web service</param> /// <param name="obj">Request type object</param> /// <returns>Response type object</returns> public TResponse Send <TRequest, TResponse>(HttpMethod httpMethod, string uri, TRequest obj) where TRequest : class { HttpResponseMessage httpResp = null; string xml = string.Empty; // -- try to get stub data xml = GetStubData(uri); if (string.IsNullOrEmpty(xml)) { httpResp = obj == null?EVHttpClient.GetHttpClient().Send(httpMethod, uri) : EVHttpClient.GetHttpClient().Send(httpMethod, uri, HttpContentExtensions.CreateXmlSerializable <TRequest>(obj)); if (!httpResp.IsStatusIsSuccessful()) { throw new EVException().AddHttpResponse(httpResp); } // -- get response data xml = GetResponseData(uri, httpResp); } return((TResponse)XmlUtility.DeserializeObject(xml, typeof(TResponse))); }