private async Task<string> Create() { string sql; var assembly = typeof(TestDatabase).GetTypeInfo().Assembly; using (var reader = new StreamReader(assembly.GetManifestResourceStream(_sqlFile))) { sql = await reader.ReadToEndAsync(); } var dbName = await CreateDatabase(); var connectionString = $"Server=localhost;Port=5432;Database={_databaseName};User Id=postgres;Password=s1mpl3;"; using (var connection = new NpgsqlConnection(connectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { foreach ( var statement in Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline) .Where(s => !string.IsNullOrWhiteSpace(s))) { //_logger.LogDebug(sql); command.CommandText = statement; await command.ExecuteNonQueryAsync(); } } } return _connectionString = connectionString; }
private async void btnRead_Click(object sender, EventArgs e) { tbData.Clear(); try { //create dir if it does not exists if (!Directory.Exists(PathToFile)) { throw new IOException(); } using (StreamReader sr = new StreamReader(Path.Combine(PathToFile, FileName))) { var readText = ""; readText = await sr.ReadToEndAsync(); tbData.Text = readText; } } catch (IOException ex) { //catch error MessageBox.Show(ex.Message, @"Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async Task<string> GetPageText(string page) { string result = ""; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(page); using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false)) { using (StreamReader stream = new StreamReader(response.GetResponseStream())) { result = await stream.ReadToEndAsync().ConfigureAwait(false); return result; } } } catch (WebException) { return ""; } catch (UriFormatException) { return ""; } }
/// <summary> /// Async method, return Response xmlDocument /// </summary> /// <param name="xmlRequest">xml request document</param> /// <returns></returns> public static async Task<XmlDocument> SendRequestXmlDocumentAsync(XmlDocument xmlRequest) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.novaposhta.ua/v2.0/xml/"); httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.ContentType = @"application/x-www-form-urlencoded"; ServicePointManager.DefaultConnectionLimit = 2000; var streamOut = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()); await streamOut.WriteAsync(xmlRequest.InnerXml); //streamOut.Flush(); streamOut.Close(); //In Stream var response = (await httpWebRequest.GetResponseAsync()).GetResponseStream(); if (response == null) return null; var streamIn = new StreamReader(response); string strResponse = await streamIn.ReadToEndAsync(); streamIn.Close(); response.Close(); //Load XML data to XmlDocument var xmlResponse = new XmlDocument(); xmlResponse.LoadXml(strResponse); return xmlResponse; }
public void With_WebSocket_CanReadTwoBufferedSmallFrames() { var handshake = GenerateSimpleHandshake(); using (var ms = new MemoryStream()) using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions)) { ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8); ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); var reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNotNull(reader); using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true)) { String s = sr.ReadToEnd(); Assert.AreEqual("Hi", s); } reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNotNull(reader); using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true)) { String s = sr.ReadToEndAsync().Result; Assert.AreEqual("Hi", s); } reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNull(reader); } }
private async void FirstVariant_Click(object sender, RoutedEventArgs e) { _task.Visibility = Visibility.Hidden; next.Visibility = Visibility.Visible; UserText.Visibility = Visibility.Hidden; var1Task.Visibility = Visibility.Visible; try { using (StreamReader sr = new StreamReader("../../../Writing/var1Task2.txt")) { string line = await sr.ReadToEndAsync(); var1Task.Text = line; } } catch (FileNotFoundException) { MessageBox.Show("File with writing rask not found"); } Help.MouseLeave += Help_MouseLeave; next.Click += next_Click; UserText.TextChanged -= UserText_TextChanged1; UserText.TextChanged -= UserText_TextChanged2; UserText.TextChanged += UserText_TextChanged; FirstVariant.IsEnabled = false; SecondVariant.IsEnabled = true; ThirdVariant.IsEnabled = true; }
public static async Task<List<TodoItem>> GetItemsAsync (Context context, int count = 0) { if (cache == null) { using (StreamReader sr = new StreamReader (context.Assets.Open ("tasks.json"))) { string data = await sr.ReadToEndAsync (); cache = await Task.Run (() => { var list = JsonConvert.DeserializeObject<List<TodoItem>> (data); List<TodoItem> items = new List<TodoItem> (list); while (items.Count < count) items.AddRange (list); return items; }); } } else { Random rng = new Random (); int n = cache.Count; while (n > 1) { n--; int k = rng.Next (n + 1); var value = cache [k]; cache [k] = cache [n]; cache [n] = value; } } return cache; }
public async Task Invoke(HttpContext context) { using (var memoryStream = new MemoryStream()) { var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { { memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { string body = await streamReader.ReadToEndAsync(); body = MinifyHtml(body); using (var minBodyStream = new MemoryStream()) using (var streamWriter = new StreamWriter(minBodyStream)) { streamWriter.Write(body); streamWriter.Flush(); minBodyStream.Seek(0, SeekOrigin.Begin); await minBodyStream.CopyToAsync(bodyStream); } } } } } }
private async Task <string> GetJSONResponseAsync(string url) { var http = (HttpWebRequest)WebRequest.Create(new Uri(url)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "POST"; System.Net.WebResponse resp; try { if (YetaWFManager.IsSync()) { resp = http.GetResponse(); } else { resp = await http.GetResponseAsync(); } } catch (Exception exc) { throw new InternalError("An error occurred retrieving exchange rates from openexchangerates.org - {0}", ErrorHandling.FormatExceptionMessage(exc)); } using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { if (YetaWFManager.IsSync()) { return(sr.ReadToEnd().Trim()); } else { return((await sr.ReadToEndAsync()).Trim()); } } }
internal static async Task<Character> LoadFromFileAsync (string filename, Rules rules) { Character character = null; Stopwatch timer = Stopwatch.StartNew(); try { string xmlString; using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true)) { using (var reader = new StreamReader(file)) { xmlString = await reader.ReadToEndAsync(); } } // cleanup campaign settings // CBuilder sometimes seems to insert invalid XML values? var endStr = "</D20CampaignSetting>"; int start = xmlString.IndexOf("<D20CampaignSetting"); int end = xmlString.IndexOf(endStr) + endStr.Length; if (start != -1 && end != -1 && start < end) { xmlString = xmlString.Remove(start, end - start + 1); } ImportCharacter import = await xmlString.DeserializeXmlAsync<ImportCharacter>(); character = import.ToCharacter(rules); } finally { timer.Stop(); Trace.TraceInformation("Deserializing Character [{0}] from CB took {1}ms", Path.GetFileName(filename), timer.ElapsedMilliseconds); } return character; }
/// <summary> /// Performs web request and gets the weather from the service. /// </summary> /// <returns>The weather.</returns> /// <param name="location">Location to get the weather</param> public static async Task<WeatherData> GetWeather(Location location) { WeatherData result = null; string weatherUrl = string.Format (WEATHER_URL, EnumHelper.GetDescription (Subscription.Subscript.free), location.city, NUMBER_OF_DAYS.ToString (), ApplicationSettingsHelper.API_KEY); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherUrl); using(WebResponse response = await request.GetResponseAsync()) { using (Stream resStream = response.GetResponseStream ()) { using (StreamReader reader = new StreamReader (resStream)) { string jsonResult = await reader.ReadToEndAsync (); result = JsonConvert.DeserializeObject<WeatherData> (jsonResult); } } } int length1 = result.data.weather.Length; int length2 = result.data.weather[0].hourly.Length; // TODO: investigate ho w to run this tasks in Parallel for( int i = 0; i < length1; i++){ for(int j = 0; j < length2; j++) { //taskArray[i*length2 + j] = Task.Factory.StartNew(async () => { await GetWeatherImageFile (result.data.weather[i].hourly[j].weatherIconUrl[0].value); }); await GetWeatherImageFile (result.data.weather[i].hourly[j].weatherIconUrl[0].value); } } return result; }
public async Task<AzureToken> LoadToken(string subscriptionId) { string path = Path.Combine(_root, "Subscriptions", subscriptionId + ".dat"); if (!File.Exists(path)) { return null; } string content = null; using (var reader = new StreamReader(path)) { content = await reader.ReadToEndAsync(); } if (content == null) { return null; } var unprotected = Encoding.UTF8.GetString( ProtectedData.Unprotect( Convert.FromBase64String(content), null, DataProtectionScope.CurrentUser)); return JsonFormat.Deserialize<AzureToken>(unprotected); }
public async Task Invoke(IDictionary<string, object> env) { IOwinContext context = new OwinContext(env); // Buffer the request body var requestBuffer = new MemoryStream(); await context.Request.Body.CopyToAsync( requestBuffer); requestBuffer.Seek(0, SeekOrigin.Begin); context.Request.Body = requestBuffer; // Read the body var reader = new StreamReader(context.Request.Body); string content = await reader.ReadToEndAsync(); // Seek to the beginning of the stream for the // other components to correctly read the request body. ((MemoryStream)context.Request.Body) .Seek(0, SeekOrigin.Begin); Console.WriteLine(content); await this.next(env); }
public async Task <ValidationResult> ProcessEquipmentSubmission(HttpContext context) { System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.Body); //TODO: handle encoding (UTF etc) correctly string responseContent = await sr.ReadToEndAsync(); string jsonString = responseContent.Trim(); try { JObject o = JObject.Parse(jsonString); JsonSerializer serializer = new JsonSerializer(); var cp = (Common.Model.ChargePoint)serializer.Deserialize(new JTokenReader(o), typeof(Common.Model.ChargePoint)); //validate cp submission return(POIManager.IsValid(cp)); } catch (Exception exp) { System.Diagnostics.Debug.WriteLine(exp); //submission failed return(new ValidationResult { IsValid = false, Message = "Exception processing submission:" + exp.Message }); } }
internal async Task<IPackageMetaData> GetPackageMetaData(string providerName) { string rootCacheDir = Environment.ExpandEnvironmentVariables(Defaults.CachePath); string metaPath = Path.Combine(rootCacheDir, providerName, Name, "metadata.json"); try { if (!File.Exists(metaPath)) { string url = string.Format(_metaPackageUrlFormat, Name); Directory.CreateDirectory(Path.GetDirectoryName(metaPath)); using (WebClient client = new WebClient()) { // When this is async, it deadlocks when called from FileCompletionProvider.cs await Task.Run(() => client.DownloadFile(url, metaPath)).ConfigureAwait(false); } } using (StreamReader reader = new StreamReader(metaPath)) { string json = await reader.ReadToEndAsync().ConfigureAwait(false); if (!string.IsNullOrEmpty(json)) { return JsonConvert.DeserializeObject<CdnjsMetaData>(json); } } } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } return null; }
private async Task<string> GetRequestToken() { try { const string requestTokenUrl = "http://api.moefou.org/oauth/request_token"; const string httpMethod = "GET"; Uri url = new Uri(requestTokenUrl); string timeStamp = this.OAuth.GenerateTimeStamp(); string nonce = this.OAuth.GenerateNonce(); string nUrl = null; string pa = null; string signature = this.OAuth.GenerateSignature(url, AppConst.MoeAppKey, AppConst.ConsumerSecret, string.Empty, string.Empty, httpMethod, timeStamp, nonce, string.Empty, out nUrl, out pa); List<QueryParameter> parameters = new List<QueryParameter>(); string requestUrl = string.Format("{0}?{1}&{2}={3}", nUrl, pa, OAuthBase.OAuthSignatureKey, signature); WebRequest request = WebRequest.Create(requestUrl); WebResponse response = await request.GetResponseAsync(); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { List<QueryParameter> reqPa = this.OAuth.GetQueryParameters(await sr.ReadToEndAsync()); var oauth_token = reqPa.Find(qp => qp.Name.Equals("oauth_token")).Value; var oauth_token_secret = reqPa.Find(qp => qp.Name.Equals("oauth_token_secret")).Value; //将为授权的token放入到 Windows.Storage.ApplicationData.Current.LocalSettings.Values["oauth_token"] = oauth_token; Windows.Storage.ApplicationData.Current.LocalSettings.Values["oauth_token_secret"] = oauth_token_secret; } return string.Empty; } catch (Exception) { throw; } }
private async Task LoadScriptPreview(string scriptPath) { this.ScriptTextBox.Text = string.Empty; this.lblScriptName.Text = string.Empty; if (string.IsNullOrEmpty(scriptPath)) { return; } if (System.IO.File.Exists(scriptPath)) { lblScriptName.Text = System.IO.Path.GetFileName(scriptPath); try { //this.ScriptTextBox.Text = System.IO.File.ReadAllText(scriptPath); using (var sr = new System.IO.StreamReader(scriptPath)) { this.ScriptTextBox.Text = await sr.ReadToEndAsync(); } } catch (Exception ex) { this.ScriptTextBox.Text = "ERROR:" + Environment.NewLine + ex.Message; } } }
public static async Task<bool> UpdateAvailable() { WebRequest request = WebRequest.Create(VersionLocation); WebResponse response = await request.GetResponseAsync(); string answer = ""; using(Stream responseStream = response.GetResponseStream()) using(StreamReader sr = new StreamReader(responseStream)) answer = await sr.ReadToEndAsync(); answer = answer.Replace("\n", ""); answer = answer.Replace("\r", ""); answer = answer.Trim(); try { DateTime lastUpdate = DateTime.ParseExact(answer, "yyyy-MM-dd", CultureInfo.InvariantCulture); if (lastUpdate.CompareTo(BuildDate) > 0) return true; else return false; } catch { return false; } }
public static async Task<string> GetAsync(string remoteAddr, bool supressErrors = false) { string remoteResponse = string.Empty; try { DateTime began = DateTime.UtcNow; // Request WebRequest request = WebRequest.Create(remoteAddr); request.Method = "GET"; using (var response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream streamResponse = response.GetResponseStream()) using (StreamReader streamReader = new StreamReader(streamResponse)) remoteResponse = await streamReader.ReadToEndAsync(); var timeDiff = DateTime.Now - began; } catch (WebException ex) { if (!supressErrors) { if (!supressErrors) throw ex; //throw new System.Exception("A required external service is not available!", ex); } } return remoteResponse; }
private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account) { HttpWebRequest request = WebRequest.CreateHttp(account.TokenService); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; var requestStream = await request.GetRequestStreamAsync(); var writer = new StreamWriter(requestStream); StringBuilder sb = new StringBuilder(); sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId)); sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri)); sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret)); sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken)); sb.Append("&grant_type=refresh_token"); if (null != account.Resource) sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource)); var content = sb.ToString(); await writer.WriteAsync(content); await writer.FlushAsync(); var response = await request.GetResponseAsync() as HttpWebResponse; if (null != response && response.StatusCode == HttpStatusCode.OK) { var responseStream = response.GetResponseStream(); if (null != responseStream) { var reader = new StreamReader(responseStream); return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync()); } } return null; }
private async void SendRequest() { try { using (ISitecoreWebApiSession session = this.instanceSettings.GetSession()) { var request = ItemWebApiRequestBuilder.RenderingHtmlRequestWithSourceAndRenderingId(sourceIdTextField.Text, renderingIdTextField.Text) .Build(); this.ShowLoader(); Stream response = await session.ReadRenderingHtmlAsync(request); response.Position = 0; string htmlText = ""; using (StreamReader reader = new StreamReader(response)) { htmlText = await reader.ReadToEndAsync(); } this.resultWebView.LoadHtmlString(htmlText, null); } } catch(Exception e) { AlertHelper.ShowLocalizedAlertWithOkOption("Error", e.Message); } finally { BeginInvokeOnMainThread(delegate { this.HideLoader(); }); } }
public static async Task <string> ReadStringFromSelectedFile() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".txt"); picker.FileTypeFilter.Add(".dat"); picker.FileTypeFilter.Add("."); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { await System.Threading.Tasks.Task.Run(async() => { var storedFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path); using (var readStream = await storedFile.OpenReadAsync()) using (var sr = new System.IO.StreamReader(readStream.AsStream())) { return(sr.ReadToEndAsync()); } }); } return(null); }
public static async Task <MetricsRow> ReadMetrics(string path) { string text; using (System.IO.StreamReader reader = new System.IO.StreamReader(path)) { text = await reader.ReadToEndAsync(); } var root = XElement.Parse(text); var target = root.Element("Targets").Element("Target"); var assemblyName = target.Attribute("Name").Value; var metricsElement = target.Element("Assembly").Element("Metrics"); return(new MetricsRow() { ProjectName = assemblyName, ClassCoupling = ReadMetricsValue(metricsElement, "ClassCoupling"), CyclomaticComplexity = ReadMetricsValue(metricsElement, "CyclomaticComplexity"), MaintainabilityIndex = ReadMetricsValue(metricsElement, "MaintainabilityIndex"), DepthOfInheritance = ReadMetricsValue(metricsElement, "DepthOfInheritance"), SourceLines = ReadMetricsValue(metricsElement, "SourceLines") }); }
public async Task <IEnumerable <MonsterResume> > ListAllResumePerRegion(int regionId) { Pokedex pokedex = null; //var var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MonsterRepository)).Assembly; Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.pokedex_{regionId}.json"); string json = ""; using (var reader = new System.IO.StreamReader(stream)) { json = await reader.ReadToEndAsync(); } if (!string.IsNullOrEmpty(json)) { pokedex = Newtonsoft.Json.JsonConvert.DeserializeObject <Pokedex>(json); } else { pokedex = await DataFetcher.GetApiObject <Pokedex>(regionId); } return(pokedex.Entries.Select(x => new MonsterResume { Id = x.EntryNumber, Name = x.Species.Name, ImagePath = $"{IMAGE_DEFAULT}{x.EntryNumber}{IMAGE_EXTENSION}" })); }
public async Task ResponseLimit() { var client = CreateClient(); var url = BaseUrl + "/000/" + Guid.NewGuid().ToString(); var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming"); var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); string msg = "\"" + new string('x', 128) + "\""; int nrOfMessages = 31; for (int i = 0; i < nrOfMessages; i++) { var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[" + msg + "]", Encoding.UTF8, "application/json")); Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); var contentStream = await response.Content.ReadAsStreamAsync(); var reader = new StreamReader(contentStream); var prelude = await reader.ReadLineAsync(); var open = await reader.ReadLineAsync(); Assert.Equal(new string('h', 2048), prelude); Assert.Equal("o", open); var remaining = await reader.ReadToEndAsync(); Assert.Equal(string.Concat(Enumerable.Repeat("a[" + msg + "]\n", nrOfMessages)), remaining); }
public static async Task <CollectionConfiguration> LoadConfig(string path) { if (!File.Exists(path)) { return(null); } string text; using (System.IO.StreamReader reader = new System.IO.StreamReader(path)) { text = await reader.ReadToEndAsync(); } var root = XElement.Parse(text); var config = new CollectionConfiguration(); config.MsBuildPath = root.Element(nameof(config.MsBuildPath)).Value; config.RootDirectory = root.Element(nameof(config.RootDirectory)).Value; string collectionStringValue = root.Element(nameof(config.CollectionMethod)).Value; config.CollectionMethod = (CollectionMethod)Enum.Parse(typeof(CollectionMethod), collectionStringValue); return(config); }
public static async Task<string> ReadAllTextFromFileAsync(string path) { using (var streamReader = new StreamReader(File.OpenRead(path))) { return await streamReader.ReadToEndAsync(); } }
public async Task<string> LoadByKeyAsync(string key) { using (await _asyncLock.LockAsync()) { var fileName = "cache_" + key; var existsFile = await ApplicationData.Current.LocalCacheFolder.TryGetItemAsync(fileName); //var existsFile = await FileSystem.Current.LocalStorage.CheckExistsAsync(fileName); if (existsFile != null) { using (var stream = (await ((StorageFile)existsFile).OpenStreamForReadAsync())) { using (var dataReader = new StreamReader(stream, Encoding.UTF8)) { var res = await dataReader.ReadToEndAsync(); return res; } } } return null; } }
public async Task<string> GetJsonAsync(double lat, double lon) { Uri uri = new Uri(string.Format( "http://maps.google.com/maps/api/geocode/json?address=" + lat + "%2C" + lon + "&sensor=false&language=ja")); try { using (var client = new HttpClient()) { var response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); // StatusCode が 200 以外なら Exception using (var stream = await response.Content.ReadAsStreamAsync()) { using (var streamReader = new StreamReader(stream)) { var json = await streamReader.ReadToEndAsync(); var res = JsonConvert.DeserializeObject<RootObject>(json); // Latitude, Longitude を投げると results の最初のフルアドレスが返ってくるようなので決め打ちですw return res.results[0].formatted_address; } } } } catch (Exception e) { #if DEBUG System.Diagnostics.Debug.WriteLine("***Error***: {0}\n{1}\n{2}", e.Source, e.Message, e.InnerException); #endif return null; //res = null; } }
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<string> ReadContentAsStringAsync() { using (var sr = new StreamReader(this.Content)) { return await sr.ReadToEndAsync(); } }
/// <summary> /// Loads data from csv file into List of PodatakViewModels to show in grid. /// </summary> /// <param name="filePath">Csv file path (directory + "podaci.csv")</param> /// <returns>List</returns> private async Task <List <PodatakViewModel> > LoadCsvDataFrom(string filePath) { List <PodatakViewModel> pom = new List <PodatakViewModel>(); if (System.IO.File.Exists(filePath)) { using (System.IO.StreamReader objReader = new System.IO.StreamReader(filePath, System.Text.Encoding.UTF8)) { var contents = await objReader.ReadToEndAsync(); using (System.IO.StringReader strReader = new System.IO.StringReader(contents)) { do { var textLine = await strReader.ReadLineAsync(); if (textLine != string.Empty) { pom.Add(new PodatakViewModel( textLine.Split(';') )); } } while (strReader.Peek() != -1); } } } return(pom); }
private async void TimerCallback(object state) { try { using (var stream = await _httpClient.Get(new HttpRequestOptions { Url = "http://bot.whatismyipaddress.com/" }).ConfigureAwait(false)) { using (var reader = new StreamReader(stream)) { var address = await reader.ReadToEndAsync().ConfigureAwait(false); if (IsValid(address)) { ((ConnectManager) _connectManager).OnWanAddressResolved(address); CacheAddress(address); } } } } catch { } }
/// <summary> /// 根据手机号码获取号码属地 /// </summary> /// <param name="_PhoneNum"></param> /// <returns></returns> public async Task<PhoneSearchGetBak> GetProvByPhoneNum(string _PhoneNum) { if (string.IsNullOrWhiteSpace(_PhoneNum)) return null; string _url = "http://shop.10086.cn/i/v1/res/numarea/" + _PhoneNum; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url); request.Method = "GET"; request.KeepAlive = true; request.CookieContainer = new CookieContainer(); using (HttpWebResponse mResponse = (HttpWebResponse)request.GetResponse()) { cookie = request.CookieContainer;//如果用不到Cookie,删去即可 using (Stream mStream = mResponse.GetResponseStream()) { using (StreamReader myStreamReader = new StreamReader(mStream, Encoding.GetEncoding("utf-8"))) { string retString = await myStreamReader.ReadToEndAsync(); return JsonConvert.DeserializeObject<PhoneSearchGetBak>(retString); } } } } catch (Exception) { } return null; }
public async Task Invoke(HttpContext context) { var sw = new Stopwatch(); sw.Start(); using (var memoryStream = new MemoryStream()) { var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { var responseBody = await streamReader.ReadToEndAsync(); //C# 6 DEMO var newFooter = string.Format($"<footer><div id='process'>Page processed in {sw.ElapsedMilliseconds} milliseconds.</div>"); responseBody = responseBody.Replace("<footer>", newFooter); context.Response.Headers.Add("X-ElapsedTime", new[] { sw.ElapsedMilliseconds.ToString() }); using (var amendedBody = new MemoryStream()) using (var streamWriter = new StreamWriter(amendedBody)) { streamWriter.Write(responseBody); amendedBody.Seek(0, SeekOrigin.Begin); await amendedBody.CopyToAsync(bodyStream); } } } } }
private async Task GoGoGo() { var webRequest = WebRequest.Create(GetUrl()); //获取或设置用于对 Internet 资源请求进行身份验证的网络凭据 webRequest.Credentials = CredentialCache.DefaultNetworkCredentials; StringBuilder sb = new StringBuilder(); sb.AppendFormat("该请求的协议方法:{0}\n", webRequest.Method); sb.AppendFormat("访问Internet的网络代理:{0}\n", webRequest.Proxy); sb.AppendFormat("请求数据的内容长度:{0}\n", webRequest.ContentLength); sb.AppendFormat("与该请求关联的URI:{0}\n", webRequest.RequestUri); sb.AppendFormat("获取或设置请求超时之前的时间(毫秒):{0}\n", webRequest.Timeout); //客户端不应该创建Response,而是通过WebRequest的GetResponse方法进行创建 var webResponse = await webRequest.GetResponseAsync(); sb.AppendFormat("响应请求的URI:{0}\n", webResponse.ResponseUri); //获取返回数据流 using (var stream = webResponse.GetResponseStream()) { using (var reader = new StreamReader(stream)) { sb.AppendLine(await reader.ReadToEndAsync()); } } rtxt1.Text = sb.ToString(); }
public async Task PackageFeedCountParameterTest() { var request = WebRequest.Create(UrlHelper.V2FeedRootUrl + @"stats/downloads/last6weeks/"); var response = await request.GetResponseAsync(); string responseText; using (var sr = new StreamReader(response.GetResponseStream())) { responseText = await sr.ReadToEndAsync(); } string[] separators = { "}," }; int packageCount = responseText.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; // Only verify the stats feed contains 500 packages for production if (UrlHelper.BaseUrl.ToLowerInvariant() == Constants.NuGetOrgUrl) { Assert.True(packageCount == 500, "Expected feed to contain 500 packages. Actual count: " + packageCount); } request = WebRequest.Create(UrlHelper.V2FeedRootUrl + @"stats/downloads/last6weeks?count=5"); // Get the response. response = await request.GetResponseAsync(); using (var sr = new StreamReader(response.GetResponseStream())) { responseText = await sr.ReadToEndAsync(); } packageCount = responseText.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; Assert.True(packageCount == 5, "Expected feed to contain 5 packages. Actual count: " + packageCount); }
private async void OnTSBOpenFileClick(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Текстовые файлы (*.txt)|*.txt;*.dat;*.ini;*.cpp;*.h;*.cs"; if(ofd.ShowDialog() == DialogResult.OK) { ACTBMainInput.Enabled = false; if(sender == TSBOpenFile) { ACTBMainInput.Clear(); } try { using (StreamReader reader = new StreamReader(ofd.FileName)) { ACTBMainInput.Text += await reader.ReadToEndAsync(); } } catch (Exception) { MessageBox.Show("При чтении файлп произошла ошибка!","Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { ACTBMainInput.Enabled = true; } } }
/// <summary> ///post 提交数据到服务器 /// </summary> /// <param name="postUrl">post地址</param> /// <param name="json">Json数据</param> /// <returns></returns> private async Task <string> HttpGet(string postUrl, int timeout = 10 * 1000) { string result_msg = ""; try { string formUrl = postUrl; // 设置提交的相关参数 HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest; Encoding myEncoding = Encoding.UTF8; request.Method = "GET"; request.KeepAlive = false; request.Timeout = timeout; request.AllowAutoRedirect = true; request.ContentType = "text/html;charset=UTF-8"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"))) { result_msg = await reader.ReadToEndAsync(); } } } } catch (Exception ex) { result_msg = ex.ToString(); } return(result_msg); }
private static async Task WriteWebRequestSizeAsync( string url) { try { WebRequest webRequest = WebRequest.Create(url); WebResponse response = await webRequest.GetResponseAsync(); using(StreamReader reader = new StreamReader( response.GetResponseStream())) { string text = await reader.ReadToEndAsync(); Console.WriteLine( FormatBytes(text.Length)); } } catch(WebException) { // ... } catch(IOException) { // ... } catch(NotSupportedException) { // ... } }
public static async Task <string> getRawBodyAsync(Stream bodyStream) { using (System.IO.StreamReader reader = new System.IO.StreamReader(bodyStream, System.Text.Encoding.UTF8)) { var result = await reader.ReadToEndAsync(); return(result); } }
public async Task <bool> ProcessMediaItemSubmission(string uploadPath, HttpContext context, MediaItem mediaItem, int userId) { try { var sr = new System.IO.StreamReader(context.Request.Body); string jsonContent = await sr.ReadToEndAsync(); var submission = JsonConvert.DeserializeObject <Common.Model.Submissions.MediaItemSubmission>(jsonContent); if (submission.ImageDataBase64 == null) { return(false); } string filePrefix = DateTime.UtcNow.Millisecond.ToString() + "_"; var tempFiles = new List <string>(); string tempFolder = uploadPath + "\\"; string tmpFileName = tempFolder + filePrefix + submission.ChargePointID; if (submission.ImageDataBase64.StartsWith("data:image/jpeg")) { tmpFileName += ".jpg"; } if (submission.ImageDataBase64.StartsWith("data:image/png")) { tmpFileName += ".png"; } if (submission.ImageDataBase64.StartsWith("data:image/tiff")) { tmpFileName += ".tiff"; } if (submission.ImageDataBase64.StartsWith("data:")) { submission.ImageDataBase64 = submission.ImageDataBase64.Substring(submission.ImageDataBase64.IndexOf(',') + 1, submission.ImageDataBase64.Length - (submission.ImageDataBase64.IndexOf(',') + 1)); } File.WriteAllBytes(tmpFileName, Convert.FromBase64String(submission.ImageDataBase64)); tempFiles.Add(tmpFileName); var task = Task.Factory.StartNew(() => { var mediaManager = new MediaItemManager(); foreach (var tmpFile in tempFiles) { var photoAdded = mediaManager.AddPOIMediaItem(tempFolder, tmpFile, submission.ChargePointID, submission.Comment, false, userId); } }, TaskCreationOptions.LongRunning); return(true); } catch { return(false); } }
static async Task <string> WGet(string url, System.Text.Encoding encoding) { HttpClient http = new HttpClient(); var st = await http.GetStreamAsync(url); var sr = new System.IO.StreamReader(st, encoding); string ans = await sr.ReadToEndAsync(); return(ans); }
public async static Task <ResponseObject> GetWebApiAsync(string uri, int timeOut = 3000) { string result = string.Empty; WebClient client = new WebClientto(timeOut); System.IO.Stream stream = client.OpenRead(uri); System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8); result = await reader.ReadToEndAsync(); reader.Close(); return(new ResponseObject(true, JsonConvert.DeserializeObject(result))); }
public async Task <List <FtpListRecord> > ListAsync(string path) { var clientFtp = _ClientFtpCreate(path); clientFtp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails; var ftpList1 = await clientFtp.GetResponseAsync() as System.Net.FtpWebResponse; var regexLineTyped = new System.Text.RegularExpressions.Regex(@"(?<date>.+((?i)am|pm))\s*?(<(?<type>\w+)>)\s*(?<name>.+)"); var regexLineFile = new System.Text.RegularExpressions.Regex(@"(?<date>.+((?i)am|pm))\s*(?<size>\d+)\s*(?<name>.+)"); var r = new List <FtpListRecord>(); using (var ftpList1Sr = new System.IO.StreamReader(ftpList1.GetResponseStream())) { var ftpList1Response = await ftpList1Sr.ReadToEndAsync(); using (var stringReader = new System.IO.StringReader(ftpList1Response)) { while (true) { var line = stringReader.ReadLine(); if (line == null) { break; } var match1 = regexLineTyped.Match(line); if (match1.Success) { r.Add(new FtpListRecord { Date = DateTime.Parse(match1.Groups["date"].Value.Trim()), Name = match1.Groups["name"].Value.Trim(), IsDir = match1.Groups["type"].Value.Trim().ToLower() == "dir", }); } else { var match2 = regexLineFile.Match(line); if (match2.Success) { r.Add(new FtpListRecord { Date = DateTime.Parse(match2.Groups["date"].Value.Trim()), Name = match2.Groups["name"].Value.Trim(), Size = long.Parse(match2.Groups["size"].Value.Trim()), IsDir = false, }); } } } } } return(r); }
internal virtual async Task <string> GetFileAsync(string basePath, string name, string extension) { var area = Area; if (!string.IsNullOrEmpty(area)) { area = area + "/"; } var lang = ""; if (WebConstants.SeparateClientSideDynamicFilesByLanguage && (WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.Both || WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.OnlyLanguageBased) && !string.IsNullOrEmpty(Lang)) { lang = Lang + "/"; } var path = ""; if (StaticsAreExternal) { path = Path.Combine(HttpContext.Server.MapPath("\\"), ".." + MasterDynamicPath + basePath + "/" + lang + area + Controller + "/" + name + extension); } else { if (basePath.Length > 0 && basePath[0] == '/') { basePath = basePath.Substring(1); } path = Path.Combine(HttpContext.Server.MapPath("\\"), basePath + "/" + lang + area + Controller + "/" + name + extension); } var result = ""; Logger?.Log($"GetFileAsync: \"{path}\""); if (System.IO.File.Exists(path)) { using (System.IO.TextReader reader = new System.IO.StreamReader(path)) { result = await reader.ReadToEndAsync(); } Logger?.Log($" result length: {result.Length}"); return(result); } else { Logger?.Log($" NOT FOUND"); throw new HttpNotFoundException("File not found: " + path); } }
/// <summary> /// A class containing all relevant information from the HttpWebResponse. /// </summary> /// <typeparam name="T">The type of the content property in result.</typeparam> /// <param name="value">The HttpWebResponse to evaluate.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">Thrown when the given argument is null.</exception> /// <exception cref="IOException">Thrown when the response stream is null.</exception> /// <exception cref="NotSupportedException">Thrown when the type is not supported.</exception> public static async Task <HttpResponse <T> > CreateFromWebResponseAsync <T>(HttpWebResponse value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } var responseStream = value.GetResponseStream(); if (responseStream == null) { throw new IOException("response stream was null!"); } var result = new HttpResponse <T>(); switch (typeof(T)) { case Type byteArrayType when byteArrayType == typeof(byte[]): var ms = new MemoryStream(); await responseStream.CopyToAsync(ms); var byteArrayContent = ms.ToArray(); result.Content = (T)(object)byteArrayContent; break; case Type stringType when stringType == typeof(string): using (var streamReader = new StreamReader(responseStream)) { var stringContent = await streamReader.ReadToEndAsync(); result.Content = (T)(object)stringContent; } break; default: throw new NotSupportedException("cannot create HttpResponse of the given type"); } if (int.TryParse(value.GetResponseHeader(HeaderNames.LimitRemaining), out var lrem)) { result.LimitRemaining = lrem; } if (int.TryParse(value.GetResponseHeader(HeaderNames.LimitReset), out var lres)) { result.LimitReset = DateTime.SpecifyKind(DateTimeOffset.FromUnixTimeSeconds(lres).DateTime, DateTimeKind.Utc); } return(result); }
public static async System.Threading.Tasks.Task <Dictionary <String, String> > GetLicenses() { var result = new Dictionary <String, String>(); var files = await(await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("LICENSE")).GetFilesAsync(); foreach (var f in files) { using (var st = (await f.OpenReadAsync()).AsStream()) using (var rd = new System.IO.StreamReader(st)) { if (f.Name == "LICENSE") { _CurrentLicense = await rd.ReadToEndAsync(); } else { result.Add(f.Name, await rd.ReadToEndAsync()); } } } return(result); }
public static async Task <IActionResult> WebhookTriggerTest([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "test")] HttpRequest request, ILogger log) { string jobId = request.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}"); return(new OkObjectResult(r.Item2)); } else { await TestInfraLogic.WebhooksTest.post(log, StorageTableConnectionString, text); return(new OkResult()); } } else { log.LogWarning($"Unhandled request method {request.Method} when job id is not set"); return(new BadRequestResult()); } } else { if (request.Method.ToLowerInvariant() == "get") { log.LogInformation($"Getting webhook messages for job ${jobId}"); var results = await TestInfraLogic.WebhooksTest.get(log, StorageTableConnectionString, jobId); return(new OkObjectResult(results)); } else { log.LogWarning($"Unhandled request method {request.Method} when job id is ${jobId}"); return(new BadRequestResult()); } } }
// read file // check if there is a new DTO detected via timestamp // parse DTO and store in DB // store new data in DB as an episode public static List <string> ReadLogData() { string currentUserAppData = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string playerLogDataPath = currentUserAppData + "Low\\Mediatonic\\FallGuys_client\\Player.log"; System.IO.FileStream fs = new System.IO.FileStream(playerLogDataPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) { List <string> playerLogData = new List <string>(); playerLogData = sr.ReadToEndAsync().Result.Split("\r\n").ToList(); return(playerLogData); } // List<string> playerLogData = System.IO.File.ReadLines(playerLogDataPath).ToList(); }
public string Update(HttpContext context, int id) { System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream); var requestFromPost = reader.ReadToEndAsync(); string response = requestFromPost.Result; BookModel books = JsonConvert.DeserializeObject <BookModel>(response); books.Update(books, id); return(response); }
public string Post(HttpContext context) { System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream); var requestFromPost = reader.ReadToEndAsync(); string teste = requestFromPost.Result; BookModel books = JsonConvert.DeserializeObject <BookModel>(teste); books.Insert(books); return(teste); }
public async Task <IActionResult> Post() { string body = string.Empty; using (var reader = new System.IO.StreamReader(Request.Body)) body = await reader.ReadToEndAsync(); if (string.IsNullOrWhiteSpace(body)) { return(BadRequest()); } return(new FileStreamResult(new MemoryStream(GenerateDocument(body)), "application/octet-stream")); }
public async Task <IActionResult> PostBase64() { string body = string.Empty; using (var reader = new System.IO.StreamReader(Request.Body)) body = await reader.ReadToEndAsync(); if (string.IsNullOrWhiteSpace(body)) { return(BadRequest()); } return(Ok(Convert.ToBase64String(GenerateDocument(body)))); }
public async static Task LoadCitiesList() { if (AllCities == null || AllCities.Count == 0) { var assembly = typeof(MainPage).GetTypeInfo().Assembly; var jsonFileName = "city.list.json"; Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}"); using (var reader = new System.IO.StreamReader(stream)) { var jsonString = await reader.ReadToEndAsync(); AllCities = JsonConvert.DeserializeObject <List <City> >(jsonString); } } }
/// <summary> /// Get the list of characters from an embedded JSON file, including their child entities. /// </summary> /// <returns>Array of Character objects</returns> private async Task <Character[]> ReadCharactersFromFile() { var assembly = typeof(CharacterService).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream(Constants.CharactersFilename); string text; using (var reader = new System.IO.StreamReader(stream)) { text = await reader.ReadToEndAsync(); } var characters = JsonConvert.DeserializeObject <Character[]>(text); return(characters); }
public async Task <T> ReadFromJsonEmbededFile <T>(string JsonFileEmbeded) { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(JsonLocalHandler)).Assembly; Stream stream = assembly.GetManifestResourceStream(JsonFileEmbeded); using (var reader = new System.IO.StreamReader(stream)) { return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(await reader.ReadToEndAsync())); } } catch (Exception ex) { Debug.WriteLine(ex.Message); return(default(T)); } }
private async Task _callPush() { try { //App Service Publish Profile Credentials //string userName = "******"; //userName //string userPassword = "******"; //userPWD ////change webJobName to your WebJob name //string webJobName = "WEBJOBNAME"; //var unEncodedString = String.Format($"{userName}:{userPassword}"); //var encodedString = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(unEncodedString)); //Change this URL to your WebApp hosting the string URL = "https://skagry-net-core.azurewebsites.net/api/job/push"; System.Net.WebRequest request = System.Net.WebRequest.Create(URL); request.Method = "GET"; //request.ContentLength = 0; //request.Headers["Authorization"] = "Basic " + encodedString; System.Net.WebResponse response = await request.GetResponseAsync(); var responseFromServer = "no responce"; using (System.IO.Stream dataStream = response.GetResponseStream()) { using (System.IO.StreamReader reader = new System.IO.StreamReader(dataStream)) { responseFromServer = await reader.ReadToEndAsync(); } } Console.WriteLine(responseFromServer); //no response } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } finally { await Task.Delay(30000); Console.WriteLine("run Next trigger:" + DateTime.UtcNow); } }
private async static Task <string> FetchTextFileContents(string inPath) { if (System.IO.File.Exists(inPath) == false) { return(""); } try { using (System.IO.StreamReader streamReader = System.IO.File.OpenText(inPath)) { return(await streamReader.ReadToEndAsync()); } } catch (Exception) { return(""); } }
/// <summary> /// Reads a travel log input file. /// </summary> /// <param name="fileName">The file name.</param> /// <returns>A string containing all text from the file.</returns> private async Task <string> ReadTravelLog(string fileName) { var assembly = typeof(TravelLogStore).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream(string.Format("CodeKata.Files.{0}", fileName)); if (stream == null) { return(""); } string text = ""; using (var reader = new System.IO.StreamReader(stream)) { text = await reader.ReadToEndAsync(); } return(text); }