/// <summary> /// Returns true if MethodRequestAndResponse instances are equal /// </summary> /// <param name="other">Instance of MethodRequestAndResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(MethodRequestAndResponse other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( RequestPayload == other.RequestPayload || RequestPayload != null && RequestPayload.Equals(other.RequestPayload) ) && ( ResponsePayload == other.ResponsePayload || ResponsePayload != null && ResponsePayload.Equals(other.ResponsePayload) ) && ( StatusCode == other.StatusCode || StatusCode != null && StatusCode.Equals(other.StatusCode) )); }
private static void PostRequest() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(SERVICE_URL); //For local web service, comment out this line. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY); var inputJson = new List <RequestPayload>(); RequestPayload payload = new RequestPayload(); List <InputDf> inputDf = new List <InputDf>(); inputDf.Add(new InputDf() { feature1 = 23.4, feature2 = 37.2, }); payload.Input_df_list = inputDf; inputJson.Add(payload); try { var request = new HttpRequestMessage(HttpMethod.Post, string.Empty); request.Content = new StringContent(JsonConvert.SerializeObject(payload)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = client.SendAsync(request).Result; Console.Write(response.Content.ReadAsStringAsync().Result); } catch (Exception e) { Console.Out.WriteLine(e.Message); } }
public IEnumerable <ResponseDetail> SolveUnitCommitment(RequestPayload payload) { var multitudes = new List <Multitude>(); foreach (var item in payload.PowerPlants) { switch (item.Type) { case "gasfired": AddGasFired(payload.Fuels, multitudes, item); break; case "turbojet": AddTurboJet(payload.Fuels, multitudes, item); break; case "windturbine": AddWindTurbine(payload.Fuels, multitudes, item); break; default: logger.LogError($"Power plant { item.Type } not identified."); break; } } SetCommitment(payload.Load, ref multitudes); return(mapper.Map <IEnumerable <ResponseDetail> >(multitudes)); }
protected override async Task WhenAsync() { await using (_testServer.Start() .ConfigureAwait(false)) { var client = await _testServer .CreateRequestClientAsync() .ConfigureAwait(false); var requestPayload = new RequestPayload( new RequestHeader(RequestHeader.MaxVersion) .WithRequestApiKey(ApiVersionsRequest.ApiKey) .WithRequestApiVersion( ApiVersionsRequest.MaxVersion) .WithCorrelationId(Int32.From(12)), new ApiVersionsRequest(ApiVersionsRequest.MaxVersion)); await client .SendAsync(requestPayload) .ConfigureAwait(false); _response = await client .ReadAsync(requestPayload) .ConfigureAwait(false); } }
private async Task <DbServer> CreateNewServer(RequestPayload requestInfo, int version, ObjectId stateId) { //Generate a token to use string token = SecureStringTool.GenerateSecureString(46); while (!await SecureStringTool.CheckStringUniquenessAsync <DbServer>(token, Program.conn.system_servers)) { token = SecureStringTool.GenerateSecureString(46); } token = "B." + token; //Create a server var server = new DbServer { display_name = requestInfo.name, _id = MongoDB.Bson.ObjectId.GenerateNewId(), image_url = Program.conn.hosts.master + "/default_server_icon.png", token = token, has_custom_image = false, latest_server_map = requestInfo.map, mods = new string[0], last_secure_mode_toggled = DateTime.UtcNow, flags = 0b00000110, last_client_version = version, last_connected_time = DateTime.UtcNow, last_pinged_time = DateTime.UtcNow, last_sync_state = stateId }; //Insert await Program.conn.system_servers.InsertOneAsync(server); return(server); }
/// <summary> /// 发送语音消息 /// </summary> /// <param name="teltemp">语音模版ID</param> /// <param name="receivers">消息接收对象,多个以逗号分隔</param> /// <param name="message">语音消息内容</param> /// <param name="contextparm">变量内容[若模板中未使用变量,则不传该参数。多个内容直接用英文状态下逗号”,”隔开.例如:num:1002,time:半小时]</param> /// <returns></returns> public override ResponseModel SendMessage(long teltemp, string receivers, string message, string contextparm) { var request = new RequestPayload { callingline = receivers, company = ConfigurationManager.AppSettings["CHUANGLAN.AUDIO.RESOURCE.company"], contextparm = contextparm, keytime = DateTime.Now.ToString("yyyyMMddHHmmssfff"), sex = 2, telno = ConfigurationManager.AppSettings["CHUANGLAN.AUDIO.RESOURCE.telno"], teltemp = long.Parse(teltemp.ToString()) }; request.key = Util.GetKeyString(ConfigurationManager.AppSettings["CHUANGLAN.AUDIO.RESOURCE.key"], ConfigurationManager.AppSettings["CHUANGLAN.AUDIO.RESOURCE.secret"], request.keytime); try { var messageSender = new AudioMessage.ChuangLan.ChuangLanAudioMessageSender(request); messageSender.Send(); return(messageSender.Response); } catch (Exception ex) { throw ex; } }
internal async Task <RequestPayload> ReadAsync( CancellationToken cancellationToken = default) { return(await RequestPayload .ReadFromAsync( RequestHeader.MaxVersion, Reader, cancellationToken) .ConfigureAwait(false)); }
public static string FromPayload(RequestPayload payload) { return(payload switch { RequestPayload.Byte10 => byte10, RequestPayload.Byte100 => byte100, RequestPayload.KilloByte10 => killoByte10, RequestPayload.KilloByte100 => killoByte100, _ => throw new ArgumentOutOfRangeException(payload.ToString()), });
public IActionResult Post([FromBody] RequestPayload request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = service.SolveUnitCommitment(request); return(Ok(result)); }
public async Task <HttpResponseMessage> PostAsync <TProps>(RequestPayload <TProps> requestPayload) { using (var content = new StringContent(JsonConvert.SerializeObject(requestPayload), Encoding.UTF8, "application/json")) { var response = await _httpClient.PostAsync(BaseAddress, content) .ConfigureAwait(false); // ToDo: HttpCliet should be here return(response); }; }
public static string ToAuthorizationHeader(this RequestPayload request) { return(Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes( string.Concat(request.ClientId, "|", request.UserName, "|", request.Identifier, "|", request.RequestCount) ) )); }
public Task ProduceRequest(RequestPayload payload) { if (this.queue == null) { this.queue = new BufferBlock <RequestPayload>(); this.ConsumeRequestsAsync(queue); } await queue.SendAsync(payload); return(await payload.CompletionSource.Task); }
// ToDo: Implement later for getLoyaltyInfo // {"system":"PA 3.0","modelName":"LoyaltyUser","calledMethod":"getLoyaltyInfoByApiKey","methodProperties":{}} public Task <ResponsePayload <GetLoyaltyInfoByApiKeyData> > GetLoyaltyInfoByApiKey(string apiKey) { var payload = new RequestPayload <GetLoyaltyInfoByApiKeyProps> { ApiKey = apiKey, ModelName = ModelName, CalledMethod = "getLoyaltyInfoByApiKey", MethodProperties = new GetLoyaltyInfoByApiKeyProps() }; return(ApiConnection.PostAsync <GetLoyaltyInfoByApiKeyProps, GetLoyaltyInfoByApiKeyData>(payload)); }
public Task <ResponsePayload <DeleteContragentAddressData> > DeleteContragentAddress(Guid addressRef) { var payload = new RequestPayload <DeleteContragentAddressProps> { ApiKey = base.ApiConnection.ApiKey, ModelName = "Address", CalledMethod = "delete", MethodProperties = new DeleteContragentAddressProps(addressRef) }; return(ApiConnection.PostAsync <DeleteContragentAddressProps, DeleteContragentAddressData>(payload)); }
public Task <ResponsePayload <SaveWaybillData> > SaveWaybill(SaveWaybillProps methodProps) { var payload = new RequestPayload <SaveWaybillProps> { ApiKey = ApiConnection.ApiKey, ModelName = ModelName, CalledMethod = "save", MethodProperties = methodProps }; return(ApiConnection.PostAsync <SaveWaybillProps, SaveWaybillData>(payload)); }
public Task <ResponsePayload <GetDocumentPriceData> > GetDocumentPriceData(GetDocumentPriceProps methodProps) { var payload = new RequestPayload <GetDocumentPriceProps> { ApiKey = ApiConnection.ApiKey, ModelName = ModelName, CalledMethod = "getDocumentPrice", MethodProperties = methodProps }; return(ApiConnection.PostAsync <GetDocumentPriceProps, GetDocumentPriceData>(payload)); }
public Task <ResponsePayload <SearchSettlementsData> > SearchSettlements(SearchSettlementsProps methodProps) { var payload = new RequestPayload <SearchSettlementsProps> { ApiKey = base.ApiConnection.ApiKey, ModelName = "Address", CalledMethod = "searchSettlements", MethodProperties = methodProps }; return(base.ApiConnection.PostAsync <SearchSettlementsProps, SearchSettlementsData>(payload)); }
public async Task <string> Send(Message message, bool dryrun = false) { // Prepare the request RequestPayload payload = new RequestPayload() { Message = message, DryRun = dryrun }; // Serialize the request string serializedMessage = JsonConvert.SerializeObject(payload, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }); LOG.Trace("Request: {0}", serializedMessage); // Prepare the request var token = await GetAccessToken(mCredentialsFile); LOG.Trace("Token: {0} Endpoint: {1}", token, mFirebaseEndpoint); using (var request = new HttpRequestMessage(HttpMethod.Post, mFirebaseEndpoint)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Content = new StringContent(serializedMessage, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { var result = await client.SendAsync(request); if (result.StatusCode != System.Net.HttpStatusCode.OK) { //TODO: handle retry-timeout for 500 messages var errorMessage = await result.Content.ReadAsStringAsync(); LOG.Error(errorMessage); throw new Exception(errorMessage); } // As per documentation: "If successful, the response body contains an instance of Message" var content = await result.Content.ReadAsStringAsync(); LOG.Trace("Response: {0}", content); Message responseMessage = JsonConvert.DeserializeObject <Message>(content); // But (currently) only the 'Name' property is outputed so we cheat a bit return(responseMessage.Name); } } }
public Task <ResponsePayload <SaveContragentAddressData> > SaveContragentAddress(SaveContragentAddressProps methodProps) { var payload = new RequestPayload <SaveContragentAddressProps> { ApiKey = base.ApiConnection.ApiKey, ModelName = "Address", CalledMethod = "save", MethodProperties = methodProps }; return(base.ApiConnection.PostAsync <SaveContragentAddressProps, SaveContragentAddressData>(payload)); }
public Task <ResponsePayload <GetAreasData> > GetAreas() { var payload = new RequestPayload <GetAreasProps> { ApiKey = base.ApiConnection.ApiKey, ModelName = "Address", CalledMethod = "getAreas", MethodProperties = new GetAreasProps() }; return(ApiConnection.PostAsync <GetAreasProps, GetAreasData>(payload)); }
public Task <ResponsePayload <GetWarehousesData> > GetWarehouses(GetWarehousesProps methodProps) { var payload = new RequestPayload <GetWarehousesProps> { ApiKey = base.ApiConnection.ApiKey, ModelName = "AddressGeneral", CalledMethod = "getWarehouses", MethodProperties = methodProps }; return(base.ApiConnection.PostAsync <GetWarehousesProps, GetWarehousesData>(payload)); }
public async Task ShouldReceive200AndValueOnIncrementRequestCount() { var client = new HttpClient(); var url = string.Concat(_address, "/api/values/5"); var result = await client.GetAsync(url); var wwwAuthenticate = result.Headers.WwwAuthenticate.First(); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); StringAssert.Equals(wwwAuthenticate.Scheme, "AuthAPI"); var responsePayload = new ResponsePayload(wwwAuthenticate.Parameter); var requestPayload = new RequestPayload { ClientId = "TestAPI", Identifier = responsePayload.Identifier, RequestCount = string.Format("{0:D8}", int.Parse(responsePayload.RequestCount) + 1), UserName = "******" }; var dataPayload = new DataPayload { ClientId = "TestAPI", Method = "GET", Password = "******", RequestBodyBase64 = string.Empty, RequestURI = "/api/values/5", UserName = "******" }; var authHeader = new AuthHeader { Data = dataPayload, Request = requestPayload }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ=")); result = await client.GetAsync(url); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.AreEqual(await result.Content.ReadAsAsync <string>(), "value"); authHeader.Request.RequestCount = string.Format("{0:D8}", int.Parse(authHeader.Request.RequestCount) + 1); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ=")); result = await client.GetAsync(url); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public async Task ShouldReceive200OnPost() { var client = new HttpClient(); var valuesModel = new ValuesModel { Id = 1, Name = "oi" }; var url = string.Concat(_address, "/api/values"); var result = await client.PostAsJsonAsync <ValuesModel>(url, valuesModel); var wwwAuthenticate = result.Headers.WwwAuthenticate.First(); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); StringAssert.Equals(wwwAuthenticate.Scheme, "AuthAPI"); var responsePayload = new ResponsePayload(wwwAuthenticate.Parameter); var requestPayload = new RequestPayload { ClientId = "TestAPI", Identifier = responsePayload.Identifier, RequestCount = string.Format("{0:D8}", int.Parse(responsePayload.RequestCount) + 1), UserName = "******" }; var json = JsonConvert.SerializeObject(valuesModel); var dataPayload = new DataPayload { ClientId = "TestAPI", Method = "POST", Password = "******", RequestBodyBase64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(valuesModel))), RequestURI = "/api/values", UserName = "******" }; var authHeader = new AuthHeader { Data = dataPayload, Request = requestPayload }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ=")); result = result = await client.PostAsJsonAsync <ValuesModel>(url, valuesModel); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
private static byte[] CreateRequestData( Command command = Command.DeviceEchoRequest, bool ackRequired = false, bool resRequired = false, byte sequence = 0, uint source = 0, ulong target = 0, RequestPayload payload = null ) { payload = payload ?? RequestPayload.Empty; return(new Request(command, ackRequired, resRequired, sequence, source, target, payload).GetData()); }
private static ApiWebException MakeOriginalException() { var innerException = new WebException("test"); var requestBody = new RequestPayload("foo", "bar"); var headers = new Dictionary <string, string> { { "key1", "value1" } }; var originalRequest = new Request(HttpMethod.Get, "http://foo.com/bar?foo=bar", headers, requestBody); var inputException = new ApiWebException("request failed", innerException, originalRequest); return(inputException); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (RequestPayload != null) hashCode = hashCode * 59 + RequestPayload.GetHashCode(); if (ResponsePayload != null) hashCode = hashCode * 59 + ResponsePayload.GetHashCode(); if (StatusCode != null) hashCode = hashCode * 59 + StatusCode.GetHashCode(); return hashCode; } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, [OrchestrationClient] DurableOrchestrationClient starter, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // Get request body RequestPayload data = await req.Content.ReadAsAsync <RequestPayload>(); log.Info($"About to start orchestration for {data}"); var orchestrationId = await starter.StartNewAsync("ProcessRequestOrchestrator", data); return(starter.CreateCheckStatusResponse(req, orchestrationId)); }
public void Insert(RequestPayload entity) { Connection.Execute( "SProc_RequestPayload_Insert", commandType: CommandType.StoredProcedure, param: new { entity.Id , entity.Uri , entity.HttpVerb , entity.RequestHeaders , entity.JsonContent , entity.Created } ); }
public Task <ResponsePayload <GetUserByLoginData> > SignIn(string email, string password) { var payload = new RequestPayload <GetUserByLoginProps> { ApiKey = ApiConnection.ApiKey, ModelName = ModelName, CalledMethod = "getUserByLogin", MethodProperties = new GetUserByLoginProps { Login = email, Password = password } }; return(ApiConnection.PostAsync <GetUserByLoginProps, GetUserByLoginData>(payload)); }
public async void bad_url_post__should_return_not_found() { var url = string.Format("{0}/foo/bar/fish/1234?oauth_consumer_key={1}", API_URL, _consumerKey); var parameters = new Dictionary <string, string> { { "foo", "bar" } }; var queryString = parameters.ToQueryString(); var requestPayload = new RequestPayload("application/xml", queryString); var request = new Request(HttpMethod.Post, url, new Dictionary <string, string>(), requestPayload); var response = await new HttpClientMediator().Send(request); AssertResponse(response, HttpStatusCode.NotFound); }