Esempio n. 1
0
        public async override Task <IEnumerable <Asset> > TransformAsync(string extension, params Asset[] assets)
        {
            AutoStream outputStream = new AutoStream(1024 * 64);

            foreach (var asset in assets)
            {
                string seperator      = this.GetSeperator(asset);
                byte[] seperatorBytes = string.IsNullOrEmpty(seperator) ? Array.Empty <byte>() : Encoding.UTF8.GetBytes(seperator);
                await asset.Content.CopyToAsync(outputStream);

                if (0 < seperatorBytes.Length)
                {
                    await outputStream.WriteAsync(seperatorBytes, 0, seperatorBytes.Length);
                }
            }
            outputStream.Seek(0, SeekOrigin.Begin);

            string hashName = Utilities.GetBaseString(Utilities.CalculateStreamHash(outputStream), Utilities.Base63Alphabet);

            outputStream.Seek(0, SeekOrigin.Begin);

            return(new[] { new Asset($"{hashName}{extension}", outputStream) });
        }
Esempio n. 2
0
        public async IAsyncEnumerable <AnalyticsItem> HandleAsync(HttpRequest request)
        {
            if (0 == string.Compare(request.Method, HttpMethods.Post))
            {
                using (Stream inputStream = new AutoStream(32 * 1024))
                {
                    bool hasPopulatedStream = false;

                    if (request.Headers.TryGetValue(HeaderNames.ContentType, out StringValues contentTypeHeader))
                    {
                        if (contentTypeHeader.Any(ct => 0 == string.Compare(ct, AiJsonSerializer.ContentType, StringComparison.OrdinalIgnoreCase)))
                        {
                            this.Logger.LogInformation("Analytics Middleware received compressed JSON data.");

                            using (var zipStream = new GZipStream(request.Body, CompressionMode.Decompress))
                            {
                                await zipStream.CopyToAsync(inputStream);

                                hasPopulatedStream = true;
                            }
                        }
                    }

                    if (!hasPopulatedStream)
                    {
                        await request.Body.CopyToAsync(inputStream);
                    }

                    inputStream.Seek(0, SeekOrigin.Begin);

                    this.Logger.LogInformation("Extracting envelope items from the request body.");
                    var envelopeItems = await NdJsonSerializer.DeserializeAsync <Envelope>(inputStream, AppInsightsHandler.JsonSerializerSettings);

                    this.Logger.LogInformation($"Extracted envelope items.");

                    if (envelopeItems.Any())
                    {
                        foreach (var envelopeItem in envelopeItems)
                        {
                            if (AnalyticsItemPopulator.TryPopulateItem(envelopeItem, out AnalyticsItem analyticsItem))
                            {
                                this.Logger.LogTrace($"Envelope item with data of type '{analyticsItem.Type}' is parsed.");
                                if (this.Populators.TryGetValue(analyticsItem.Type, out AnalyticsItemPopulator populator))
                                {
                                    if (populator.TryPopulate(envelopeItem, ref analyticsItem))
                                    {
                                        this.Logger.LogTrace($"Analytics item of type '{analyticsItem.Type}' is populated.");
                                    }
                                }
                                else
                                {
                                    this.Logger.LogWarning($"AppInsights handler received a type of '{analyticsItem.Type}' and doesn't have a populator registered for that type.");
                                }
                                if (await this.Validator.ValidateInstrumentationKeyAsync(analyticsItem.InstrumentationKey))
                                {
                                    yield return(analyticsItem);
                                }
                            }
                        }
                    }
                }
            }
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            this.Logger.LogInformation($"Html response minification is {(this.Options.MinifyHtml ? "Enabled" : "Disabled")}");
            if (this.Options.MinifyHtml)
            {
                Stream originalStream = context.Response.Body;

                using (AutoStream autoStream = new AutoStream(this.Options.HtmlBufferSize))
                {
                    bool fallbackToDefault = true;
                    context.Response.Body = autoStream;
                    await next.Invoke(context);

                    autoStream.Seek(0, SeekOrigin.Begin);

                    if (!string.IsNullOrWhiteSpace(context.Response.ContentType))
                    {
                        var contentType = new ContentType(context.Response.ContentType);

                        if (0 == string.Compare(contentType.MediaType, MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase))
                        {
                            using (StreamReader reader = new StreamReader(autoStream, Encoding.UTF8, false, 4096, true))
                            {
                                string content = await reader.ReadToEndAsync();

                                var result = Uglify.Html(content, this.HtmlSettings);

                                if (result.HasErrors)
                                {
                                    this.Logger.LogWarning("Html minification has errors. Falling back to no minification.");

                                    foreach (var error in result.Errors)
                                    {
                                        this.Logger.LogWarning(error.ToString());
                                    }
                                }

                                if (!(fallbackToDefault = result.HasErrors))
                                {
                                    context.Response.Body = originalStream;
                                    await context.Response.WriteAsync(result.Code, Encoding.UTF8);

                                    this.Logger.LogInformation($"Html minification succeeded for '{context.Request.Path}'.");
                                }
                            }
                        }
                    }

                    if (fallbackToDefault)
                    {
                        await autoStream.CopyToAsync(originalStream);

                        context.Response.Body = originalStream;
                    }
                }
            }
            else
            {
                await next.Invoke(context);
            }
        }