ReadToEndAsync() public method

public ReadToEndAsync ( ) : Task
return Task
Example #1
0
		/// <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 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);
                            }
                        }
                    }
                }
            }
        }
Example #3
0
        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 "";
            }
        }
        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 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;
        }
Example #6
0
        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);
        }
Example #7
0
        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;
            }
        }
Example #8
0
        /// <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;
        }
Example #9
0
        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();
        }
        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 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 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);
        }
        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)
            {
                // ...
            }
        }
        /// <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;
        }
Example #15
0
        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
            {
            }
        }
        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;
        }
Example #17
0
        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;
            }
        }
Example #18
0
		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;
				}
			}
		}
 public static async Task<string> ReadAllTextFromFileAsync(string path)
 {
     using (var streamReader = new StreamReader(File.OpenRead(path)))
     {
         return await streamReader.ReadToEndAsync();
     }
 }
Example #20
0
        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;
        }
Example #21
0
        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;
            }
        }
        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);
                        }
                    }
                }
            }
        }
        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);
        }
Example #24
0
        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 async Task<string> ReadContentAsStringAsync()
 {
     using (var sr = new StreamReader(this.Content))
     {
         return await sr.ReadToEndAsync();
     }
 }
		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);
		}
        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;
        }
		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;
		}
Example #29
0
        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 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;
 }