Esempio n. 1
0
        public string Serialize <T>(T value, MediaTypeHeaderValue contentType)
        {
            if (OutputFormatterSelector == null)
            {
                throw new FormatterNotFoundException(contentType);
            }

            if (value == null)
            {
                return(string.Empty);
            }

            using (var stringWriter = new StringWriter())
            {
                var outputFormatterContext = GetOutputFormatterContext(
                    stringWriter,
                    value,
                    value.GetType(),
                    contentType);

                var formatter = OutputFormatterSelector.SelectFormatter(
                    outputFormatterContext,
                    new List <IOutputFormatter>(),
                    new MediaTypeCollection());

                if (formatter == null)
                {
                    throw new FormatterNotFoundException(contentType);
                }

                formatter.WriteAsync(outputFormatterContext).GetAwaiter().GetResult();
                stringWriter.FlushAsync().GetAwaiter().GetResult();
                return(stringWriter.ToString());
            }
        }
Esempio n. 2
0
        private async Task <string> RenderLayoutAsync(MailTemplateLayout layout, MailTemplateContext context, string body, IDictionary <string, Func <TextWriter, Task> > sections)
        {
            using (var output = new StringWriter())
            {
                layout.Context = context;
                layout.Output  = output;

                layout.ChildBody     = body;
                layout.ChildSections = sections;

                await layout.ExecuteAsync();

                await output.FlushAsync();

                layout.Output = null;

                string result;
                if (layout.Layout != null)
                {
                    result = await RenderLayoutAsync(layout.Layout, context, output.ToString(), layout.Sections);
                }
                else
                {
                    result = output.ToString();
                }

                return(result);
            }
        }
Esempio n. 3
0
        public async Task <string> RenderViewToStringAsync(string viewName, object model, IViewEngine viewEngine)
        {
            var actionContext = await GetActionContextAsync();

            var view = FindView(actionContext, viewName, viewEngine);

            using (var sb = StringBuilderPool.GetInstance())
            {
                using (var output = new StringWriter(sb.Builder))
                {
                    var viewContext = new ViewContext(
                        actionContext,
                        view,
                        new ViewDataDictionary(
                            metadataProvider: new EmptyModelMetadataProvider(),
                            modelState: new ModelStateDictionary())
                    {
                        Model = model
                    },
                        new TempDataDictionary(
                            actionContext.HttpContext,
                            _tempDataProvider),
                        output,
                        new HtmlHelperOptions());

                    await view.RenderAsync(viewContext);

                    await output.FlushAsync();
                }

                return(sb.Builder.ToString());
            }
        }
Esempio n. 4
0
        private async Task <string> RenderAsync(MailTemplate template, MailTemplateContext context)
        {
            using (var output = new StringWriter())
            {
                template.Context = context;
                template.Output  = output;

                await template.ExecuteAsync();

                await output.FlushAsync();

                template.Output = null;

                string result;
                if (template.Layout != null)
                {
                    result = await RenderLayoutAsync(template.Layout, context, output.ToString(), template.Sections);
                }
                else
                {
                    result = output.ToString();
                }

                return(result);
            }
        }
Esempio n. 5
0
        private static string Serialize <T>(T value, IOutputFormatter formatter, MediaTypeHeaderValue contentType)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            using (var stringWriter = new StringWriter())
            {
                var outputFormatterContext = GetOutputFormatterContext(
                    stringWriter,
                    value,
                    value.GetType(),
                    contentType);

                formatter.WriteAsync(outputFormatterContext).GetAwaiter().GetResult();
                stringWriter.FlushAsync().GetAwaiter().GetResult();
                var response = stringWriter.ToString();
                if (string.IsNullOrEmpty(response))
                {
                    // workaround for SystemTextJsonOutputFormatter
                    var ms = (MemoryStream)outputFormatterContext.HttpContext.Response.Body;
                    response = Encoding.ASCII.GetString(ms.ToArray());
                }

                return(response);
            }
        }
Esempio n. 6
0
        public async Task WriteReadLinesAsync()
        {
            var lines = new[] { "Line 1", "Line 2", "Line 3" };

            string data;

            await using (var wr = new StringWriter())
            {
                await wr.WriteLinesAsync("Line 1", "Line 2", "Line 3");

                await wr.FlushAsync();

                data = wr.GetStringBuilder().ToString();
            }

            var expectedWrite = string.Join(Environment.NewLine, lines) +
                                Environment.NewLine;

            Assert.AreEqual(expectedWrite, data);

            string[] readData;
            using (var rd = new StringReader(data))
            {
                readData = await rd.ReadLinesAsync().ToArrayAsync();
            }

            CollectionAssert.AreEqual(lines, readData);
        }
Esempio n. 7
0
        public static async Task <string> ToHtml(this MarkdownDocument markdownDocument, IDocumentationProject documentationProject, string urlBase = "")
        {
            using StringWriter stringWriter = new StringWriter();
            HtmlRenderer htmlRenderer = new HtmlRenderer(stringWriter);

            if (!string.IsNullOrWhiteSpace(urlBase))
            {
                // If the url is a file, we want to remove the query string.
                if (Path.GetExtension(urlBase) == "")
                {
                    htmlRenderer.BaseUrl = new Uri(urlBase, UriKind.Absolute);
                }
                else
                {
                    htmlRenderer.BaseUrl = new Uri(UrlHelper.RemoveUrlQueryStrings(urlBase), UriKind.Absolute);
                }
            }

            htmlRenderer.ObjectRenderers.AddIfNotAlready(new HtmlTableRenderer());

            var linkRender = new LinkInlineRenderer
            {
                LinkRewriter = (originalUrl) => RewriteUrl(originalUrl, urlBase, documentationProject)
            };

            htmlRenderer.ObjectRenderers.ReplaceOrAdd <Markdig.Renderers.Html.Inlines.LinkInlineRenderer>(linkRender);

            htmlRenderer.Render(markdownDocument);
            await stringWriter.FlushAsync();

            return(stringWriter.ToString());
        }
        async Task ShowTranslationHistory()
        {
            if (this.CurrentString == null)
            {
                return;
            }

            StringBuilder sb = new StringBuilder(1000);

            try
            {
                TextWriter wr = new StringWriter(sb);
                await HistoryToText(this.CurrentString, wr);

                await wr.FlushAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "Error");
                return;
            }

            TextViewWindow wnd = new TextViewWindow();

            wnd.Text  = sb.ToString();
            wnd.Title = "String translation history";
            wnd.Owner = this;
            wnd.ShowDialog();
        }
        private static async Task <string> GetTextAsync(Exception ex)
        {
            var writer = new StringWriter();
            await ex.ToDiagnosticStringAsync(writer);

            await writer.FlushAsync();

            var text = writer.ToString();

            return(text);
        }
Esempio n. 10
0
        public static async Task FlushAsyncWorks()
        {
            StringBuilder sb = getSb();
            StringWriter  sw = new StringWriter(sb);

            sw.Write(sb.ToString());

            await sw.FlushAsync(); // I think this is a noop in this case

            Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString());
        }
        public async Task TestHealthCheckWithConnectorAsync()
        {
            // Arrange
            var activity = new Activity
            {
                Type = ActivityTypes.Invoke,
                Name = "healthCheck"
            };

            Activity[] activitiesToSend = null;
            void CaptureSend(Activity[] arg)
            {
                activitiesToSend = arg;
            }

            var turnContext = new TurnContext(new SimpleAdapter(CaptureSend), activity);

            IConnectorClient connector = new MockConnectorClient();

            turnContext.TurnState.Add(connector);

            // Act
            var bot = new ActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.NotNull(activitiesToSend);
            Assert.Single(activitiesToSend);
            Assert.IsType <InvokeResponse>(activitiesToSend[0].Value);
            Assert.Equal(200, ((InvokeResponse)activitiesToSend[0].Value).Status);

            using (var writer = new StringWriter())
            {
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    var settings = new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    };
                    var serializer = JsonSerializer.Create(settings);

                    serializer.Serialize(jsonWriter, ((InvokeResponse)activitiesToSend[0].Value).Body);
                }

                await writer.FlushAsync();

                var obj = JObject.Parse(writer.ToString());

                Assert.True(obj["healthResults"]["success"].Value <bool>());
                Assert.Equal("awesome", obj["healthResults"]["authorization"].ToString());
                Assert.Equal("Windows/3.1", obj["healthResults"]["user-agent"].ToString());
                Assert.Equal("Health check succeeded.", obj["healthResults"]["messages"][0].ToString());
            }
        }
Esempio n. 12
0
        public async Task <string> RenderTemplateAsync <TViewModel>(RouteData routeData, ActionDescriptor actionDescriptor,
                                                                    string viewName, TViewModel viewModel, Dictionary <string, object> additonalViewDictionary = null, bool isMainPage = true) where TViewModel : IViewData
        {
            var httpContext = new DefaultHttpContext
            {
                RequestServices = _serviceProvider
            };

            var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);

            using (var outputWriter = new StringWriter())
            {
                var viewResult     = _viewEngine.FindView(actionContext, viewName, isMainPage);
                var viewDictionary = new ViewDataDictionary <TViewModel>(viewModel.ViewData, viewModel);
                if (additonalViewDictionary != null)
                {
                    foreach (var kv in additonalViewDictionary)
                    {
                        if (!viewDictionary.ContainsKey(kv.Key))
                        {
                            viewDictionary.Add(kv);
                        }
                        else
                        {
                            viewDictionary[kv.Key] = kv.Value;
                        }
                    }
                }

                var tempDataDictionary = new TempDataDictionary(httpContext, _tempDataProvider);

                if (!viewResult.Success)
                {
                    throw new TemplateServiceException($"Failed to render template {viewName} because it was not found.");
                }

                try
                {
                    var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary,
                                                      tempDataDictionary, outputWriter, new HtmlHelperOptions());

                    await viewResult.View.RenderAsync(viewContext);
                }
                catch (Exception ex)
                {
                    throw new TemplateServiceException("Failed to render template due to a razor engine failure", ex);
                }

                await outputWriter.FlushAsync();

                return(outputWriter.ToString());
            }
        }
Esempio n. 13
0
        private static async Task <string> GetTextAsync(Exception ex)
        {
            // ReSharper disable once UseAwaitUsing
            using var writer = new StringWriter();
            await ex.ToDiagnosticStringAsync(writer).ConfigureAwait(false);

            await writer.FlushAsync().ConfigureAwait(false);

            var text = writer.ToString();

            return(text);
        }
Esempio n. 14
0
        public static async Task <int> ExtractJsonFragment(string textToSearch, string text, StringBuilder responseBuilder, int?depthToSearch = null)
        {
            using (var reader = new StringReader(text))
            {
                var writer = new StringWriter(responseBuilder);
                var result = await ExtractJsonFragment(textToSearch, reader, writer, depthToSearch);

                await writer.FlushAsync();

                return(result);
            }
        }
        private async Task <string> Render(MyViewComponentContext myViewComponentContext, string viewComponentName, object args)
        {
            using (var writer = new StringWriter())
            {
                var helper = this.GetViewComponentHelper(myViewComponentContext, writer);
                var result = await helper.InvokeAsync(viewComponentName, args);

                result.WriteTo(writer, HtmlEncoder.Default);
                await writer.FlushAsync();

                return(writer.ToString());
            }
        }
Esempio n. 16
0
        public ContentItemType(IOptions <GraphQLContentOptions> optionsAccessor)
        {
            _options = optionsAccessor.Value;

            Name = "ContentItemType";

            Field(ci => ci.ContentItemId).Description("Content item id");
            Field(ci => ci.ContentItemVersionId).Description("The content item version id");
            Field(ci => ci.ContentType).Description("Type of content");
            Field(ci => ci.DisplayText).Description("The display text of the content item");
            Field(ci => ci.Published).Description("Is the published version");
            Field(ci => ci.Latest).Description("Is the latest version");
            Field <DateTimeGraphType>("modifiedUtc", resolve: ci => ci.Source.ModifiedUtc, description: "The date and time of modification");
            Field <DateTimeGraphType>("publishedUtc", resolve: ci => ci.Source.PublishedUtc, description: "The date and time of publication");
            Field <DateTimeGraphType>("createdUtc", resolve: ci => ci.Source.CreatedUtc, description: "The date and time of creation");
            Field(ci => ci.Owner).Description("The owner of the content item");
            Field(ci => ci.Author).Description("The author of the content item");

            Field <StringGraphType, string>()
            .Name("render")
            .ResolveLockedAsync(async context =>
            {
                var userContext     = (GraphQLContext)context.UserContext;
                var serviceProvider = userContext.ServiceProvider;

                // Build shape
                var displayManager      = serviceProvider.GetRequiredService <IContentItemDisplayManager>();
                var updateModelAccessor = serviceProvider.GetRequiredService <IUpdateModelAccessor>();
                var model = await displayManager.BuildDisplayAsync(context.Source, updateModelAccessor.ModelUpdater);

                var displayHelper = serviceProvider.GetRequiredService <IDisplayHelper>();
                var htmlEncoder   = serviceProvider.GetRequiredService <HtmlEncoder>();

                using (var sb = StringBuilderPool.GetInstance())
                {
                    using (var sw = new StringWriter(sb.Builder))
                    {
                        var htmlContent = await displayHelper.ShapeExecuteAsync(model);
                        htmlContent.WriteTo(sw, htmlEncoder);

                        await sw.FlushAsync();
                        return(sw.ToString());
                    }
                }
            });

            Interface <ContentItemInterface>();

            IsTypeOf = IsContentType;
        }
Esempio n. 17
0
            static async ValueTask <string> Awaited(
                ValueTask task,
                StringWriter writer,
                StringBuilderPool builder)
            {
                await task;
                await writer.FlushAsync();

                var s = builder.ToString();

                builder.Dispose();
                writer.Dispose();
                return(s);
            }
Esempio n. 18
0
        public async Task TestHealthCheckAsync()
        {
            // Arrange
            var activity = new Activity
            {
                Type = ActivityTypes.Invoke,
                Name = "healthCheck"
            };

            Activity[] activitiesToSend = null;
            void CaptureSend(Activity[] arg)
            {
                activitiesToSend = arg;
            }

            var turnContext = new TurnContext(new SimpleAdapter(CaptureSend), activity);

            // Act
            var bot = new ActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.IsNotNull(activitiesToSend);
            Assert.AreEqual(1, activitiesToSend.Length);
            Assert.IsInstanceOfType(activitiesToSend[0].Value, typeof(InvokeResponse));
            Assert.AreEqual(200, ((InvokeResponse)activitiesToSend[0].Value).Status);

            using (var writer = new StringWriter())
            {
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    var settings = new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    };
                    var serializer = JsonSerializer.Create(settings);

                    serializer.Serialize(jsonWriter, ((InvokeResponse)activitiesToSend[0].Value).Body);
                }

                await writer.FlushAsync();

                var obj = JObject.Parse(writer.ToString());

                Assert.IsTrue(obj["healthResults"]["success"].Value <bool>());
                Assert.AreEqual("Health check succeeded.", obj["healthResults"]["messages"][0].ToString());
            }
        }
        private async Task <string> EvaluateStatementsAsync(TextEncoder encoder, TemplateContext context)
        {
            using (var sb = StringBuilderPool.GetInstance())
            {
                using (var content = new StringWriter(sb.Builder))
                {
                    foreach (var statement in Statements)
                    {
                        await statement.WriteToAsync(content, encoder, context);
                    }

                    await content.FlushAsync();
                }

                return(sb.Builder.ToString());
            }
        }
Esempio n. 20
0
        //以下为序列化XML
        // 注意目标类必须包含     [XmlRoot(ElementName = "entry")]
        // [XmlElement("id")]         [XmlAttribute("href")] 类似的属性标记
        // 比如:
        // [XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
        //public class Feed : ViewModelBase
        //{
        //    private string title;
        //    [XmlElement("title")]
        //    public string Title{get;set;}

        //    private string id;
        //    [XmlElement("id")]
        //    public string ID{get;set;}

        //    private ObservableCollection<Entry> entries;
        //    [XmlElement("entry")]
        //    public ObservableCollection<Entry> Entries{get;set;}

        /// <summary>
        /// 序列化成XML
        /// </summary>
        /// <typeparam name="T">源对象的类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns>返回xml</returns>
        public async static Task <string> SerializeToXml <T>(T obj)
        {
            if (obj != null)
            {
                var ser = new XmlSerializer(typeof(T));
                using (var writer = new StringWriter())
                {
                    ser.Serialize(writer, obj);
                    await writer.FlushAsync();

                    return(writer.GetStringBuilder().ToString());
                }
            }
            else
            {
                return(null);
            }
        }
        public string Serialize <T>(T value, MediaTypeHeaderValue contentType)
        {
            if (OutputFormatterSelector == null)
            {
                throw new FormatterNotFoundException(contentType);
            }

            if (value == null)
            {
                return(string.Empty);
            }

            using (var stringWriter = new StringWriter())
            {
                var outputFormatterContext = GetOutputFormatterContext(
                    stringWriter,
                    value,
                    value.GetType(),
                    contentType);

                var formatter = OutputFormatterSelector.SelectFormatter(
                    outputFormatterContext,
                    new List <IOutputFormatter>(),
                    new MediaTypeCollection());

                if (formatter == null)
                {
                    throw new FormatterNotFoundException(contentType);
                }

                formatter.WriteAsync(outputFormatterContext).GetAwaiter().GetResult();
                stringWriter.FlushAsync().GetAwaiter().GetResult();
                var result = stringWriter.ToString();
                if (string.IsNullOrEmpty(result))
                {
                    // workaround for SystemTextJsonOutputFormatter
                    var ms = (MemoryStream)outputFormatterContext.HttpContext.Response.Body;
                    result = Encoding.UTF8.GetString(ms.ToArray());
                }

                return(result);
            }
        }
Esempio n. 22
0
        async Task <string> RenderView(IView view, ViewDataDictionary viewData, ActionContext actionContext, ImageEmbedder imageEmbedder)
        {
            //https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.ViewFeatures/ViewFeatures/ViewExecutor.cs
            var response = actionContext.HttpContext.Response;
            var tempDataDictionaryFactory = serviceProvider.GetRequiredService <ITempDataDictionaryFactory>();
            var viewOptions = serviceProvider.GetService <Microsoft.Extensions.Options.IOptions <MvcViewOptions> >();

            using (var writer = new StringWriter())
            {
                var tempData    = tempDataDictionaryFactory.GetTempData(actionContext.HttpContext);
                var viewContext = new ViewContext(actionContext, view, viewData, tempData, writer, viewOptions.Value.HtmlHelperOptions);
                viewData[ImageEmbedder.ViewDataKey] = imageEmbedder;
                await view.RenderAsync(viewContext);

                viewData.Remove(ImageEmbedder.ViewDataKey);
                await writer.FlushAsync();

                return(writer.GetStringBuilder().ToString());
            }
        }
Esempio n. 23
0
        public string Serialize <T>(T value, IOutputFormatter formatter, MediaTypeHeaderValue contentType)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            using (var stringWriter = new StringWriter())
            {
                var outputFormatterContext = GetOutputFormatterContext(
                    stringWriter,
                    value,
                    value.GetType(),
                    contentType);

                formatter.WriteAsync(outputFormatterContext).GetAwaiter().GetResult();
                stringWriter.FlushAsync().GetAwaiter().GetResult();
                return(stringWriter.ToString());
            }
        }
Esempio n. 24
0
        public static async Task <string> Serialize <T>(T obj)
        {
            var result = string.Empty;

            if (obj != null)
            {
                var ser = new XmlSerializer(typeof(T));

                using (var writer = new StringWriter())
                {
                    ser.Serialize(writer, obj);

                    await writer.FlushAsync();

                    result = writer.GetStringBuilder().ToString();
                }
            }

            return(result);
        }
Esempio n. 25
0
        /// <summary>
        /// Render component to string
        /// </summary>
        /// <param name="componentName">Component name</param>
        /// <param name="arguments">Arguments</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the result
        /// </returns>
        protected virtual async Task <string> RenderViewComponentToStringAsync(string componentName, object arguments = null)
        {
            var helper = new DefaultViewComponentHelper(
                EngineContext.Current.Resolve <IViewComponentDescriptorCollectionProvider>(),
                HtmlEncoder.Default,
                EngineContext.Current.Resolve <IViewComponentSelector>(),
                EngineContext.Current.Resolve <IViewComponentInvokerFactory>(),
                EngineContext.Current.Resolve <IViewBufferScope>());

            using var writer = new StringWriter();
            var context = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());

            helper.Contextualize(context);
            var result = await helper.InvokeAsync(componentName, arguments);

            result.WriteTo(writer, HtmlEncoder.Default);
            await writer.FlushAsync();

            return(writer.ToString());
        }
Esempio n. 26
0
        public static async Task <string> RenderViewComponentAsync(this Controller controller, string nombreComponent, object parametros = null)
        {
            var servicesProvider = controller.HttpContext.RequestServices;
            var helper           = new DefaultViewComponentHelper(
                servicesProvider.GetRequiredService <IViewComponentDescriptorCollectionProvider>(),
                HtmlEncoder.Default,
                servicesProvider.GetRequiredService <IViewComponentSelector>(),
                servicesProvider.GetRequiredService <IViewComponentInvokerFactory>(),
                servicesProvider.GetRequiredService <IViewBufferScope>());

            using (var writer = new StringWriter())
            {
                var context = new ViewContext(controller.ControllerContext, NullView.Instance, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
                helper.Contextualize(context);
                var result = await helper.InvokeAsync(nombreComponent, parametros);

                result.WriteTo(writer, HtmlEncoder.Default);
                await writer.FlushAsync();

                return(writer.ToString());
            }
        }
            public override async Task ExecuteAsync(
                ActionContext actionContext,
                IView view,
                ViewDataDictionary viewData,
                ITempDataDictionary tempData,
                string contentType,
                int?statusCode)
            {
                using (var stringWriter = new StringWriter(StringBuilder))
                {
                    var viewContext = new ViewContext(
                        actionContext,
                        view,
                        viewData,
                        tempData,
                        stringWriter,
                        ViewOptions.HtmlHelperOptions);
                    await ExecuteAsync(viewContext, contentType, statusCode);

                    await stringWriter.FlushAsync();
                }
            }
        /// <summary>
        /// Starts the a <see cref="Process" /> asynchronously.
        /// </summary>
        /// <param name="workingDirectory">The working directory.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="showShellWindow">if set to <c>true</c> show a shell window instead of logging.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The result and console output from executing the process.
        /// </returns>
        public static async Task <(ProcessResult processResult, string message)> StartAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            bool showShellWindow = false,
            CancellationToken cancellationToken = default)
        {
            TestLogger.WriteLine($"Executing {fileName} {arguments} from {workingDirectory}");

            var stringBuilder = new StringBuilder();

            using (var stringWriter = new StringWriter(stringBuilder))
            {
                ProcessResult processResult;
                try
                {
                    var exitCode = await StartProcessAsync(
                        fileName,
                        arguments,
                        workingDirectory,
                        stringWriter,
                        stringWriter,
                        showShellWindow,
                        cancellationToken).ConfigureAwait(false);

                    processResult = exitCode == 0 ? ProcessResult.Succeeded : ProcessResult.Failed;
                }
                catch (TaskCanceledException)
                {
                    await stringWriter.FlushAsync().ConfigureAwait(false);

                    TestLogger.WriteLine($"Timed Out {fileName} {arguments} from {workingDirectory}");
                    processResult = ProcessResult.TimedOut;
                }

                var message = GetAndWriteMessage(processResult, stringBuilder.ToString());
                return(processResult, message);
            }
        }
    public async Task <string> RenderViewComponent(string viewComponent, object args)
    {
        var sp = HttpContext.RequestServices;

        var helper = new DefaultViewComponentHelper(
            sp.GetRequiredService <IViewComponentDescriptorCollectionProvider>(),
            HtmlEncoder.Default,
            sp.GetRequiredService <IViewComponentSelector>(),
            sp.GetRequiredService <IViewComponentInvokerFactory>(),
            sp.GetRequiredService <IViewBufferScope>());

        using (var writer = new StringWriter()) {
            var context = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());
            helper.Contextualize(context);
            var result = await helper.InvokeAsync(viewComponent, args);

            result.WriteTo(writer, HtmlEncoder.Default);
            await writer.FlushAsync();

            return(writer.ToString());
        }
    }
Esempio n. 30
0
        public async Task DisplayedAsync(ShapeDisplayContext context)
        {
            var cacheContext = context.ShapeMetadata.Cache();

            // If the shape is not configured to be cached, continue as usual
            if (cacheContext == null)
            {
                if (context.ChildContent == null)
                {
                    context.ChildContent = HtmlString.Empty;
                }

                return;
            }

            // If we have got this far, then this shape is configured to be cached.
            // We need to determine whether or not the ChildContent of this shape was retrieved from the cache by the DisplayingAsync method above, as opposed to generated by the View Engine.
            // ChildContent will be generated by the View Engine if it was not available in the cache when we rendered the shape.
            // In this instance, we need insert the ChildContent into the cache so that subsequent attempt to render this shape can take advantage of the cached content.

            // If the ChildContent was retrieved form the cache, then the Cache Context will be present in the _cached collection (see the DisplayingAsync method in this class).
            // So, if the cache context is not present in the _cached collection, we need to insert the ChildContent value into the cache:
            if (!_cached.ContainsKey(cacheContext.CacheId) && context.ChildContent != null)
            {
                // The content is pre-encoded in the cache so we don't have to do it every time it's rendered
                using (var sb = StringBuilderPool.GetInstance())
                {
                    using (var sw = new StringWriter(sb.Builder))
                    {
                        context.ChildContent.WriteTo(sw, HtmlEncoder.Default);
                        await _dynamicCacheService.SetCachedValueAsync(cacheContext, sw.ToString());

                        await sw.FlushAsync();
                    }
                }
            }
        }