public async Task <IActionResult> Refill([FromServices] DaprClient daprClient) { using (var reader = new System.IO.StreamReader(Request.Body)) { // boldly assume the input is correctly formatted var body = await reader.ReadToEndAsync(); var item = JsonSerializer.Deserialize <dynamic>(body); var SKU = item.GetProperty("SKU").GetString(); var Quantity = item.GetProperty("Quantity").GetInt32(); var stateItem = await daprClient.GetStateEntryAsync <ItemState>(StoreName_item, SKU); stateItem.Value ??= new ItemState() { SKU = SKU, Changes = new List <ItemReservation>() }; // update balance stateItem.Value.BalanceQuantity += Quantity; // save item state await stateItem.SaveAsync(); Console.WriteLine($"Refill of {SKU} for quantity {Quantity}, new balance {stateItem.Value.BalanceQuantity}"); } return(this.Ok()); }
public virtual async Task <ResponseApi> Edit([FromForm, FromBody] T obj) { if (Request.ContentType.Contains("application/json")) { using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body)) { // Ref(ref obj, reader.ReadToEnd()); Ref(ref obj, reader.ReadToEndAsync().Result);//类库影响 } } else if (Request.ContentType.Contains("text/xml")) { using System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body); Type t = typeof(T); XmlSerializer serializer = new XmlSerializer(t); obj = serializer.Deserialize(reader) as T; } //this.ActionParam(HttpContext.Request,ref obj);//无效 作用域可能 绑定模型失败 //ActionParam(HttpContext.Request,ref obj); var validate = await this.Validate(obj, 3); if (validate != null) { return(validate); } else { return(await EditMiddlewareExecuted(obj)); } }
//Test async static async Task <int> HandleFileAsync() { string file = @"C:\programs\enable1.txt"; Console.WriteLine("HandleFile enter"); int count = 0; // Read in the specified file. // ... Use async StreamReader method. using (System.IO.StreamReader reader = new System.IO.StreamReader(file)) { string v = await reader.ReadToEndAsync(); // ... Process the file data somehow. count += v.Length; // ... A slow-running computation. // Dummy code. for (int i = 0; i < 10000; i++) { int x = v.GetHashCode(); if (x == 0) { count--; } } } Console.WriteLine("HandleFile exit"); return(count); }
private static async Task <string> GetObjectAsync(BlobContainerClient client, string fileName, CancellationToken token) { try { BlobClient blobClient = client.GetBlobClient(fileName); if (await blobClient.ExistsAsync()) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { await blobClient.DownloadToAsync(ms, token); ms.Position = 0; using (System.IO.StreamReader sr = new System.IO.StreamReader(ms)) return(await sr.ReadToEndAsync()); } } } catch (Exception ex) { throw; } return(null); }
/// <summary> /// 模拟登录 /// </summary> /// <param name="passport"></param> /// <param name="password"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task <OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }; var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest; request.Referer = GetAuthorizeUrl(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); var postBody = GetSimulateLoginPostBody(passport, password); var postData = System.Text.Encoding.UTF8.GetBytes(postBody); cancelToken.ThrowIfCancellationRequested(); var result = ""; using (var requestStream = await request.GetRequestStreamAsync()) { await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken); } using (var response = await request.GetResponseAsync()) { using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { cancelToken.ThrowIfCancellationRequested(); result = await sr.ReadToEndAsync(); return(ConvertToAccessTokenByRegex(result)); } } }
/// <summary> /// 模拟登录 /// </summary> /// <param name="passport"></param> /// <param name="password"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task<OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; }; var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest; request.Referer = GetAuthorizeUrl(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); var postBody = GetSimulateLoginPostBody(passport, password); var postData = System.Text.Encoding.UTF8.GetBytes(postBody); cancelToken.ThrowIfCancellationRequested(); var result = ""; using (var requestStream = await request.GetRequestStreamAsync()) { await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken); } using (var response = await request.GetResponseAsync()) { using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { cancelToken.ThrowIfCancellationRequested(); result = await sr.ReadToEndAsync(); return ConvertToAccessTokenByRegex(result); } } }
private async Task <Dictionary <string, string> > GetAllAsync() { var result = new Dictionary <string, string>(); var assemblies = DIResolver.GetAssemblies(); foreach (var assembly in assemblies) { var resourceNames = assembly.GetManifestResourceNames(); foreach (var resourceName in resourceNames) { var resourceStream = assembly.GetManifestResourceStream(resourceName); if (resourceStream == null) { continue; } using (var reader = new System.IO.StreamReader(resourceStream, Encoding.UTF8)) { var sql = await reader.ReadToEndAsync(); result.Add(resourceName, sql); } } } return(result); }
/// <summary> /// Attempt to load from file /// </summary> public static async Task <(bool IsSuccess, LocalUserConfig Result)> TryLoadLocalUserConfigFromFileAsync( Path localUserConfigFile) { // Verify the requested file exists Log.Diag("Load Local User Config: " + localUserConfigFile.ToString()); if (!LifetimeManager.Get <IFileSystem>().Exists(localUserConfigFile)) { Log.Warning("Local User Config file does not exist."); return(false, new LocalUserConfig()); } // Open the file to read from var file = LifetimeManager.Get <IFileSystem>().OpenRead(localUserConfigFile); // Open the file to read from using (var reader = new System.IO.StreamReader(file.GetInStream())) { // Read the contents of the local user config file try { var result = ValueTableTomlUtilities.Deserialize( localUserConfigFile, await reader.ReadToEndAsync()); return(true, new LocalUserConfig(result)); } catch (Exception ex) { Log.Error("Deserialize Threw: " + ex.Message); Log.Info("Failed to parse local user config."); return(false, new LocalUserConfig()); } } }
public async Task <PostImportApiResult> Import() { if (!this.ModelState.IsValid) { return(ApiHelpers.CreateApiResult <PostImportApiResult>(ApiCode.BadRequest)); } IFormFile importFile = this.Request.Form.Files.FirstOrDefault(); if (importFile == null) { return(ApiHelpers.CreateApiResult <PostImportApiResult>(ApiCode.BadRequest)); } var xmlString = ""; using (var sr = new System.IO.StreamReader(importFile.OpenReadStream())) { xmlString = await sr.ReadToEndAsync(); } await this.ImportWordpressPostsFromXmlString(xmlString); return(ApiHelpers.CreateApiResult <PostImportApiResult>(ApiCode.Success)); }
private async Task OutputProfileSignInResult(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter) { var sr = new System.IO.StreamReader(context.Request.Body); string jsonContent = await sr.ReadToEndAsync(); var loginModel = JsonConvert.DeserializeObject <LoginModel>(jsonContent); User user = new OCM.API.Common.UserManager().GetUser(loginModel); string access_token = null; var responseEnvelope = new APIResponseEnvelope(); if (user == null) { context.Response.StatusCode = 401; return; } else { access_token = Security.JWTAuth.GenerateEncodedJWT(user); /* * var validatedToken = Security.JWTAuthTicket.ValidateJWTForUser(testTicket, user); */ } responseEnvelope.Data = new { UserProfile = user, access_token = access_token }; await outputProvider.GetOutput(context, context.Response.Body, responseEnvelope, filter); }
public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation) { var stream = await actionContext?.Request?.Content?.ReadAsStreamAsync(); if (stream == null) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.BadRequest, value: new { Message = Displays.BadRequest( context: new Context( sessionStatus: false, sessionData: false, item: false)) }, mediaType: "application/json"))); } var reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8); var requestData = await reader.ReadToEndAsync(); stream.Position = 0; var context = new Context( sessionStatus: false, sessionData: false, item: false, apiRequestBody: requestData); if (!context.ContractSettings.AllowedIpAddress(context.UserHostAddress)) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.Forbidden, value: new { Message = Displays.InvalidIpAddress(context) }, mediaType: "application/json"))); } if (Parameters.Security.TokenCheck && HttpContext.Current?.User?.Identity?.IsAuthenticated == true) { var data = await actionContext.Request?.Content?.ReadAsStringAsync(); var api = data?.Deserialize <Api>(); if (api?.Token != Authentications.Token()) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.BadRequest, value: new { Message = Displays.BadRequest(context: context) }, mediaType: "application/json"))); } } return(await continuation()); }
/// <summary> /// 读文件 /// </summary> /// <param name="path">文件路径</param> /// <param name="charset">编码,默认utf-8</param> /// <returns></returns> public static async Task <string> ReadAsync(string path, string charset = "utf-8") { using System.IO.StreamReader f2 = new System.IO.StreamReader(path, System.Text.Encoding.GetEncoding(charset)); var s = await f2.ReadToEndAsync(); return(s); }
public static async Task <HttpResponseData> WebhookTriggerTest([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "test")] HttpRequestData request, FunctionContext executionContext) { var log = executionContext.GetLogger("WebhooksTrigger"); var query = System.Web.HttpUtility.ParseQueryString(request.Url.Query); string jobId = query["jobId"]; if (string.IsNullOrEmpty(jobId)) { if (request.Method.ToLowerInvariant() == "post") { var s = new System.IO.StreamReader(request.Body); var text = await s.ReadToEndAsync(); log.LogInformation($"Body: {text}"); //https://docs.microsoft.com/en-us/azure/event-grid/webhook-event-delivery var r = await TestInfraLogic.WebhooksTest.validation(log, text); if (r.Item1) { log.LogInformation($"Returning validation code {r.Item2}"); var response = request.CreateResponse(HttpStatusCode.OK); await response.WriteAsJsonAsync(r.Item2); return(response); } else { await TestInfraLogic.WebhooksTest.post(log, StorageTableConnectionString, text); return(request.CreateResponse(HttpStatusCode.OK)); } } else { log.LogWarning($"Unhandled request method {request.Method} when job id is not set"); return(request.CreateResponse(HttpStatusCode.BadRequest)); } } else { if (request.Method.ToLowerInvariant() == "get") { log.LogInformation($"Getting webhook messages for job {jobId}"); var results = await TestInfraLogic.WebhooksTest.get(log, StorageTableConnectionString, jobId); var response = request.CreateResponse(HttpStatusCode.OK); await response.WriteAsJsonAsync(results); return(response); } else { log.LogWarning($"Unhandled request method {request.Method} when job id is {jobId}"); return(request.CreateResponse(HttpStatusCode.BadRequest)); } } }
public async System.Threading.Tasks.Task <ActionResult> Index(string colour = "white", string power = "on") { var client = new HttpClient(); //There are different parameters that can be passed to API. var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("color", $"{colour} saturation:0.5"), new KeyValuePair <string, string>("power", power), new KeyValuePair <string, string>("brightness", "0.5"), new KeyValuePair <string, string>("duration", "1") } ); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ConfigurationManager.AppSettings["LIFX:APIKey"]); //call the LIFX api var response = await client.PutAsync("https://api.lifx.com/v1/lights/all/state", requestContent); // Get the response content from API var responseContent = response.Content; using (var reader = new System.IO.StreamReader(await responseContent.ReadAsStreamAsync())) { // Write the output. Console.WriteLine(await reader.ReadToEndAsync()); } return(View()); }
public async Task <PickedFile[]> GetSelectionResponseAsync() { UriBuilder uri = new UriBuilder("https://apis.live.net"); uri.Path = string.Format("/v5.0/{0}/files", this.SelectionId); OneDrive.QueryStringBuilder qsb = new OneDrive.QueryStringBuilder(); qsb.Add("method", "GET"); qsb.Add("interface_method", "OneDrive.open"); qsb.Add("pretty", "false"); qsb.Add("access_token", this.AccessToken); qsb.Add("suppress_redirects", "true"); uri.Query = qsb.ToString(); HttpWebRequest request = WebRequest.CreateHttp(uri.ToString()); var response = await request.GetResponseAsync() as HttpWebResponse; if (response == null) { return(null); } if (response.StatusCode != HttpStatusCode.OK) { return(null); } using (var responseStream = response.GetResponseStream()) { var reader = new System.IO.StreamReader(responseStream); var responseText = await reader.ReadToEndAsync(); var parsed = Newtonsoft.Json.JsonConvert.DeserializeObject <SelectionResponse>(responseText); return(parsed.data); } }
public async Task ExpandNestedCount() { var parser = new OeParser(new Uri("http://dummy/"), Fixture.OeDataAdapter, Fixture.EdmModel); var request = new Uri("http://dummy/Orders?$expand=Items($count=true)"); Newtonsoft.Json.Linq.JObject responseJObject; using (var stream = new System.IO.MemoryStream()) { await parser.ExecuteQueryAsync(request, OeRequestHeaders.Default, stream, System.Threading.CancellationToken.None); stream.Position = 0; using (var reader = new System.IO.StreamReader(stream)) { string responseStr = await reader.ReadToEndAsync(); responseJObject = Newtonsoft.Json.Linq.JObject.Parse(responseStr); } } var jArray = (Newtonsoft.Json.Linq.JArray)responseJObject["value"]; var actualCounts = jArray.Select(o => (int?)o["*****@*****.**"]); int?[] expectedCounts = null; using (var dbContext = Fixture.CreateContext()) expectedCounts = dbContext.Orders.Select(i => (int?)i.Items.Count()).ToArray(); Assert.Equal(expectedCounts, actualCounts); }
public virtual ResponseApi Add([FromForm] T obj) { if (Request.ContentType.Contains("application/json")) { using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body)) { // Ref(ref obj, reader.ReadToEnd()); Ref(ref obj, reader.ReadToEndAsync().Result);//类库影响 } } else if (Request.ContentType.Contains("text/xml")) { using System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body); Type t = typeof(T); XmlSerializer serializer = new XmlSerializer(t); obj = serializer.Deserialize(reader) as T; } //if (!ModelState.IsValid) //{ // return ResponseApi.Fail(); //} obj.CreateDate = DateTime.Now; this.Repository.Insert(obj); return(ResponseApi.CreateSuccess()); }
protected async Task HandleBodyRequest(HttpContext context, Method method, Entity ent, IGenericSPSerializer serializer) { var request = context.Request; Dictionary <string, object> parameterObject; #if NET48 var cntType = MediaTypeHeaderValue.Parse(request.ContentType); bool hasFormContentType = HasMultipartFormContentType(cntType) || HasApplicationFormContentType(cntType); #else bool hasFormContentType = request.HasFormContentType; #endif if (hasFormContentType) { parameterObject = new Dictionary <string, object>(StringComparer.CurrentCultureIgnoreCase); #if NETFX foreach (var key in request.Form.AllKeys) { parameterObject.Add(key, request.Form[key]); } foreach (var key in request.Files.AllKeys) { parameterObject.Add(key, request.Files[key]); } #else foreach (var item in request.Form) { parameterObject.Add(item.Key, string.Join(",", item.Value)); } foreach (var file in request.Form.Files) { parameterObject.Add(file.Name, file); } #endif } else { #if NETFX var streamReader = new System.IO.StreamReader(request.InputStream); #else var streamReader = new System.IO.StreamReader(request.Body); #endif string json = await streamReader.ReadToEndAsync(); parameterObject = new Dictionary <string, object>(StringComparer.CurrentCultureIgnoreCase); JsonConvert.PopulateObject(json, parameterObject); } var cmd = await commandPreparation.GetCommandWithParameters(context, null, dbConnection, ent, method, parameterObject); var start = DateTime.UtcNow; foreach (var log in requestLoggers) { log.OnRequestStart(context, cmd); } await serializer.ReadResultToBody(new SerializationContext(cmd, context, method, ent)); foreach (var log in requestLoggers) { log.OnRequestEnd(context, cmd, start); } }
/// <summary> /// Attempt to load from file /// </summary> public static async Task <(bool IsSuccess, Recipe Result)> TryLoadRecipeFromFileAsync(Path recipeFile) { // Verify the requested file exists Log.Diag("Load Recipe: " + recipeFile.ToString()); if (!System.IO.File.Exists(recipeFile.ToString())) { Log.Info("Recipe file does not exist."); return(false, new Recipe()); } // Open the file to read from using (var fileStream = System.IO.File.OpenRead(recipeFile.ToString())) using (var reader = new System.IO.StreamReader(fileStream)) { // Read the contents of the recipe file try { var result = ValueTableTomlUtilities.Deserialize( recipeFile, await reader.ReadToEndAsync()); return(true, new Recipe(result)); } catch (Exception ex) { Log.Error($"Deserialize Threw: {ex.Message}"); Log.Info("Failed to parse Recipe."); return(false, new Recipe()); } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(async(context, next) => { // use a temporary MemoryStream to disallow sending the response to the client, // until the MemoryStream gets disposed -- hence we can change the response var originalBody = context.Response.Body; using (var newBody = new System.IO.MemoryStream()) { context.Response.Body = newBody; await next(); newBody.Seek(0, System.IO.SeekOrigin.Begin); using (var bodyReader = new System.IO.StreamReader(context.Response.Body)) { string content = await bodyReader.ReadToEndAsync(); content = FilterBadWords(content); context.Response.Body = originalBody; await context.Response.WriteAsync(content); } } }); app.UseMvcWithDefaultRoute(); }
LoadAsync ( string path ) { if (string.IsNullOrEmpty(path)) { return(null); } string[] path_parts = path.Split(new[] { "." }, StringSplitOptions.None); string format = path_parts[path_parts.Length - 1]; string library = path_parts[path_parts.Length - 2]; string content = null; using (System.IO.StreamReader reader = System.IO.File.OpenText(path)) { content = await reader.ReadToEndAsync(); } Artifact object_deserialized = null; switch (format) { case "json": default: object_deserialized = Artifact.DeserializeFromJSON(content); break; } return(object_deserialized); }
public async System.Threading.Tasks.Task <ActionResult> PostAsync([FromQuery] PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, _wechatSetting.Token)) { _logger.LogError("参数错误!"); return(Content("参数错误!")); } postModel.Token = _wechatSetting.Token; // postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致 postModel.AppId = _wechatSetting.AppID; //根据自己后台的设置保持一致 #region // Add for read Request.Body multiple times { Request.EnableBuffering(); var reader = new System.IO.StreamReader(Request.Body, encoding: System.Text.Encoding.UTF8); { var body = await reader.ReadToEndAsync(); _logger.LogInformation(body); // Do some processing with body… // Reset the request body stream position so the next middleware can read it Request.Body.Position = 0; } } #endregion var messageHandler = new CustomMessageHandler(Request.Body, postModel, _wechatSetting);//接收消息(第一步) Request.Body.Position = 0; messageHandler.Execute(); //执行微信处理过程(第二步) return(Content(messageHandler.ResponseDocument.ToString()));; //返回(第三步) }
public async Task CountQueryParameter() { var parser = new OeParser(new Uri("http://dummy/"), Fixture.OeDataAdapter, Fixture.EdmModel); var request = new Uri("http://dummy/Orders?$expand=Items&$count=true"); Newtonsoft.Json.Linq.JObject responseJObject; using (var stream = new System.IO.MemoryStream()) { await parser.ExecuteQueryAsync(request, OeRequestHeaders.Default, stream, System.Threading.CancellationToken.None); stream.Position = 0; using (var reader = new System.IO.StreamReader(stream)) { string responseStr = await reader.ReadToEndAsync(); responseJObject = Newtonsoft.Json.Linq.JObject.Parse(responseStr); } } var actualCount = (int?)responseJObject["@odata.count"]; int?expectedCount = null; using (var dbContext = Fixture.CreateContext()) expectedCount = dbContext.Orders.Count(); Assert.Equal(expectedCount, actualCount); }
async Task <string> HttpGetAsync(string URI) { try { using (HttpClient hc = new HttpClient()) { Task <System.IO.Stream> result = hc.GetStreamAsync(URI); using (System.IO.Stream vs = await result) { using (System.IO.StreamReader am = new System.IO.StreamReader(vs)) { return(await am.ReadToEndAsync()); } } } } catch (System.Net.WebException ex) { if (ex.Status == System.Net.WebExceptionStatus.NameResolutionFailure) { System.Console.WriteLine("Error: domain not found"); } //switch (ex.Status) //{ // case System.Net.WebExceptionStatus.NameResolutionFailure: // System.Console.WriteLine("Error: domain not found"); // break; // //Catch other exceptions here //} throw; } }
public async Task <string> Get() { string result = null; try { //"2016-06-12T13:49:24.759Z" string request_string = Program.config_couchdb_url + $"/metadata/2016-06-12T13:49:24.759Z/validator.js"; System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string)); request.Method = "GET"; request.PreAuthenticate = false; System.Net.WebResponse response = (System.Net.HttpWebResponse) await request.GetResponseAsync(); System.IO.Stream dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); result = await reader.ReadToEndAsync(); } catch (Exception ex) { Console.WriteLine(ex); } return(result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // Handle the echo request app.Use(async(context, next) => { if (context.Request.Method == "POST" && context.Request.Path.StartsWithSegments("/api/Echo")) { using var reader = new System.IO.StreamReader(context.Request.Body); var payload = await reader.ReadToEndAsync(); await context.Response.WriteAsync(payload); } await next(); }); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); }
public async Task <ActionResult <System.Net.Http.HttpResponseMessage> > Get() { azureMapsSubscriptionKey = await DoVault(); Console.WriteLine("HERE!!"); Console.WriteLine(azureKeyVaultUrl); string jsonString; using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body, System.Text.Encoding.UTF8)) { jsonString = await reader.ReadToEndAsync(); } var stringContent = new System.Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json"); Console.WriteLine($"stringContent: {stringContent}"); System.Net.Http.HttpResponseMessage response = await client.PostAsync( $"https://atlas.microsoft.com/mapData/upload?subscription-key={azureMapsSubscriptionKey}&api-version=1.0&dataFormat=geojson", stringContent ); // System.Net.Http.HttpResponseMessage response = await client.GetAsync( // $"https://atlas.microsoft.com/route/directions/json?subscription-key={azureMapsSubscriptionKey}&api-version=1.0&query=52.50931,13.42936:52.50274,13.43872" // ); Console.WriteLine($"Maps Key: {azureMapsSubscriptionKey}"); return(response); }
private static async System.Threading.Tasks.Task <string> ReceiveStringAsync( WebSocket socket, System.Threading.CancellationToken ct) { System.ArraySegment <byte> buffer = new System.ArraySegment <byte>(new byte[8192]); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.Net.WebSockets.WebSocketReceiveResult result; do { ct.ThrowIfCancellationRequested(); result = await socket.ReceiveAsync(buffer, ct); ms.Write(buffer.Array, buffer.Offset, result.Count); } while (!result.EndOfMessage); ms.Seek(0, System.IO.SeekOrigin.Begin); if (result.MessageType != System.Net.WebSockets.WebSocketMessageType.Text) { return(null); } // Encoding UTF8: https://tools.ietf.org/html/rfc6455#section-5.6 using (System.IO.TextReader reader = new System.IO.StreamReader(ms, System.Text.Encoding.UTF8)) { return(await reader.ReadToEndAsync()); } } }
public async Task <Dictionary <string, string> > getExternalItems() { try { Dictionary <string, string> items = new Dictionary <string, string>(); File assetFile = new File(externalDir, ASSET_LIST_NAME); var reader = new System.IO.StreamReader(assetFile.Path); var content = await reader.ReadToEndAsync(); var lines = content.Split('\n'); foreach (string line in lines) { if (!line.Equals(String.Empty)) { String[] fields = line.Split(' '); items.Add(fields[0], fields[1]); } } return(items); } catch (Exception e) { return(new Dictionary <string, string>()); } }
public async Task <string> Post() { using (var reader = new System.IO.StreamReader(Request.Body)) { return(await reader.ReadToEndAsync()); } }
private async void btnLoad_Click(object sender, EventArgs e) { //se presenta el dialogo por defecto para abrir un archivo DialogResult result = openFileDialog1.ShowDialog(); //si se pulsa diferente de "YES" no hace ninguna acción if (result != DialogResult.OK) { return; } ///obtenemos la ruta del archivo seleccionado string filePath = openFileDialog1.FileName; ///se abre el archivo para lectura y se cierra cuando finaliza el bloque ///para evitar que el archivo se trunque using (System.IO.StreamReader streamReader = new System.IO.StreamReader(filePath)) { // se obtiene el contenido del archivo de manera asíncrona var contentFile = await streamReader.ReadToEndAsync(); //TODO: 3. Convertir JSON a un Objeto Libro //TODO: 4. Asignar valores a las cajas de texto } }
public override async Task<string> PostStringAsync(System.Net.Http.HttpClient client, Uri requestUrl, Dictionary<string, string> content, System.Threading.CancellationToken? token = null) { var strm = await GetStreamAsync(client, requestUrl, token); if (strm == null) throw new ApiErrorException("引数requestUrlで指定されたデータが見つかりませんでした。", ErrorType.ParameterError, requestUrl, null, null, null); using (var reader = new System.IO.StreamReader(strm, Encoding.UTF8)) return await reader.ReadToEndAsync(); }
/// <summary> /// /// </summary> /// <param name="isTest"></param> /// <param name="pCommand"></param> /// <param name="pLanguage"></param> /// <returns></returns> public static async Task<RootPayUQueriesPingResponse> PingTheApi(bool isTest, string pCommand, string pLanguage) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionQueriesConnectionUrl; var url = productionOrTestUrl; if (url != null) { var jsonObject = new RootPayUQueriesPingRequest() { command = pCommand, language = pLanguage, merchant = new Merchant() { apiKey = productionOrTestApiKey, apiLogin = productionOrTestApiLogIn }, test = isTest }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayUGeneralApi(url, requestJson, HttpMethod.POST); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUQueriesPingResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (Exception) { throw; } return null; }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pEnail"></param> /// <param name="pFullName"></param> /// <returns></returns> public static async Task<RootPayUCustomerCreationResponse> CreateACustomer(string pLanguage, string pEnail, string pFullName) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCustomerRecurringPaymentsUrl; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); var jsonObject = new RootPayUCustomerCreationRequest() { email = pEnail, fullName = pFullName }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson, pLanguage, pBse64, HttpMethod.POST); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUCustomerCreationResponse>(res); sr.Close(); if (des != null) { return des; } } } else if (resp.StatusCode == HttpStatusCode.Created) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUCustomerCreationResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { throw; } throw; } return null; }
private async Task<string> GetServiceUri(Uri type) { // Read the root document (usually out of the cache :)) JObject doc; var sourceUrl = new Uri(_source.Url); if (sourceUrl.IsFile) { using (var reader = new System.IO.StreamReader( sourceUrl.LocalPath)) { string json = await reader.ReadToEndAsync(); doc = JObject.Parse(json); } } else { doc = await _client.GetFile(sourceUrl); } var obj = JsonLdProcessor.Expand(doc).FirstOrDefault(); if (obj == null) { throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode); } var resources = obj[ServiceUris.Resources.ToString()] as JArray; if (resources == null) { throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode); } // Query it for the requested service var candidates = (from resource in resources.OfType<JObject>() let resourceType = resource["@type"].Select(t => t.ToString()).FirstOrDefault() where resourceType != null && Equals(resourceType, type.ToString()) select resource) .ToList(); NuGetTraceSources.V3SourceRepository.Verbose( "service_candidates", "Found {0} candidates for {1} service: [{2}]", candidates.Count, type, String.Join(", ", candidates.Select(c => c.Value<string>("@id")))); var selected = candidates.FirstOrDefault(); if (selected != null) { NuGetTraceSources.V3SourceRepository.Info( "getserviceuri", "Found {0} service at {1}", selected["@type"][0], selected["@id"]); return selected.Value<string>("@id"); } else { NuGetTraceSources.V3SourceRepository.Error( "getserviceuri_failed", "Unable to find compatible {0} service on {1}", type, _root); return null; } }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pDocument"></param> /// <param name="pExpMonth"></param> /// <param name="pExpYearm"></param> /// <param name="pName"></param> /// <param name="pAddress"></param> /// <param name="pCreditCardToken"></param> /// <returns></returns> public static async Task<RootPayUCreditCardUpdateResponse> UpdateACreditCard( string pLanguage, string pDocument, string pExpMonth, string pExpYearm, string pName, Request_Recurring_Address pAddress, string pCreditCardToken) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCreditCardRecurringPaymentsUrl + pCreditCardToken; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); var jsonObject = new RootPayUCreditCardUpdateRequest() { document = pDocument, expMonth = pExpMonth, expYear = pExpYearm, name = pName, address = pAddress, }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson, pLanguage, pBse64, HttpMethod.PUT); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUCreditCardUpdateResponse>(res); sr.Close(); if (des != null) { return des; } } } else if (resp.StatusCode == HttpStatusCode.Created) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUCreditCardUpdateResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { return new RootPayUCreditCardUpdateResponse() { token = "there migth be a problem please try again", }; } throw; } return null; }
async private Task<string> Request(string url, string method, object parameters) { Console.WriteLine ("Request to: " + "https://graph.facebook.com/v2.1" + url + "?access_token=" + UserToken); WebRequest request = WebRequest.Create ("https://graph.facebook.com/v2.1" + url + "?access_token=" + UserToken); request.UseDefaultCredentials = true; request.Method = method; string response = ""; if (request.Method == "POST") { Dictionary<string, string> parametersDictionary = new Dictionary<string, string> (); Console.WriteLine ("parameters: " + parameters); if (parameters != null) { var properties = parameters.GetType ().GetProperties (); for (int i = 0; i < properties.Length; i++) { Console.WriteLine (properties [i].Name); parametersDictionary.Add (properties [i].Name, properties [i].GetValue (parameters, null).ToString ()); } } Console.WriteLine ("parameters: " + parameters); Console.WriteLine ("parametersDictionary: " + parametersDictionary); Console.WriteLine (parametersDictionary.Keys.Count + " keys"); Console.WriteLine (parametersDictionary.Values.Count + " values"); string content = ""; var stringBuilder = new StringBuilder (); // stringBuilder.AppendFormat ("?{0}={1}&", "access_token", UserToken); foreach (var parameter in parametersDictionary) { stringBuilder.AppendFormat ("&{0}={1}", parameter.Key, parameter.Value); } content = stringBuilder.ToString (); Console.WriteLine (url); Console.WriteLine (content); byte[] byteContent = Encoding.UTF8.GetBytes(content); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteContent.Length; System.IO.Stream stream = await request.GetRequestStreamAsync ().ConfigureAwait (false); stream.Write (byteContent, 0, byteContent.Length); stream.Close (); } try { WebResponse webResponse = await request.GetResponseAsync (); System.IO.StreamReader requestHeader = new System.IO.StreamReader (webResponse.GetResponseStream ()); response = await requestHeader.ReadToEndAsync (); webResponse.Close (); } catch (WebException ex) { HttpWebResponse httpResponse = (HttpWebResponse)ex.Response; Console.WriteLine (WebExceptionStatus.ProtocolError); Console.WriteLine ("StatusCode: " + httpResponse.StatusCode); Console.WriteLine ("Status: " + ex.Status); Console.WriteLine ("Message: " + ex.Message); } return response; }
/// <summary> /// This feature allows you to make collections using a Token code that was previously created by our system, /// and which was used to store your customers’ credit cards data safely. /// </summary> /// <param name="isTest"></param> /// <param name="pCommand"></param> /// <param name="pLanguage"></param> /// <param name="pCreditCardTokenId"></param> /// <param name="pTX_VALUE"></param> /// <param name="pBuyer"></param> /// <param name="pOrderShippingAddress"></param> /// <param name="pPayer"></param> /// <param name="pExtraParameters"></param> /// <param name="pPaymentCountry"></param> /// <param name="pPaymentMethod"></param> /// <param name="pType"></param> /// <param name="pUserAgent"></param> /// <param name="pDescription"></param> /// <param name="pNotifyUrl"></param> /// <param name="pReferenceCode"></param> /// <param name="pCookie"></param> /// <param name="pDeviceSessionId"></param> /// <param name="pIpAddress"></param> /// <returns></returns> public static async Task<RootPayUIndividualPaymentWithTokenResponse> IndividualPaymentWithToken(bool isTest, string pCommand, string pLanguage, string pCreditCardTokenId, Request_TXVALUE pTX_VALUE, bool calculateTaxes, Request_IndividualPaymentWithToken_Buyer pBuyer, Address pOrderShippingAddress, Request_IndividualPaymentWithToken_Payer pPayer, Request_ExtraParameters pExtraParameters, string pPaymentCountry, string pPaymentMethod, string pType, string pUserAgent, string pDescription, string pNotifyUrl, string pReferenceCode, string pCookie, string pDeviceSessionId, string pIpAddress) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestMerchantId = ConfigurationManager.AppSettings["PAYU_API_MERCHANTID"]; int productionOrTestAccountId = int.Parse(ConfigurationManager.AppSettings["PAYU_API_ACCOUNTID"]); string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionPaymentsConnectionUrl; var url = productionOrTestUrl; if (url != null) { string source = productionOrTestApiKey + "~" + productionOrTestMerchantId + "~" + pReferenceCode + "~" + pTX_VALUE.value + "~" + pTX_VALUE.currency; MD5 md5Hash = MD5.Create(); string pSignature = CryptoHelper.GetMd5Hash(md5Hash, source); var jsonObject = new RootPayUIndividualPaymentWithTokenRequest() { command = pCommand, language = pLanguage, merchant = new Merchant() { apiKey = productionOrTestApiKey, apiLogin = productionOrTestApiLogIn }, transaction = new Request_IndividualPaymentWithToken_Transaction() { cookie = pCookie, creditCardTokenId = pCreditCardTokenId, deviceSessionId = pDeviceSessionId, userAgent = pUserAgent, ipAddress = pIpAddress, paymentCountry = pPaymentCountry, paymentMethod = pPaymentMethod, type = pType, payer = pPayer, order = new Request_IndividualPaymentWithToken_Order() { accountId = productionOrTestAccountId, buyer = pBuyer, description = pDescription, language = pLanguage, notifyUrl = pNotifyUrl, referenceCode = pReferenceCode, shippingAddress = pOrderShippingAddress, additionalValues = calculateTaxes ? new Request_AdditionalValues() { TX_VALUE = pTX_VALUE, TX_TAX = new Request_TXTAX() { currency = pTX_VALUE.currency, value = Tax_BaseReturnHelper.CalculateTaxValue(pTX_VALUE.value) }, TX_TAX_RETURN_BASE = new Request_TXTAXRETURNBASE() { currency = pTX_VALUE.currency, value = Tax_BaseReturnHelper.CalculateBaseReturnValue(pTX_VALUE.value) } } : new Request_AdditionalValues() { TX_VALUE = pTX_VALUE, TX_TAX = new Request_TXTAX() { currency = pTX_VALUE.currency, value = 0.0 }, TX_TAX_RETURN_BASE = new Request_TXTAXRETURNBASE() { currency = pTX_VALUE.currency, value = 0.0 } }, signature = pSignature }, extraParameters = pExtraParameters }, test = isTest }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayUGeneralApi(url, requestJson, HttpMethod.POST); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUIndividualPaymentWithTokenResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (Exception) { throw; } return null; }
public override async Task Invoke(IOwinContext context) { var customerService = new CustomerService(); var commerceService = new CommerceService(); var ctx = SiteContext.Current; ctx.LoginProviders = GetExternalLoginProviders(context).ToArray(); // Need to load language for all files, since translations are used within css and js // the order of execution is very important when initializing context // 1st: initialize some sort of context, especially get a list of all shops first // other methods will rely on that to be performance efficient // 2nd: find current shop from url, which context with shops will be used for ctx.Shops = await commerceService.GetShopsAsync(); // Get current language var language = this.GetLanguage(context).ToSpecificLangCode(); ctx.Language = language; var shop = this.GetStore(context, language); if (shop == null) { using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath("~/App_data/Help/nostore.html"))) { var content = await reader.ReadToEndAsync(); await context.Response.WriteAsync(content); } } else { var currency = GetStoreCurrency(context, shop); shop.Currency = currency; ctx.Shop = shop; ctx.Themes = await commerceService.GetThemesAsync(SiteContext.Current); // if language is not set, set it to default shop language if (String.IsNullOrEmpty(ctx.Language)) { language = shop.DefaultLanguage; if (String.IsNullOrEmpty(language)) { throw new HttpException(404, "Store language not found"); } CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(language); ctx.Language = language; } if (!this.IsResourceFile()) // only load settings for resource files, no need for other contents { // save info to the cookies context.Response.Cookies.Append(StoreCookie, shop.StoreId, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); context.Response.Cookies.Append(LanguageCookie, ctx.Language, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); context.Response.Cookies.Append(CurrencyCookie, shop.Currency, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated) { ctx.Customer = await customerService.GetCustomerAsync( context.Authentication.User.Identity.Name, shop.StoreId); if (ctx.Customer == null) { context.Authentication.SignOut(); } else { ctx.CustomerId = ctx.Customer.Id; } } if (ctx.Customer == null) { var cookie = context.Request.Cookies[AnonymousCookie]; if (string.IsNullOrEmpty(cookie)) { cookie = Guid.NewGuid().ToString(); var cookieOptions = new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }; context.Response.Cookies.Append(AnonymousCookie, cookie, cookieOptions); } ctx.CustomerId = cookie; } // TODO: detect if shop exists, user has access // TODO: store anonymous customer id in cookie and update and merge cart once customer is logged in ctx.Linklists = await commerceService.GetListsAsync(SiteContext.Current); ctx.PageTitle = ctx.Shop.Name; ctx.Collections = await commerceService.GetCollectionsAsync(SiteContext.Current); ctx.Pages = new PageCollection(); ctx.Forms = commerceService.GetForms(); var cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId); if (cart == null) { var dtoCart = new ApiClient.DataContracts.Cart.ShoppingCart { CreatedBy = ctx.CustomerId, CreatedDate = DateTime.UtcNow, Currency = shop.Currency, CustomerId = ctx.CustomerId, CustomerName = ctx.Customer != null ? ctx.Customer.Name : null, LanguageCode = ctx.Language, Name = "default", StoreId = shop.StoreId }; await commerceService.CreateCartAsync(dtoCart); cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId); } ctx.Cart = cart; if (context.Authentication.User.Identity.IsAuthenticated) { var anonymousCookie = context.Request.Cookies[AnonymousCookie]; if (anonymousCookie != null) { var anonymousCart = await commerceService.GetCartAsync(ctx.StoreId, anonymousCookie); if (anonymousCart != null) { ctx.Cart = await commerceService.MergeCartsAsync(anonymousCart); } } context.Response.Cookies.Delete(AnonymousCookie); } ctx.PriceLists = await commerceService.GetPriceListsAsync(ctx.Shop.Catalog, shop.Currency, new TagQuery()); ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context)); // update theme files await commerceService.UpdateThemeCacheAsync(SiteContext.Current); ctx.Blogs = commerceService.GetBlogs(SiteContext.Current); } else { ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context)); } ctx.Settings = commerceService.GetSettings( ctx.Theme.ToString(), context.Request.Path.HasValue && context.Request.Path.Value.Contains(".scss") ? "''" : null); ctx.CountryOptionTags = commerceService.GetCountryTags(); if (ctx.Shop.Currency.Equals("GBP", StringComparison.OrdinalIgnoreCase) || ctx.Shop.Currency.Equals("USD", StringComparison.OrdinalIgnoreCase)) { ctx.Shop.MoneyFormat = commerceService.CurrencyDictionary[ctx.Shop.Currency] + "{{ amount }}"; } else { ctx.Shop.MoneyFormat = "{{ amount }} " + commerceService.CurrencyDictionary[ctx.Shop.Currency]; } context.Set("vc_sitecontext", ctx); await this.Next.Invoke(context); } }
private async Task RenderHtmlContents(IOwinContext context, string page) { using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(String.Format("~/App_data/Help/{0}.html", page)))) { var content = await reader.ReadToEndAsync(); await context.Response.WriteAsync(content); } }
async private Task<string> Request(string url, string method, object parameters) { WebRequest request = WebRequest.Create ("https://api.twitter.com/1.1" + url + ".json"); // request.UseDefaultCredentials = true; ServicePointManager.Expect100Continue = false; request.Method = method; string response = ""; if (request.Method == "POST") { Dictionary<string, string> parametersDictionary = new Dictionary<string, string> (); Console.WriteLine ("parameters: " + parameters); if (parameters != null) { var properties = parameters.GetType ().GetProperties (); for (int i = 0; i < properties.Length; i++) { Console.WriteLine (properties [i].Name); parametersDictionary.Add (properties [i].Name, properties [i].GetValue (parameters, null).ToString ()); } } Console.WriteLine ("parameters: " + parameters); Console.WriteLine ("parametersDictionary: " + parametersDictionary); Console.WriteLine (parametersDictionary.Keys.Count + " keys"); Console.WriteLine (parametersDictionary.Values.Count + " values"); string content = ""; var stringBuilder = new StringBuilder (); foreach (var parameter in parametersDictionary) { stringBuilder.AppendFormat ("{0}={1}&", parameter.Key, Uri.EscapeDataString(parameter.Value)); } if (stringBuilder.Length > 0) { stringBuilder.Length--; } content = stringBuilder.ToString (); Console.WriteLine (url); Console.WriteLine (content); Console.WriteLine ("Params: " + content); byte[] byteContent = Encoding.UTF8.GetBytes(content); request.Headers.Add ("Authorization", AuthorizationHeader(parametersDictionary["status"])); request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; request.ContentLength = byteContent.Length; System.IO.Stream stream = await request.GetRequestStreamAsync ().ConfigureAwait (false); stream.Write (byteContent, 0, byteContent.Length); stream.Close (); } try { WebResponse webResponse = await request.GetResponseAsync (); System.IO.StreamReader requestHeader = new System.IO.StreamReader (webResponse.GetResponseStream ()); response = await requestHeader.ReadToEndAsync (); webResponse.Close (); } catch (WebException ex) { HttpWebResponse httpResponse = (HttpWebResponse)ex.Response; Console.WriteLine (WebExceptionStatus.ProtocolError); Console.WriteLine ("StatusCode: " + httpResponse.StatusCode); Console.WriteLine ("Status: " + ex.Status); Console.WriteLine ("Message: " + ex.Message); } return response; }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pCreditCardToken"></param> /// <returns></returns> public static async Task<RootPayUCreditCardDeleteResponse> DeleteACreditCard(string pLanguage, string pCustomerId, string pCreditCardToken) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCustomerRecurringPaymentsUrl + pCustomerId + PayU_Constants.DefaultCreditCardRecurringPaymentsUrl + pCreditCardToken; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, null, pLanguage, pBse64, HttpMethod.DELETE); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUCreditCardDeleteResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { return null; } } else { throw new Exception(ex.Message); } } return null; }
public async Task<PickedFile[]> GetSelectionResponseAsync() { UriBuilder uri = new UriBuilder("https://apis.live.net"); uri.Path = string.Format("/v5.0/{0}/files", this.SelectionId); OneDrive.QueryStringBuilder qsb = new OneDrive.QueryStringBuilder(); qsb.Add("method", "GET"); qsb.Add("interface_method", "OneDrive.open"); qsb.Add("pretty", "false"); qsb.Add("access_token", this.AccessToken); qsb.Add("suppress_redirects", "true"); uri.Query = qsb.ToString(); HttpWebRequest request = WebRequest.CreateHttp(uri.ToString()); var response = await request.GetResponseAsync() as HttpWebResponse; if (response == null) return null; if (response.StatusCode != HttpStatusCode.OK) return null; using (var responseStream = response.GetResponseStream()) { var reader = new System.IO.StreamReader(responseStream); var responseText = await reader.ReadToEndAsync(); var parsed = Newtonsoft.Json.JsonConvert.DeserializeObject<SelectionResponse>(responseText); return parsed.data; } }
public async Task<int> ExpiresInAccessTokenAsync(string accessToken) { HttpWebRequest request = null; try { request = WebRequest.Create(Settings.QueryAccessTokenUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); var parameters = new Dictionary<string, string>(); parameters.Add("access_token", accessToken); var postBody = parameters.BuildToUrlString(); var postData = System.Text.Encoding.UTF8.GetBytes(postBody); using (var requestStream = await request.GetRequestStreamAsync()) { await requestStream.WriteAsync(postData, 0, postData.Length); } var expiresIn = 0; using (var response = await request.GetResponseAsync()) { using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { var result = await sr.ReadToEndAsync(); var regex = new Regex(Constants.OAuth2AccessTokenExpiresInPattern); var match = regex.Match(result); if (match == null) { return expiresIn; } var strExpiresIn = match.Groups["expires_in"].Value; var parseResult = int.TryParse(strExpiresIn, out expiresIn); return expiresIn; } } } finally { if (request != null) request.Abort(); } }
public static void Listing(Uri uri, Func<string, bool> where, Action<IEnumerable<Uri>> result) { try { var req = System.Net.WebRequest.Create(uri); var resp = (System.Net.HttpWebResponse)req.GetResponse(); var s = new System.IO.StreamReader(resp.GetResponseStream()); s.ReadToEndAsync().ContinueWith(r => { using (resp) using (s) result(listing .Matches(r.Result ?? "") .OfType<System.Text.RegularExpressions.Match>() .Select(m => m.Groups[1].Value) .Where(where) .Select(x => new Uri(uri, x))); }); } catch { } }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pDescription"></param> /// <param name="pInterval"></param> /// <param name="pIntervalCount"></param> /// <param name="pMaxPaymentsAllowed"></param> /// <param name="pPaymentAttemptsDelay"></param> /// <param name="pMaxPaymentAttempts"></param> /// <param name="pMaxPendingPayments"></param> /// <param name="pPlanCode"></param> /// <param name="pAdditionalValues"></param> /// <returns></returns> public static async Task<RootPayUPlanCreationResponse> CreateAPlan(string pLanguage, string pDescription, string pInterval, string pIntervalCount, string pMaxPaymentsAllowed, string pMaxPaymentAttempts, string pMaxPendingPayments, string pTrialDays, string pPaymentAttemptsDelay, string pPlanCode, List<Request_Recurring_AdditionalValue> pAdditionalValues) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestAccountId = ConfigurationManager.AppSettings["PAYU_API_ACCOUNTID"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultPlanRecurringPaymentsUrl; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); var jsonObject = new RootPayUPlanCreationRequest() { accountId = productionOrTestAccountId, description = pDescription, interval = pInterval, intervalCount = pIntervalCount, maxPaymentsAllowed = pMaxPaymentsAllowed, paymentAttemptsDelay = pPaymentAttemptsDelay, planCode = pPlanCode, maxPaymentAttempts = pMaxPaymentAttempts, maxPendingPayments = pMaxPendingPayments, trialDays = pTrialDays, additionalValues = pAdditionalValues }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson, pLanguage, pBse64, HttpMethod.POST); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUPlanCreationResponse>(res); sr.Close(); if (des != null) { return des; } } } else if (resp.StatusCode == HttpStatusCode.Created) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUPlanCreationResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { throw; } throw; } return null; }
/// <summary> /// Get AccessToken Async /// </summary> /// <param name="grantType">authorization_code、password、refresh_token</param> /// <param name="parameters"></param> /// <returns></returns> internal async Task<OAuthAccessToken> GetAccessTokenAsync(GrantType grantType, Dictionary<string, string> parameters) { if (parameters == null || parameters.Count == 0) { throw new ArgumentException("GetAccessTokenAsync Parameters is invalid."); } HttpWebRequest request = null; try { request = WebRequest.Create(Settings.AccessTokenUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); parameters.Add("client_id", Settings.AppKey); parameters.Add("client_secret", Settings.AppSecret); var grant_type = ""; switch (grantType) { case GrantType.AuthorizationCode: grant_type = "authorization_code"; break; case GrantType.Password: grant_type = "password"; break; case GrantType.RefreshToken: grant_type = "refresh_token"; break; default: grant_type = "authorization_code"; break; } parameters.Add("grant_type", grant_type); var postBody = parameters.BuildToUrlString(); var postData = System.Text.Encoding.UTF8.GetBytes(postBody); using (var requestStream = await request.GetRequestStreamAsync()) { await requestStream.WriteAsync(postData, 0, postData.Length); } using (var response = await request.GetResponseAsync()) { using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { var result = await sr.ReadToEndAsync(); return ConvertToAccessTokenByRegex(result); } } } finally { if (request != null) request.Abort(); } }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pInstallments"></param> /// <param name="pTrialDays"></param> /// <param name="pCustomer"></param> /// <param name="pPlan"></param> /// <returns></returns> public static async Task<RootPayUSubscriptionCreationNewPlanResponse> CreateASubscriptionNewPlan(string pLanguage, string pInstallments, string pTrialDays, Request_Subscription_Creation_NewPlan_Customer pCustomer, Request_Subscription_Creation_NewPlan_Plan pPlan) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultSubscriptionRecurringPaymentsUrl; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); var jsonObject = new RootPayUSubscriptionCreationNewPlanRequest() { installments = pInstallments, trialDays = pTrialDays, customer = pCustomer, plan = pPlan }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson, pLanguage, pBse64, HttpMethod.POST); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUSubscriptionCreationNewPlanResponse>(res); sr.Close(); if (des != null) { return des; } } } else if (resp.StatusCode == HttpStatusCode.Created) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUSubscriptionCreationNewPlanResponse>(res); sr.Close(); if (des != null) { return des; } } } else { throw new Exception(resp.StatusCode + "; " + resp.StatusDescription); } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { return null; } } else { throw new Exception(ex.Message); } } return null; }
public async Task<HttpProgressInfo> ExecuteRequestAsync(string url, Dictionary<string,string> headers = null, string method = "GET", JToken body = null) { var pi = new HttpProgressInfo(); pi.Url = new Uri(url); pi.Method = method; pi.RequestHeaders = new WebHeaderCollection(); var req = WebRequest.CreateHttp(url); req.Method = method; if (headers != null) { foreach (var i in headers) { req.Headers.Add(i.Key, i.Value); pi.RequestHeaders.Add(i.Key, i.Value); } } pi.RequestBody = body == null ? null : body.DeepClone(); pi.RequestStarted = DateTime.UtcNow; pi.State = HttpTransactionState.Started; OnProgress(pi); if (body != null) { using (var rs = await req.GetRequestStreamAsync()) using (var sw = new System.IO.StreamWriter(rs)) { await sw.WriteAsync(body.ToString(Formatting.None)); } } pi.RequestCompleted = DateTime.UtcNow; pi.State = HttpTransactionState.RequestSent; OnProgress(pi); var res = (HttpWebResponse)await req.GetResponseAsync(); pi.State = HttpTransactionState.HeadersReceived; pi.ResponseStarted = DateTime.UtcNow; pi.ResponseStatus = res.StatusCode; pi.ResponseStatusDescription = res.StatusDescription; pi.ResponseHeaders = res.Headers; OnProgress(pi); using (var rs = res.GetResponseStream()) using (var sr = new System.IO.StreamReader(rs, Encoding.UTF8)) { var dataText = await sr.ReadToEndAsync(); pi.State = HttpTransactionState.Complete; pi.ResponseCompleted = DateTime.UtcNow; if (!string.IsNullOrWhiteSpace(dataText)) { var tok = JToken.Parse(dataText); pi.ResponseBody = tok; } } OnProgress(pi); return pi; }
/// <summary> /// /// </summary> /// <param name="pLanguage"></param> /// <param name="pSubscriptionId"></param> /// <param name="pDescription"></param> /// <param name="pAdditionalValues"></param> /// <param name="pRecurringBillItemId"></param> /// <returns></returns> public static async Task<RootPayUAdditionalChargesUpdateResponse> UpdateAnAdditionalCharge(string pLanguage, string pDescription, List<Request_Recurring_AdditionalValue> pAdditionalValues, string pRecurringBillItemId) { try { string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"]; string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"]; string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl; if (!string.IsNullOrWhiteSpace(productionOrTestUrl)) { productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultAdditionalChargesRecurringPaymentsUrl + pRecurringBillItemId; string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey; string pBse64 = CryptoHelper.GetBase64Hash(source); var jsonObject = new RootPayUAdditionalChargesUpdateRequest() { description = pDescription, additionalValues = pAdditionalValues }; string requestJson = JsonConvert.SerializeObject(jsonObject); HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson, pLanguage, pBse64, HttpMethod.PUT); if (resp == null) return null; if (resp.StatusCode == HttpStatusCode.OK) { using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { string res = await sr.ReadToEndAsync(); var des = JsonConvert.DeserializeObject<RootPayUAdditionalChargesUpdateResponse>(res); sr.Close(); if (des != null) { return des; } } } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { return null; } } else { throw new Exception(ex.Message); } } return null; }