System.IO.StreamReader.ReadToEndAsync()

Here are the examples of the csharp api System.IO.StreamReader.ReadToEndAsync() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

961 Examples 7

19 Source : RequestMiddleware.cs
with Apache License 2.0
from 91270

private async Task<string> GetRequesContent(HttpContext context)
        {
            var request = context.Request;
            var sr = new StreamReader(request.Body);

            var content = $"{await sr.ReadToEndAsync()}";

            if (!string.IsNullOrEmpty(content))
            {
                request.Body.Position = 0;
            }

            return content;
        }

19 Source : StringIntoFileInjector.cs
with MIT License
from Abdulrhman5

public async Task<string> GetInjectedHtmlFileAsync(string fileName, params string[] strings)
        {

            var mainDir = AppDomain.CurrentDomain.BaseDirectory;
            var appCode = Path.Combine(mainDir, "Injectables");
            var requiredFile = Path.Combine(appCode, fileName);

            using (StreamReader reader = new StreamReader(requiredFile))
            {
                var content = await reader.ReadToEndAsync().ConfigureAwait(false);
                var injectedContent = string.Format(content, strings);
                return injectedContent;
            }
        }

19 Source : HttpClientHelpers.cs
with MIT License
from Abdulrhman5

public async Task<HttpRequestMessage> CreateAsync(
            HttpContext context,
            HttpMethod method,
            string url,
            bool forwardUrlPars,
            bool forwardHeaders,
            // add new headers,
            Func<string, (string Content, string ContentType)> changeBody = null
            )
        {
            string finalUrl = forwardUrlPars ? url + context.Request.QueryString.ToUriComponent() : url;

            var request = new HttpRequestMessage(method, finalUrl);
            context.Request.QueryString.ToUriComponent();
            if (forwardHeaders)
            {
                foreach (var requestHeader in context.Request.Headers)
                {
                    if (requestHeader.Key.EqualsIC("Host")) continue;
                    request.Headers.TryAddWithoutValidation(requestHeader.Key, requestHeader.Value.AsEnumerable());
                }
            }

            if (changeBody is null)
            {
                return request;

            }

            var body = new StreamReader(context.Request.Body);
            //The modelbinder has already read the stream and need to reset the stream index
            body.BaseStream.Seek(0, SeekOrigin.Begin);
            var requestBody = await body.ReadToEndAsync();

            var (content, type) = changeBody(requestBody);
            request.Content = new StringContent(content);
            request.Content.Headers.ContentType.MediaType = type;

            return request;
        }

19 Source : HttpClientHelpers.cs
with MIT License
from Abdulrhman5

public async Task<HttpRequestMessage> CreateAsync(
            HttpMethod method,
            string url,
            bool forwardUrlPars,
            bool forwardHeaders,
            // add new headers,
            Func<string, (string Content, string ContentType)> changeBody = null)
        {
            string finalUrl = forwardUrlPars ? url + _httpContext.Request.QueryString.ToUriComponent() : url;

            var request = new HttpRequestMessage(method, finalUrl);
            _httpContext.Request.QueryString.ToUriComponent();
            if (forwardHeaders)
            {
                foreach (var requestHeader in _httpContext.Request.Headers)
                {
                    if (requestHeader.Key.EqualsIC("Host")) continue;
                    request.Headers.TryAddWithoutValidation(requestHeader.Key, requestHeader.Value.AsEnumerable());
                }
            }

            if (changeBody is null)
            {
                return request;

            }

            var body = new StreamReader(_httpContext.Request.Body);
            //The modelbinder has already read the stream and need to reset the stream index
            body.BaseStream.Seek(0, SeekOrigin.Begin);
            var requestBody = await body.ReadToEndAsync();

            var (content, type) = changeBody(requestBody);
            request.Content = new StringContent(content);
            request.Content.Headers.ContentType.MediaType = type;

            return request;
        }

19 Source : Program.cs
with MIT License
from Accelerider

public static void Main(string[] args)
        {
            (string name, int age) a = ("123", 123);
            var json = JsonConvert.SerializeObject(a);
            var aa = JsonConvert.DeserializeObject(json, typeof((string, int)));


            var server = new NamedPipeServerStream("");
            using (var sr = new StreamReader(server))
            {
                sr.ReadToEndAsync();
            }
            var client = new NamedPipeClientStream("");
            using (var sw = new StreamWriter(client))
            {
                sw.WriteAsync("");
            }
                 

            var responder = new NamedPipeResponder<MockClient>();

            responder.Subscribe<string>(nameof(MockClient.SetName), (o, value) => o.SetName(value));
        }

19 Source : TippingManager.cs
with MIT License
from acid-chicken

public static async Task<string> InvokeMethodAsync(params object[] args)
        {
            using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }))
            using (var reader = process.StandardOutput)
            {
                var output = await reader.ReadToEndAsync().ConfigureAwait(false);
                process.WaitForExit();
                process.Close();
                return output.Trim();
            }
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task<Config> LoadConfigAsync(string path = ConfigurePath)
        {
            Config result;
            try
            {
                using (var stream = File.OpenRead(path))
                using (var reader = new StreamReader(stream))
                {
                    result = JsonConvert.DeserializeObject<Config>(await reader.ReadToEndAsync().ConfigureAwait(false));
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "Program", "The config has been loaded successfully.")).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "Program", ex.Message, ex)).ConfigureAwait(false);
                throw;
            }
            return result;
        }

19 Source : FileUtil.cs
with MIT License
from adospace

public static async Task<string> ReadAllTextFileAsync(string filename)
        {
            using (var reader = File.OpenText(filename))
            {
                return await reader.ReadToEndAsync();
            }
        }

19 Source : HttpURLConnectionClient.cs
with MIT License
from Adyen

public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
        {
            string responseText = null;
            //Set security protocol. Only TLS1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
                    {
                        responseText = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (WebException e)
            {
                HandleWebException(e);
            }
            return responseText;
        }

19 Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu

private static async Task<string> ReadResponse(WebResponse response)
        {
            string json;
            using (response)
            {
                if (response.ContentLength == 0)
                {
                    return null;
                }
                var receivedStream = response.GetResponseStream();
                if (receivedStream == null)
                    return null;

                using (receivedStream)
                {
                    using (var streamReader = new StreamReader(receivedStream))
                    {
                        json = await streamReader.ReadToEndAsync();
                        streamReader.Close();
                    }
                    receivedStream.Close();
                }
                response.Close();
            }
            return json;
        }

19 Source : ImportService.cs
with Apache License 2.0
from Aguafrommars

private async Task<ImportFileResult> ImportFileAsync(IFormFile file)
        {
            var reader = new StreamReader(file.OpenReadStream());
            var content = await reader.ReadToEndAsync().ConfigureAwait(false);
            var metadata = JsonConvert.DeserializeObject<EnreplacedyMetadata>(content);
            var enreplacedyType = Type.GetType(metadata.Metadata.TypeName);
            var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
            var importer = Activator.CreateInstance(importerType, _provider) as Importer;
            var result = await importer.ImportAsync(content).ConfigureAwait(false);
            result.FileName = file.FileName;
            return result;
        }

19 Source : FilePackageStorageServiceTests.cs
with MIT License
from ai-traders

protected async Task<string> ToStringAsync(Stream input)
            {
                using (var reader = new StreamReader(input))
                {
                    return await reader.ReadToEndAsync();
                }
            }

19 Source : LavalinkRestClient.cs
with MIT License
from Aiko-IT-Systems

internal async Task<LavalinkLoadResult> InternalResolveTracksAsync(Uri uri)
        {
            // this function returns a Lavalink 3-like dataset regardless of input data version

            var json = "[]";
            using (var req = await this._http.GetAsync(uri).ConfigureAwait(false))
            using (var res = await req.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
            using (var sr = new StreamReader(res, Utilities.UTF8))
                json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var jdata = JToken.Parse(json);
            if (jdata is JArray jarr)
            {
                // Lavalink 2.x

                var tracks = new List<LavalinkTrack>(jarr.Count);
                foreach (var jt in jarr)
                {
                    var track = jt["info"].ToObject<LavalinkTrack>();
                    track.TrackString = jt["track"].ToString();

                    tracks.Add(track);
                }

                return new LavalinkLoadResult
                {
                    PlaylistInfo = default,
                    LoadResultType = tracks.Count == 0 ? LavalinkLoadResultType.LoadFailed : LavalinkLoadResultType.TrackLoaded,
                    Tracks = tracks
                };
            }
            else if (jdata is JObject jo)
            {
                // Lavalink 3.x

                jarr = jo["tracks"] as JArray;
                var loadInfo = jo.ToObject<LavalinkLoadResult>();
                var tracks = new List<LavalinkTrack>(jarr.Count);
                foreach (var jt in jarr)
                {
                    var track = jt["info"].ToObject<LavalinkTrack>();
                    track.TrackString = jt["track"].ToString();

                    tracks.Add(track);
                }

                loadInfo.Tracks = new ReadOnlyCollection<LavalinkTrack>(tracks);

                return loadInfo;
            }
            else
                return null;
        }

19 Source : LogFilter.cs
with MIT License
from aishang2015

public void OnResultExecuted(ResultExecutedContext context)
        {
            var controllerType = context.Controller.GetType();
            var message = new OperateLogMessage();
            message.Controller = controllerType.FullName;
            message.Action = context.RouteData.Values["action"].ToString();
            message.HttpResultCode = context.HttpContext.Response.StatusCode.ToString();
            message.Uri = context.HttpContext.Request.Path;
            message.Account = context.HttpContext?.User?.GetUserName();
            message.Name = context.HttpContext?.User?.GetName();

            // todo 文件,form等特殊情况的处理
            var reader = new StreamReader(context.HttpContext.Request.Body);
            context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
            message.RequestContent = reader.ReadToEndAsync().Result;

            OperateLogQueue.blockingCollection.Add(message);
        }

19 Source : LoginLogFilter.cs
with MIT License
from aishang2015

public void OnResultExecuted(ResultExecutedContext context)
        {
            var reader = new StreamReader(context.HttpContext.Request.Body);
            context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
            var postBodyString = reader.ReadToEndAsync().Result;
            var body = JObject.Parse(postBodyString);

            var message = new LoginLogMessage();
            message.OperateAt = DateTime.Now;
            message.OperatorAccount = body["UserName"].ToString();
            message.IpAddress = context.HttpContext.Connection.RemoteIpAddress.ToString();
            message.IsSuccess = context.HttpContext.Response.StatusCode == 200;
            LoginLogQueue.blockingCollection.Add(message);
        }

19 Source : UpdateAssist.cs
with GNU General Public License v3.0
from alexdillon

private async Task<(int exitCode, string output)> InvokeProcessAsync(ProcessStartInfo psi, CancellationToken ct)
        {
            var pi = Process.Start(psi);
            await Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (pi.WaitForExit(2000))
                    {
                        return;
                    }
                }

                if (ct.IsCancellationRequested)
                {
                    pi.Kill();
                    ct.ThrowIfCancellationRequested();
                }
            });

            string textResult = await pi.StandardOutput.ReadToEndAsync();
            if (string.IsNullOrWhiteSpace(textResult) || pi.ExitCode != 0)
            {
                textResult = (textResult ?? string.Empty) + "\n" + await pi.StandardError.ReadToEndAsync();

                if (string.IsNullOrWhiteSpace(textResult))
                {
                    textResult = string.Empty;
                }
            }

            return (pi.ExitCode, textResult.Trim());
        }

19 Source : ConfigLoader.cs
with MIT License
from alexis-

public static async Task<T> SafeLoadJson<T>(string filePath)
    {
      if (filePath != null && File.Exists(filePath))
        using (var reader = File.OpenText(filePath))
          return JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());

      return default(T);
    }

19 Source : MarkdigConverter.cs
with Apache License 2.0
from alexz76

public async override Task<string> ConvertToHtmlAsync(Stream markdown)
        {
            var markdownReader = new StreamReader(markdown);

            var result = await markdownReader.ReadToEndAsync();

            return ConvertToHtml(result);
        }

19 Source : SwaggerUI.cs
with MIT License
from aliencube

public async Task<ISwaggerUI> BuildAsync()
        {
            var replacedembly = replacedembly.GetExecutingreplacedembly();

            using (var stream = replacedembly.GetManifestResourceStream(swaggerUiCss))
            using (var reader = new StreamReader(stream))
            {
                this._swaggerUiCss = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            using (var stream = replacedembly.GetManifestResourceStream(swaggerUiBundleJs))
            using (var reader = new StreamReader(stream))
            {
                this._swaggerUiBundleJs = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            using (var stream = replacedembly.GetManifestResourceStream(swaggerUiStandalonePresetJs))
            using (var reader = new StreamReader(stream))
            {
                this._swaggerUiStandalonePresetJs = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            using (var stream = replacedembly.GetManifestResourceStream(indexHtml))
            using (var reader = new StreamReader(stream))
            {
                this._indexHtml = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            return this;
        }

19 Source : SSOAuthenticationMiddleware.cs
with MIT License
from AlphaYu

private async Task SaveToken(HttpContext context, RequestDelegate next)
        {
            string responseContent;

            var originalBodyStream = context.Response.Body;

            using (var fakeResponseBody = new MemoryStream())
            {
                context.Response.Body = fakeResponseBody;

                await next(context);

                fakeResponseBody.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(fakeResponseBody))
                {
                    responseContent = await reader.ReadToEndAsync();
                    fakeResponseBody.Seek(0, SeekOrigin.Begin);

                    await fakeResponseBody.CopyToAsync(originalBodyStream);
                }
            }

            if (StatusCodeChecker.Is2xx(context.Response.StatusCode))
            {
                var tokenTxt = JObject.Parse(responseContent).GetValue("token")?.ToString();
                if (tokenTxt.IsNullOrWhiteSpace())
                    return;
                //refreshTokenTxt = JObject.Parse(responseContent).GetValue("refreshToken").ToString();

                var claimsInfo = GetClaimsInfo(tokenTxt);
                if (claimsInfo.Account.IsNotNullOrWhiteSpace())
                {
                    var tokenKey = $"{tokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}";
                    _cache.Set(tokenKey, claimsInfo.Token, claimsInfo.Expire - DateTime.Now);
                    //var refreshTokenKey = $"{refreshTokenPrefx}:{claimsInfo.Account}:{claimsInfo.Id}";
                    //_cache.Set(refreshTokenKey, refreshTokenTxt, TimeSpan.FromSeconds(_jwtConfig.RefreshTokenExpire));
                }
            }
        }

19 Source : PolicyController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Authorize(Policy = AuthzConstants.POLICY_STUDIO_DESIGNER)]
        [HttpPost]
        public async Task<ActionResult> WritePolicy([FromQuery] string org, [FromQuery] string app)
        {
            if (string.IsNullOrWhiteSpace(org))
            {
                return BadRequest("Organisation must be defined in query string");
            }

            if (string.IsNullOrWhiteSpace(app))
            {
                return BadRequest("App must be defined in query string");
            }

            // Use Request.Body to capture raw data from body to support other format than JSON
            Stream content = Request.Body;

            // Request.Body returns Stream of type FrameRequestStream which can only be read once
            // Copy Request.Body to another stream that supports seeking so the content can be read multiple times
            string contentString = await new StreamReader(content, Encoding.UTF8).ReadToEndAsync();

            if (string.IsNullOrWhiteSpace(contentString))
            {
                return BadRequest("Policy file cannot be empty");
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(contentString);
            Stream dataStream = new MemoryStream(byteArray);

            try
            {
                bool successfullyStored = await _pap.WritePolicyAsync(org, app, dataStream);

                if (successfullyStored)
                {
                    return Ok();
                }
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.Message);
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
                return StatusCode(500);
            }

            return BadRequest("Something went wrong in the upload of file to storage");
        }

19 Source : XacmlRequestApiModelBinder.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // Special logic for body, treat the model name as string.Empty for the top level
            // object, but allow an override via BinderModelName. The purpose of this is to try
            // and be similar to the behavior for POCOs bound via traditional model binding.
            string modelBindingKey;
            if (bindingContext.IsTopLevelObject)
            {
                modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
            }
            else
            {
                modelBindingKey = bindingContext.ModelName;
            }

            HttpContext httpContext = bindingContext.HttpContext;

            try
            {
                using (StreamReader reader = new StreamReader(httpContext.Request.Body))
                {
                    string input = await reader.ReadToEndAsync();
                    bindingContext.Model = new XacmlRequestApiModel() { BodyContent = input };
                    bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
                    return;
                }
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex, bindingContext.ModelMetadata);
                return;
            }
        }

19 Source : DatamodelsController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private async Task<string> ReadRequestBodyContentAsync()
        {
            string content;

            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                content = await reader.ReadToEndAsync();
            }

            return content;
        }

19 Source : GiteaDeployPermissionHandler.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            GiteaDeployPermissionRequirement requirement)
        {
            if (_httpContext == null)
            {
                return;
            }

            string org = _httpContext.GetRouteValue("org")?.ToString();
            string app = _httpContext.GetRouteValue("app")?.ToString();

            if (string.IsNullOrWhiteSpace(org) ||
                string.IsNullOrWhiteSpace(app))
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            string environment = _httpContext.GetRouteValue("environment")?.ToString();

            if (string.IsNullOrEmpty(environment))
            {
                _httpContext.Request.EnableBuffering();

                using (var reader = new StreamReader(
                   _httpContext.Request.Body,
                   encoding: Encoding.UTF8,
                   detectEncodingFromByteOrderMarks: false,
                   bufferSize: 1024,
                   leaveOpen: true))
                {
                    string body = await reader.ReadToEndAsync();

                    try
                    {
                        CreateDeploymentRequestViewModel model = JsonConvert.DeserializeObject<CreateDeploymentRequestViewModel>(body);
                        environment = model.Environment.Name;
                    }
                    catch
                    {
                        reader.Close();
                        _httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return;
                    }

                    // Reset the request body stream position so the next middleware can read it
                    _httpContext.Request.Body.Position = 0;
                }
            }

            string matchTeam = $"Deploy-{environment}";
            List<Team> teams = await _giteaApiWrapper.GetTeams();

            bool any = teams.Any(t => t.Organization.Username.Equals(
                org, System.StringComparison.OrdinalIgnoreCase)
                && t.Name.Equals(matchTeam, System.StringComparison.OrdinalIgnoreCase));

            if (any)
            {
                context.Succeed(requirement);
            }
            else
            {
                _httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
        }

19 Source : XacmlRequestApiModelBinder.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // Special logic for body, treat the model name as string.Empty for the top level
            // object, but allow an override via BinderModelName. The purpose of this is to try
            // and be similar to the behavior for POCOs bound via traditional model binding.
            string modelBindingKey;
            if (bindingContext.IsTopLevelObject)
            {
                modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
            }
            else
            {
                modelBindingKey = bindingContext.ModelName;
            }

            var httpContext = bindingContext.HttpContext;

            try
            {
                var input = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                bindingContext.Model = new XacmlRequestApiModel() { BodyContent = input };
                bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);

                return;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex, bindingContext.ModelMetadata);
                return;
            }
        }

19 Source : AltinnCoreApiModelBinder.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // Special logic for body, treat the model name as string.Empty for the top level
            // object, but allow an override via BinderModelName. The purpose of this is to try
            // and be similar to the behavior for POCOs bound via traditional model binding.
            string modelBindingKey;
            if (bindingContext.IsTopLevelObject)
            {
                modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
            }
            else
            {
                modelBindingKey = bindingContext.ModelName;
            }

            var httpContext = bindingContext.HttpContext;

            try
            {
                var input = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                bindingContext.Model = new AltinnCoreApiModel() { BodyContent = input };
                bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);

                return;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex, bindingContext.ModelMetadata);
                return;
            }
        }

19 Source : StatusMiddlewareTests.cs
with MIT License
from andrewlock

[Fact]
        public async Task ReturnsPongBodyContent()
        {
            var bodyStream = new MemoryStream();
            var context = new DefaultHttpContext();
            context.Response.Body = bodyStream;
            context.Request.Path = "/ping";

            RequestDelegate next = (ctx) => Task.CompletedTask;
            var middleware = new StatusMiddleware(next: next);

            await middleware.Invoke(context);

            string response;
            bodyStream.Seek(0, SeekOrigin.Begin);
            using (var stringReader = new StreamReader(bodyStream))
            {
                response = await stringReader.ReadToEndAsync();
            }

            replacedert.Equal("pong", response);
        }

19 Source : SwitchNotifierActionType.cs
with GNU General Public License v3.0
from Angelinsky7

protected override async Task PostProcess(String pathChanged, MultiplexedStream stream) {
            MemoryStream output = new MemoryStream();
            await stream.CopyOutputToAsync(null, output, null, default(CancellationToken));
            output.Position = 0;
            using (StreamReader reader = new StreamReader(output)) {
                String text = await reader.ReadToEndAsync();
                if (text.Contains($"exec: \\\"{m_Shell}\\\": executable file not found in $PATH")) {
                    m_Notifier.LogMessage($"Cannot execute {m_Shell} for this container ({m_Notifier.m_Container}) changing for {m_ReplacingShell}");
                    m_Shell = m_ReplacingShell;
                    m_HandleError = false;
                    await Notify(pathChanged);
                } else {
                    m_Notifier.LogMessage($"Can execute {m_Shell} for this container ({m_Notifier.m_Container}) disactivating error handling");
                    m_HandleError = false;
                }
            }
        }

19 Source : EmailTemplateSender.cs
with MIT License
from angelsix

public async Task<SendEmailResponse> SendGeneralEmailAsync(SendEmailDetails details, string replacedle, string content1, string content2, string buttonText, string buttonUrl)
        {
            var templateText = default(string);

            // Read the general template from file
            // TODO: Replace with IoC Flat data provider
            using (var reader = new StreamReader(replacedembly.GetEntryreplacedembly().GetManifestResourceStream("Fasetto.Word.Web.Server.Email.Templates.GeneralTemplate.htm"), Encoding.UTF8))
            {
                // Read file contents
                templateText = await reader.ReadToEndAsync();
            }

            // Replace special values with those inside the template
            templateText = templateText.Replace("--replacedle--", replacedle)
                                        .Replace("--Content1--", content1)
                                        .Replace("--Content2--", content2)
                                        .Replace("--ButtonText--", buttonText)
                                        .Replace("--ButtonUrl--", buttonUrl);

            // Set the details content to this template content
            details.Content = templateText;

            // Send email
            return await DI.EmailSender.SendEmailAsync(details);
        }

19 Source : DeflateCompression.cs
with MIT License
from angusmillar

public static async Task<string> UncompressAsync(byte[] input)
    {
      using (MemoryStream MemoryStream = new MemoryStream(input))
      {
        using (DeflateStream DeflateStream = new DeflateStream(MemoryStream, CompressionMode.Decompress))
        {
          using (StreamReader StreamReader = new StreamReader(DeflateStream, Encoding.UTF8))
          {
            return await StreamReader.ReadToEndAsync();
          }
        }
      }
    }

19 Source : HttpHelper.cs
with Apache License 2.0
from anjoy8

public static async Task<string> GetAsync(string serviceAddress)
        { 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = await myStreamReader.ReadToEndAsync();
            myStreamReader.Close();
            myResponseStream.Close(); 
            return retString;
        }

19 Source : RecordAccessLogsMildd.cs
with Apache License 2.0
from anjoy8

public async Task<string> GetResponse(HttpResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);
            var text = await new StreamReader(response.Body).ReadToEndAsync();
            response.Body.Seek(0, SeekOrigin.Begin);
            return text;
        }

19 Source : RequRespLogMildd.cs
with Apache License 2.0
from anjoy8

private async Task RequestDataLog(HttpContext context)
        {
            var request = context.Request;
            var sr = new StreamReader(request.Body);

            var content = $" QueryData:{request.Path + request.QueryString}\r\n BodyData:{await sr.ReadToEndAsync()}";

            if (!string.IsNullOrEmpty(content))
            {
                //Parallel.For(0, 1, e =>
                //{
                //    LogLock.OutSql2Log("RequestResponseLog", new string[] { "Request Data:", content });

                //});
                SerilogServer.WriteLog("RequestResponseLog", new string[] { "Request Data:", content });

                request.Body.Position = 0;
            }
        }

19 Source : WeChatController.cs
with Apache License 2.0
from anjoy8

[AllowAnonymous]
        [HttpPost]
        [HttpGet]
        public async Task<string> Valid([FromQuery] WeChatValidDto validDto)
        {
            using (var reader = new StreamReader(Request.Body))
            {
                var body = await reader.ReadToEndAsync();
                return await _weChatConfigServices.Valid(validDto, body);
            }
        }

19 Source : HttpHelper.cs
with Apache License 2.0
from anjoy8

public static async Task<string> PostAsync(string serviceAddress, string strContent = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "POST";
            request.ContentType = "application/json";
            //判断有无POST内容
            if (!string.IsNullOrWhiteSpace(strContent))
            {
                using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                {
                    dataStream.Write(strContent);
                    dataStream.Close();
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (string.IsNullOrWhiteSpace(encoding))
            {
                encoding = "UTF-8"; //默认编码  
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = await reader.ReadToEndAsync();
            return retString;
        }

19 Source : PayServices.cs
with Apache License 2.0
from anjoy8

public async Task<MessageModel<PayRefundReturnResultModel>> PayRefund(PayRefundNeedModel payModel)
        {
            _logger.LogInformation("退款开始");
            MessageModel<PayRefundReturnResultModel> messageModel = new MessageModel<PayRefundReturnResultModel>();
            messageModel.response = new PayRefundReturnResultModel();
            try
            {
                _logger.LogInformation($"原始GET参数->{_httpContextAccessor.HttpContext.Request.QueryString}");

                string REQUEST_SN = StringHelper.GetGuidToLongID().ToString().Substring(0, 16);//请求序列码
                string CUST_ID = StaticPayInfo.MERCHANTID;//商户号
                string USER_ID = StaticPayInfo.USER_ID;//操作员号
                string PreplacedWORD = StaticPayInfo.PreplacedWORD;//密码
                string TX_CODE = "5W1004";//交易码
                string LANGUAGE = "CN";//语言
                                       //string SIGN_INFO = "";//签名信息
                                       //string SIGNCERT = "";//签名CA信息
                                       //外联平台客户端服务部署的地址+设置的监听端口
                string sUrl = StaticPayInfo.OutAddress;

                //XML请求报文
                //string sRequestMsg = $" requestXml=<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";
                string sRequestMsg = $"<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";

                //string sRequestMsg = readRequestFile("E:/02-外联平台/06-测试/测试报文/商户网银/客户端连接-5W1001-W06.txt");


                //注意:请求报文必须放在requestXml参数送
                sRequestMsg = "requestXml=" + sRequestMsg;

                _logger.LogInformation("请求地址:" + sUrl);
                _logger.LogInformation("请求报文:" + sRequestMsg);
                HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(sUrl);
                request.Method = "POST";

                request.ContentType = "application/x-www-form-urlencoded";
                request.KeepAlive = false;
                request.Connection = "";

                //外联平台使用GB18030编码,这里进行转码处理 
                byte[] byteRquest = Encoding.GetEncoding("GB18030").GetBytes(sRequestMsg);
                request.ContentLength = byteRquest.Length;

                //发送请求
                Stream writerStream = request.GetRequestStream();
                await writerStream.WriteAsync(byteRquest, 0, byteRquest.Length);
                writerStream.Flush();
                writerStream.Close();

                //接收请求
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream result = response.GetResponseStream();
                StreamReader readerResult = new StreamReader(result, System.Text.Encoding.GetEncoding("GB18030"));
                string sResult = await readerResult.ReadToEndAsync();
                _logger.LogInformation("响应报文:" + sResult);
                var Xmlresult = XmlHelper.ParseFormByXml<PayRefundReturnModel>(sResult, "TX");
                if (Xmlresult.RETURN_CODE.Equals("000000"))
                {
                    messageModel.success = true;
                    messageModel.msg = "退款成功";
                }
                else
                {
                    messageModel.success = false;
                    messageModel.msg = "退款失败";
                }
                messageModel.response.RETURN_MSG = Xmlresult.RETURN_MSG;
                messageModel.response.TX_CODE = Xmlresult.TX_CODE;
                messageModel.response.REQUEST_SN = Xmlresult.REQUEST_SN;
                messageModel.response.RETURN_CODE = Xmlresult.RETURN_CODE;
                messageModel.response.CUST_ID = Xmlresult.CUST_ID;
                messageModel.response.LANGUAGE = Xmlresult.LANGUAGE;

                messageModel.response.AMOUNT = Xmlresult.TX_INFO?.AMOUNT;
                messageModel.response.PAY_AMOUNT = Xmlresult.TX_INFO?.PAY_AMOUNT;
                messageModel.response.ORDER_NUM = Xmlresult.TX_INFO?.ORDER_NUM;
            }
            catch (Exception ex)
            {
                messageModel.success = false;
                messageModel.msg = "服务错误";
                messageModel.response.RETURN_MSG = ex.Message;
                _logger.LogInformation($"异常信息:{ex.Message}");
                _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
            }
            finally
            {
                _logger.LogInformation($"返回数据->{JsonHelper.GetJSON<MessageModel<PayRefundReturnResultModel>>(messageModel)}");
                _logger.LogInformation("退款结束");
            }
            return messageModel;

        }

19 Source : StatisticsDatabase.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private async Task<IEnumerable<RankingModel>> LoadRankingsFileAsync()
        {
            if (!File.Exists(this.RankingDatabaseFileName))
            {
                return null;
            }

            using (var sr = new StreamReader(this.RankingDatabaseFileName, new UTF8Encoding(false)))
            {
                var json = await sr.ReadToEndAsync();
                return JsonConvert.DeserializeObject<List<RankingModel>>(json);
            }
        }

19 Source : Operations.cs
with MIT License
from anthonychu

[FunctionName(nameof(Captions))]
        public static async Task Captions(
            [HttpTrigger(AuthorizationLevel.Anonymous, "POST")] HttpRequest req,
            [SignalR(HubName = "captions")] IAsyncCollector<SignalRMessage> signalRMessages)
        {
            if (!IsAuthorized(req))
            {
                throw new Exception("Unauthorized"); // TODO: should return an HTTP response
            }

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic payload = JsonConvert.DeserializeObject(requestBody);

            var languageCaptionsTasks = new List<Task>();
            var languages = payload.languages.ToObject<Dictionary<string, string>>();

            foreach (var language in languages)
            {
                var caption = new
                {
                    language = language.Key,
                    offset = payload.offset,
                    text = language.Value
                };

                languageCaptionsTasks.Add(signalRMessages.AddAsync(new SignalRMessage
                {
                    Target = "newCaption",
                    GroupName = language.Key,
                    Arguments = new[] { caption }
                }));
            }

            await Task.WhenAll(languageCaptionsTasks);
        }

19 Source : Init.cs
with Apache License 2.0
from apache

public async Task<Run> HandleRequest(HttpContext httpContext)
        {
            await _initSemapreplacedSlim.WaitAsync();
            try
            {
                if (Initialized)
                {
                    await httpContext.Response.WriteError("Cannot initialize the action more than once.");
                    Console.Error.WriteLine("Cannot initialize the action more than once.");
                    return (new Run(Type, Method, Constructor, AwaitableMethod));
                }

                string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                JObject inputObject = JObject.Parse(body);
                if (!inputObject.ContainsKey("value"))
                {
                    await httpContext.Response.WriteError("Missing main/no code to execute.");
                    return (null);
                }

                JToken message = inputObject["value"];

                if (message["main"] == null || message["binary"] == null || message["code"] == null)
                {
                    await httpContext.Response.WriteError("Missing main/no code to execute.");
                    return (null);
                }

                string main = message["main"].ToString();

                bool binary = message["binary"].ToObject<bool>();

                if (!binary)
                {
                    await httpContext.Response.WriteError("code must be binary (zip file).");
                    return (null);
                }

                string[] mainParts = main.Split("::");
                if (mainParts.Length != 3)
                {
                    await httpContext.Response.WriteError("main required format is \"replacedembly::Type::Function\".");
                    return (null);
                }

                string tempPath = Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString());
                string base64Zip = message["code"].ToString();
                try
                {
                    using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Zip)))
                    {
                        using (ZipArchive archive = new ZipArchive(stream))
                        {
                            archive.ExtractToDirectory(tempPath);
                        }
                    }
                }
                catch (Exception)
                {
                    await httpContext.Response.WriteError("Unable to decompress package.");
                    return (null);
                }

                Environment.CurrentDirectory = tempPath;

                string replacedemblyFile = $"{mainParts[0]}.dll";

                string replacedemblyPath = Path.Combine(tempPath, replacedemblyFile);

                if (!File.Exists(replacedemblyPath))
                {
                    await httpContext.Response.WriteError($"Unable to locate requested replacedembly (\"{replacedemblyFile}\").");
                    return (null);
                }

                try
                {
                    replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
                    Type = replacedembly.GetType(mainParts[1]);
                    if (Type == null)
                    {
                        await httpContext.Response.WriteError($"Unable to locate requested type (\"{mainParts[1]}\").");
                        return (null);
                    }
                    Method = Type.GetMethod(mainParts[2]);
                    Constructor = Type.GetConstructor(Type.EmptyTypes);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.ToString());
                    await httpContext.Response.WriteError(ex.Message
#if DEBUG
                                                          + ", " + ex.StackTrace
#endif
                    );
                    return (null);
                }

                if (Method == null)
                {
                    await httpContext.Response.WriteError($"Unable to locate requested method (\"{mainParts[2]}\").");
                    return (null);
                }

                if (Constructor == null)
                {
                    await httpContext.Response.WriteError($"Unable to locate appropriate constructor for (\"{mainParts[1]}\").");
                    return (null);
                }

                Initialized = true;

                AwaitableMethod = (Method.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null);

                return (new Run(Type, Method, Constructor, AwaitableMethod));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.StackTrace);
                await httpContext.Response.WriteError(ex.Message
#if DEBUG
                                                  + ", " + ex.StackTrace
#endif
                );
                Startup.WriteLogMarkers();
                return (null);
            }
            finally
            {
                _initSemapreplacedSlim.Release();
            }
        }

19 Source : Run.cs
with Apache License 2.0
from apache

public async Task HandleRequest(HttpContext httpContext)
        {
            if (_type == null || _method == null || _constructor == null)
            {
                await httpContext.Response.WriteError("Cannot invoke an uninitialized action.");
                return;
            }

            try
            {
                string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();

                JObject inputObject = string.IsNullOrEmpty(body) ? null : JObject.Parse(body);

                JObject valObject = null;

                if (inputObject != null)
                {
                    valObject = inputObject["value"] as JObject;
                    foreach (JToken token in inputObject.Children())
                    {
                        try
                        {
                            if (token.Path.Equals("value", StringComparison.InvariantCultureIgnoreCase))
                                continue;
                            string envKey = $"__OW_{token.Path.ToUpperInvariant()}";
                            string envVal = token.First.ToString();
                            Environment.SetEnvironmentVariable(envKey, envVal);
                            //Console.WriteLine($"Set environment variable \"{envKey}\" to \"{envVal}\".");
                        }
                        catch (Exception)
                        {
                            await Console.Error.WriteLineAsync(
                                $"Unable to set environment variable for the \"{token.Path}\" token.");
                        }
                    }
                }

                object owObject = _constructor.Invoke(new object[] { });

                try
                {
                    JObject output;

                    if(_awaitableMethod) {
                        output = (JObject) await (dynamic) _method.Invoke(owObject, new object[] {valObject});
                    }
                    else {
                        output = (JObject) _method.Invoke(owObject, new object[] {valObject});
                    }

                    if (output == null)
                    {
                        await httpContext.Response.WriteError("The action returned null");
                        Console.Error.WriteLine("The action returned null");
                        return;
                    }

                    await httpContext.Response.WriteResponse(200, output.ToString());
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.StackTrace);
                    await httpContext.Response.WriteError(ex.Message
#if DEBUG
                                                          + ", " + ex.StackTrace
#endif
                    );
                }
            }
            finally
            {
                Startup.WriteLogMarkers();
            }
        }

19 Source : Init.cs
with Apache License 2.0
from apache

public async Task<Run> HandleRequest(HttpContext httpContext)
        {
            await _initSemapreplacedSlim.WaitAsync();
            try
            {
                if (Initialized)
                {
                    await httpContext.Response.WriteError("Cannot initialize the action more than once.");
                    Console.Error.WriteLine("Cannot initialize the action more than once.");
                    return (new Run(Type, Method, Constructor, AwaitableMethod));
                }

                string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                JObject inputObject = JObject.Parse(body);
                if (!inputObject.ContainsKey("value"))
                {
                    await httpContext.Response.WriteError("Missing main/no code to execute.");
                    return (null);
                }

                JToken message = inputObject["value"];

                if (message["main"] == null || message["binary"] == null || message["code"] == null)
                {
                    await httpContext.Response.WriteError("Missing main/no code to execute.");
                    return (null);
                }

                string main = message["main"].ToString();

                bool binary = message["binary"].ToObject<bool>();

                if (!binary)
                {
                    await httpContext.Response.WriteError("code must be binary (zip file).");
                    return (null);
                }

                string[] mainParts = main.Split("::");
                if (mainParts.Length != 3)
                {
                    await httpContext.Response.WriteError("main required format is \"replacedembly::Type::Function\".");
                    return (null);
                }

                string tempPath = Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString());
                string base64Zip = message["code"].ToString();
                try
                {
                    using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Zip)))
                    {
                        using (ZipArchive archive = new ZipArchive(stream))
                        {
                            archive.ExtractToDirectory(tempPath);
                        }
                    }
                }
                catch (Exception)
                {
                    await httpContext.Response.WriteError("Unable to decompress package.");
                    return (null);
                }

                Environment.CurrentDirectory = tempPath;

                string replacedemblyFile = $"{mainParts[0]}.dll";

                string replacedemblyPath = Path.Combine(tempPath, replacedemblyFile);

                if (!File.Exists(replacedemblyPath))
                {
                    await httpContext.Response.WriteError($"Unable to locate requested replacedembly (\"{replacedemblyFile}\").");
                    return (null);
                }

                try
                {
                    // Export init arguments as environment variables
                    if (message["env"] != null && message["env"].HasValues)
                    {
                        Dictionary<string, string> dictEnv = message["env"].ToObject<Dictionary<string, string>>();
                        foreach (KeyValuePair<string, string> entry in dictEnv) {
                            // See https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable
                            // If entry.Value is null or the empty string, the variable is not set
                            Environment.SetEnvironmentVariable(entry.Key, entry.Value);
                        }
                    }

                    replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
                    Type = replacedembly.GetType(mainParts[1]);
                    if (Type == null)
                    {
                        await httpContext.Response.WriteError($"Unable to locate requested type (\"{mainParts[1]}\").");
                        return (null);
                    }
                    Method = Type.GetMethod(mainParts[2]);
                    Constructor = Type.GetConstructor(Type.EmptyTypes);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.ToString());
                    await httpContext.Response.WriteError(ex.Message
#if DEBUG
                                                          + ", " + ex.StackTrace
#endif
                    );
                    return (null);
                }

                if (Method == null)
                {
                    await httpContext.Response.WriteError($"Unable to locate requested method (\"{mainParts[2]}\").");
                    return (null);
                }

                if (Constructor == null)
                {
                    await httpContext.Response.WriteError($"Unable to locate appropriate constructor for (\"{mainParts[1]}\").");
                    return (null);
                }

                Initialized = true;

                AwaitableMethod = (Method.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null);

                return (new Run(Type, Method, Constructor, AwaitableMethod));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.StackTrace);
                await httpContext.Response.WriteError(ex.Message
#if DEBUG
                                                  + ", " + ex.StackTrace
#endif
                );
                Startup.WriteLogMarkers();
                return (null);
            }
            finally
            {
                _initSemapreplacedSlim.Release();
            }
        }

19 Source : FileUtils.cs
with MIT License
from aprilyush

public static async Task<string> ReadTextAsync(string filePath, Encoding encoding)
        {
            string text;
            using (var sr = new StreamReader(filePath, encoding))
            {
                text = await sr.ReadToEndAsync();
                sr.Close();
            }
            return text;
        }

19 Source : DBCFile.cs
with MIT License
from Aptiv-WLL

public async Task CreateLibraryDBCAsync()
        {
            if (Filename == "") return;
            string s;
            using (StreamReader sr = new StreamReader(Filename))
                s = await sr.ReadToEndAsync();

            await Task.Run(()=> { Parse(s); });
        }

19 Source : AreaController.cs
with MIT License
from ArchaicQuest

[HttpPost]
        [Route("api/World/Area/UploadArea")]
        public async Task<IActionResult> UploadArea([FromForm(Name = "file")] IFormFile jsonString)
        {

            if (CheckIfValidFile(jsonString))
            {
                using (var reader = new StreamReader(jsonString.OpenReadStream()))
                {
                    var x = await reader.ReadToEndAsync();

                    var exitingArea = JsonConvert.DeserializeObject<Area>(x);
                    var editExistingArea = JsonConvert.DeserializeObject<Area>(x);

                    // server may already issued the ids
                    // so we will remove them and have 
                    // the DB issue new ones

                    editExistingArea.Id = _db.GetList<Area>(DataBase.Collections.Area).Count + 2;
                    editExistingArea.DateCreated = DateTime.Now;
                    editExistingArea.Rooms = new List<Room>();

                    // Add the new area first
                    _db.Save(editExistingArea, DataBase.Collections.Area);


                    
                    //create rooms
                    foreach (var room in exitingArea.Rooms)
                    {
                        room.Id = exitingArea.Rooms.Max(x => x.Id) + 1;
                        room.AreaId = editExistingArea.Id;
                        if (room.Exits.Down != null)
                        {
                            room.Exits.Down.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.Up != null)
                        {
                            room.Exits.Up.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.North != null)
                        {
                            room.Exits.North.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.NorthEast != null)
                        {
                            room.Exits.NorthEast.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.NorthWest != null)
                        {
                            room.Exits.NorthWest.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.East != null)
                        {
                            room.Exits.East.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.SouthEast != null)
                        {
                            room.Exits.SouthEast.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.South != null)
                        {
                            room.Exits.South.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.SouthWest != null)
                        {
                            room.Exits.SouthWest.AreaId = editExistingArea.Id;
                        }
                        if (room.Exits.West != null)
                        {
                            room.Exits.West.AreaId = editExistingArea.Id;
                        }
                        _db.Save(room, DataBase.Collections.Room);

                    }

                    //do exits
                    var newRooms = _db.GetCollection<Room>(DataBase.Collections.Room).FindAll().Where(x => x.AreaId == editExistingArea.Id);
                    foreach (var room in newRooms)
                    {
                        if (room.Exits.Down != null)
                        {
                            room.Exits.Down.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.Down.Coords.X && x.Coords.Y == room.Exits.Down.Coords.Y &&
                                x.Coords.Z == room.Exits.Down.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.Up != null)
                        {
                            room.Exits.Up.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.Up.Coords.X && x.Coords.Y == room.Exits.Up.Coords.Y &&
                                x.Coords.Z == room.Exits.Up.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.North != null)
                        {
                            room.Exits.North.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.North.Coords.X && x.Coords.Y == room.Exits.North.Coords.Y &&
                                x.Coords.Z == room.Exits.North.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.NorthEast != null)
                        {
                            room.Exits.NorthEast.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.NorthEast.Coords.X && x.Coords.Y == room.Exits.NorthEast.Coords.Y &&
                                x.Coords.Z == room.Exits.NorthEast.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.NorthWest != null)
                        {
                            room.Exits.NorthWest.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.NorthWest.Coords.X && x.Coords.Y == room.Exits.NorthWest.Coords.Y &&
                                x.Coords.Z == room.Exits.NorthWest.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.East != null)
                        {
                            room.Exits.East.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.East.Coords.X && x.Coords.Y == room.Exits.East.Coords.Y &&
                                x.Coords.Z == room.Exits.East.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.SouthEast != null)
                        {
                            room.Exits.SouthEast.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.SouthEast.Coords.X && x.Coords.Y == room.Exits.SouthEast.Coords.Y &&
                                x.Coords.Z == room.Exits.SouthEast.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.South != null)
                        {
                            room.Exits.South.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.South.Coords.X && x.Coords.Y == room.Exits.South.Coords.Y &&
                                x.Coords.Z == room.Exits.South.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.SouthWest != null)
                        {
                            room.Exits.SouthWest.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.SouthWest.Coords.X &&
                                x.Coords.Y == room.Exits.SouthWest.Coords.Y &&
                                x.Coords.Z == room.Exits.SouthWest.Coords.Z)?.Id ?? -1;
                        }
                        if (room.Exits.West != null)
                        {
                            room.Exits.West.RoomId = newRooms.FirstOrDefault(x =>
                                x.Coords.X == room.Exits.West.Coords.X && x.Coords.Y == room.Exits.West.Coords.Y &&
                                x.Coords.Z == room.Exits.West.Coords.Z)?.Id ?? -1;
                        }
                        room.RoomObjects.RemoveAll(x => x.Name == null);
                        _db.Save(room, DataBase.Collections.Room);
                    }

                    //save mobs
                    foreach (var room in newRooms)
                    {
                        // if a room has 4 goblins don't add 4 goblins to the mob list
                        foreach (var mob in room.Mobs.GroupBy(x => x.Name).Select(x => x.First()).ToList())
                        {
                            _db.Save(mob, DataBase.Collections.Mobs);
                        }
                    }

                    //save items
                    foreach (var room in newRooms)
                    {
                        foreach (var item in room.Items.GroupBy(x => x.Name).Select(x => x.First()).ToList())
                        {
                            _db.Save(item, DataBase.Collections.Items);
                        }
                    }

                }

            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();

        }

19 Source : TcpHealthService.cs
with MIT License
from arcus-azure

public async Task<HealthReport> GetHealthReportAsync()
        {
            using (var client = new TcpClient())
            {
                _logger.LogTrace("Connecting to the TCP {Address}:{Port}...", LocalAddress, _healthTcpPort);
                await client.ConnectAsync(IPAddress.Parse(LocalAddress), _healthTcpPort);
                _logger.LogTrace("Connected to the TCP {Address}:{Port}", LocalAddress, _healthTcpPort);
                
                _logger.LogTrace("Retrieving health report...");
                using (NetworkStream clientStream = client.GetStream())
                using (var reader = new StreamReader(clientStream))
                {
                    string healthReport = await reader.ReadToEndAsync();
                    var report = JsonConvert.DeserializeObject<HealthReport>(healthReport, new HealthReportEntryConverter());

                    _logger.LogTrace("Health report retrieved");
                    return report;
                }
            }
        }

19 Source : RequestTrackingMiddleware.cs
with MIT License
from arcus-azure

private static async Task<string> SanitizeStreamAsync(Stream stream, int? maxLength, string targetName)
        {
            if (!stream.CanRead)
            {
                return $"{targetName} body could not be tracked because stream is not readable";
            }

            if (!stream.CanSeek)
            {
                return $"{targetName} body could not be tracked because stream is not seekable";
            }

            string contents;
            long? originalPosition = null;

            try
            {
                originalPosition = stream.Position;
                if (stream.Position != 0)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                var reader = new StreamReader(stream);
                if (maxLength.HasValue)
                {
                    var buffer = new char[maxLength.Value];
                    await reader.ReadBlockAsync(buffer, 0, buffer.Length);
                    contents = new String(buffer); 
                }
                else
                {
                    contents = await reader.ReadToEndAsync();
                }
            }
            catch
            {
                // We don't want to track additional telemetry for cost purposes,
                // so we surface it like this
                contents = $"Unable to get '{targetName}' body for request tracking";
            }

            try
            {
                if (originalPosition.HasValue)
                {
                    stream.Seek(originalPosition.Value, SeekOrigin.Begin);
                }
            }
            catch
            {
                // Nothing to do here, we want to ensure the value is always returned.
            }

            // Trim string 'NULL' characters when the buffer was greater than the actual request/response body that was tracked.
            return contents?.TrimEnd('\0');
        }

19 Source : EventGridSubscriptionValidationActionFilter.cs
with MIT License
from arcus-azure

private async Task<string> ReadRequestBodyAsync(HttpRequest request)
        {
            using (var reader = new StreamReader(request.Body))
            {
                // TODO: use max buffer size option.
                string json = await reader.ReadToEndAsync();
                return json;
            }
        }

19 Source : HealthEndpointService.cs
with MIT License
from arcus-azure

public async Task<HealthReport> ProbeHealthReportAsync()
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(IPAddress.Parse("127.0.0.1"), _healthPort);
                _outputWriter.WriteLine("Connected to TCP health port {0}", _healthPort);

                using (NetworkStream clientStream = client.GetStream())
                using (var reader = new StreamReader(clientStream))
                {
                    _outputWriter.WriteLine("Probe for health report at TCP port {0}", _healthPort);
                    string healthReportJson = await reader.ReadToEndAsync();

                    replacedert.False(String.IsNullOrWhiteSpace(healthReportJson), $"Probed health at TCP port {_healthPort} report cannot be blank");
                    return JsonConvert.DeserializeObject<HealthReport>(healthReportJson);
                }
            }
        }

19 Source : PlainTextInputFormatter.cs
with MIT License
from arcus-azure

public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            HttpRequest request = context.HttpContext.Request;
            using (var reader = new StreamReader(request.Body))
            {
                string content = await reader.ReadToEndAsync();
                return InputFormatterResult.Success(content);
            }
        }

19 Source : LoggingMiddleware.cs
with GNU General Public License v3.0
from arduosoft

public async override Task InvokeAsync(HttpContext context)
        {
            await next(context);
            try
            {
                logger.LogInformation($"Request: {context.Request.Path}");
                logger.LogInformation($"Method: {context.Request.Method}");
                logger.LogInformation($"Headers: {JsonConvert.SerializeObject(context.Request.Headers)}");
                if (context.Request.Body != null && context.Request.Body.CanRead)
                {
                    using (var reader = new StreamReader(context.Request.Body))
                    {
                        logger.LogInformation($"Content: {reader.ReadToEndAsync()}");
                    }
                }
                logger.LogInformation("Response************");
                logger.LogInformation($"Status Code: {context.Response.StatusCode}");
                logger.LogInformation($"Headers: {JsonConvert.SerializeObject(context.Response.Headers)}");

                if (context.Request.Body != null && context.Request.Body.CanRead)
                {
                    using (var reader = new StreamReader(context.Response.Body))
                    {
                        logger.LogInformation($"Content: {reader.ReadToEndAsync()}");
                    }
                }
            }
            catch { }
        }

See More Examples