public void SetEncoding() { var response = new HtmlResponse("Test", encoding: Encoding.ASCII); response.ContentType.Should().Be("text/html"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Body.AsString().Should().Be("Test"); }
public void SetContentType() { var response = new HtmlResponse("Test", contentType: "text/javascript"); response.ContentType.Should().Be("text/javascript"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Body.AsString().Should().Be("Test"); }
public Response ProcessRequest(NancyContext context, string path) { var pattern = new Regex(@"~?/?[a-z]{5,}/[a-f0-9]{10,}/", RegexOptions.IgnoreCase); path = pattern.Replace(path, "/"); using (bundles.GetReadLock()) { var bundle = bundles.FindBundlesContainingPath(path).OfType <TBundle>().FirstOrDefault(); if (bundle == null) { logger.Info("ProcessRequest : Bundle '{0}' not found", path); return(new HtmlResponse(HttpStatusCode.NotFound)); } var actualETag = "\"" + bundle.Hash.ToHexString() + "\""; var givenETag = context.Request.Headers["If-None-Match"]; if (givenETag.Equals(actualETag)) { logger.Info("ProcessRequest : Bundle '{0}' not modified", path); var notModified = new HtmlResponse(HttpStatusCode.NotModified); notModified.ContentType = bundle.ContentType; return(notModified); } logger.Info("ProcessRequest : Bundle '{0}' returned", path); var response = new StreamResponse(bundle.OpenStream, bundle.ContentType); response.WithHeader("ETag", actualETag); return(response); } }
public void NullBody() { var response = new HtmlResponse(null); response.ContentType.Should().Be("text/html"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Body.AsString().Should().BeNull(); }
public BaseModule() { HtmlResponse unAuthorizedResponse = new HtmlResponse(HttpStatusCode.Unauthorized); unAuthorizedResponse.Headers.Add("WWW-Authenticate", "NTLM"); Before += x => { return(GetUser(this.Context) == null ? unAuthorizedResponse : null); }; }
internal void WebRequestPreSendHeaders() { this.GetFireDump().CloseHeaders(); if (this.Enabled == true) { if (!this.webRedirect.HasValue) { this.webRedirect = Dispatcher.webCheckIfResponseIsRedirect(); } // add possible rendered exceptions and debug bar if necessary if (this.webRenderDesharpBar > -1 && Dispatcher.WebCheckIfResponseIsHtmlOrXml()) { this.webRenderDesharpBar = 1; } if (this.webRenderDesharpBar == 1 && this.webRedirect != true) { string responseContentType = HttpContext.Current.Response.ContentType.ToLower(); if (!Dispatcher.WebCheckIfResponseIsHtmlOrXml()) { // if there was necessary to render in output anything (by response type change to text/html) // change response to that type if it is not any proper type to render any html code HttpContext.Current.Response.ContentType = "text/html"; } // manage Content-Security-Policy http header this.webManageContentSecurityPolicyHeader(); } } else { if (this.webTransmitErrorPage && Dispatcher.WebStaticErrorPage.Length > 0) { HtmlResponse.TransmitStaticErrorPagePrepareHeaders(); } } }
/// <summary> /// Adds the file. /// </summary> /// <param name="pageContent">Content of the page.</param> /// <param name="packagePath">The package path.</param> /// <returns></returns> private void AddFile(string pageContent, string packagePath) { Assert.ArgumentNotNullOrEmpty(pageContent, nameof(pageContent)); Assert.ArgumentNotNullOrEmpty(packagePath, nameof(packagePath)); var uploadPackagePage = new HtmlResponse(pageContent); var viewState = uploadPackagePage.GetValueByElementName("__VIEWSTATE", false); var csrfToken = uploadPackagePage.GetValueByElementName("__CSRFTOKEN", false); var fileHandler = uploadPackagePage.GetNameByElementType("file"); this.formData = new NameValueCollection { { "__CSRFTOKEN", csrfToken }, { "__VIEWSTATE", viewState }, { "Unzip", "0" }, { "Overwrite", "1" }, { "__EVENTTARGET", "NextButton" }, { "__EVENTARGUMENT", "" }, { "__SOURCE", "NextButton" }, { "__EVENTTYPE", "click" }, { "__ISEVENT", "1" }, { "__BUTTON", "0" }, { fileHandler, packagePath } }; this.Client.Post(uploadPackageWizardUrl, this.formData); }
public void Defaults() { var response = new HtmlResponse("Test"); response.ContentType.Should().Be("text/html"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Body.AsString().Should().Be("Test"); }
public override async Task Process(HtmlResponse response) { Console.WriteLine($"Url:{response.Url}"); Console.WriteLine($"Document String:{response.ToString()}"); //response.Css("div", "class", "id"); //response.Meta("name"); }
/// <summary> /// Restore the data store. /// </summary> /// <returns> /// The <see cref="Response"/>. /// </returns> internal Response RestoreDatastore() { if (!AppConfig.Current.Backtier.IsDbRestoreEnabled) { Logger.Info( "Data restore API invoked but it was disabled from configuration, cancel further processing..."); var notAcceptableResponse = new Response().WithStatusCode(HttpStatusCode.NotAcceptable); this.HeaderInfoProvider.RegisterResponseHeaders(notAcceptableResponse); return(notAcceptableResponse); } try { Logger.Info("Starting data store rollback"); this.DataStoreController.RestoreDataStore(); // reset the credential cache as the underlying datastore was reset this.WebServiceAuthentication.ResetCredentialCache(); Logger.Info("Finished data store rollback"); var response = new HtmlResponse(); this.HeaderInfoProvider.RegisterResponseHeaders(response); return(response); } catch (Exception ex) { Logger.Error(ex, "Error occured during data store rollback"); var errorResponse = new HtmlResponse(HttpStatusCode.InternalServerError); this.HeaderInfoProvider.RegisterResponseHeaders(errorResponse); return(errorResponse); } }
internal void WebRequestPreSendBody() { if (this.Enabled == true) { if (this.webRenderDesharpBar == 1 && this.webRedirect != true) { // render debug bar for current request with any previous redirect records from session List <List <RenderedPanel> > renderedPanels = this.webReqEndSession ?? Dispatcher.webGetSessionStorrage(); if (this.webBarPanels != null) { renderedPanels.Insert(0, HtmlResponse.RenderDebugPanels(this.webBarPanels)); this.webBarPanels = null; } HtmlResponse.WriteDebugBarToResponse(renderedPanels); } else { //HttpContext.Current.Response.Flush(); } } else { if (this.webTransmitErrorPage && Dispatcher.WebStaticErrorPage.Length > 0) { HtmlResponse.TransmitStaticErrorPageSendContent(); } //HttpContext.Current.Response.Flush(); } }
public static void Stop() { Dispatcher dispatcher = Dispatcher.GetCurrent(); if (dispatcher.Enabled != true) { return; } bool htmlOut = dispatcher.Output == LogFormat.Html && Dispatcher.EnvType == EnvType.Web; string renderedException = Exceptions.RenderCurrentApplicationPoint( "Script has been stopped.", "Exception", false, htmlOut ); if (Dispatcher.EnvType == EnvType.Web) { HtmlResponse.SendRenderedExceptions(renderedException, "Exception"); } else { dispatcher.WriteExceptionToOutput(new List <string>() { renderedException }); Console.ReadLine(); } dispatcher.Stop(); }
public Response ProcessRequest(NancyContext context, string path) { path = string.Concat("~", path.Substring(PathPrefix.Length)); using (bundles.GetReadLock()) { Bundle bundle; IAsset asset; if (!bundles.TryGetAssetByPath(path, out asset, out bundle)) { logger.Info("ProcessRequest : Asset '{0}' not found", path); return(new HtmlResponse(HttpStatusCode.NotFound)); } var actualETag = "\"" + asset.Hash.ToHexString() + "\""; var givenETag = context.Request.Headers["If-None-Match"]; if (givenETag.Equals(actualETag)) { logger.Info("ProcessRequest : Asset '{0}' not modified", path); var notModified = new HtmlResponse(HttpStatusCode.NotModified); notModified.ContentType = bundle.ContentType; return(notModified); } logger.Info("ProcessRequest : Asset '{0}' returned", path); var response = new StreamResponse(asset.OpenStream, bundle.ContentType); response.WithHeader("ETag", actualETag); return(response); } }
internal void WebRequestSessionEnd() { if (this.WebRequestState < 3) { if (this.Enabled == true && this.webBarPanels != null) { this.WebRequestEndTime = Debug.GetProcessingTime(); HttpSessionState session = HttpContext.Current.Session; List <List <RenderedPanel> > sessionStorrage = Dispatcher.webGetSessionStorrage(); this.webRedirect = Dispatcher.webCheckIfResponseIsRedirect(); if (this.webRedirect == true) { this.webRequestSessionEndCallBarPanelsSessionEnd(); List <RenderedPanel> renderedPanels = HtmlResponse.RenderDebugPanels(this.webBarPanels); sessionStorrage.Insert(0, renderedPanels); if (session is HttpSessionState) { session[Debug.SESSION_STORAGE_KEY] = sessionStorrage; } this.webBarPanels = null; // frees memory } else { this.webReqEndSession = sessionStorrage; // clear session storage, panels will be rendered in this request end event if (session is HttpSessionState && session[Debug.SESSION_STORAGE_KEY] != null) { session.Remove(Debug.SESSION_STORAGE_KEY); } this.webRequestSessionEndCallBarPanelsSessionEnd(); } } this.WebRequestState = 3; } }
public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var template = renderContext.ViewCache.GetOrAdd(viewLocationResult, result => { try { var context = new NancyVeilContext(renderContext, Extensions); var engine = new VeilEngine(context); Type modelType = model == null ? typeof(object) : model.GetType(); return(engine.CompileNonGeneric(viewLocationResult.Extension, result.Contents(), modelType)); } catch (Exception e) { return(CreateErrorPage(e)); } }); var response = new HtmlResponse(); response.ContentType = "text/html; charset=utf-8"; response.Contents = s => { var writer = new StreamWriter(s, Encoding.UTF8); template(writer, model); writer.Flush(); }; return(response); }
/// <summary> /// Selects the file. /// </summary> /// <param name="pageContent">Content of the page.</param> /// <param name="packageName">Name of the package.</param> private void SelectFile(string pageContent, string packageName) { Assert.ArgumentNotNullOrEmpty(pageContent, nameof(pageContent)); Assert.ArgumentNotNullOrEmpty(packageName, nameof(packageName)); var package = Path.GetFileName(packageName); var uploadPackagePage = new HtmlResponse(pageContent); var viewState = uploadPackagePage.GetValueByElementName("__VIEWSTATE", false); var csrfToken = uploadPackagePage.GetValueByElementName("__CSRFTOKEN", false); this.formData = new NameValueCollection { { "__PARAMETERS", "" }, { "__EVENTTARGET", "NextButton" }, { "__EVENTARGUMENT", "" }, { "__SOURCE", "NextButton" }, { "__CSRFTOKEN", csrfToken }, { "__VIEWSTATE", viewState }, { "__EVENTTYPE", "click" }, { "__ISEVENT", "1" }, { "PackageFile", package }, { "AcceptLicense", "yes" }, { "PackageName", package }, { "Version", "1.0" }, { "Author", "" }, { "Publisher", "" }, { "Restart", "1" }, { "ReadmeText", "" } }; this.Client.Post(InstallationWizardUrl, this.formData); }
/// <summary> /// Renders the view. /// </summary> /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param> /// <param name="model">The model that should be passed into the view</param> /// <param name="renderContext">The render context.</param> /// <param name="isPartial">Used by HtmlHelpers to declare a view as partial</param> /// <returns>A response.</returns> public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext, bool isPartial) { Assembly referencingAssembly = null; if (model != null) { var underlyingSystemType = model.GetType().UnderlyingSystemType; if (underlyingSystemType != null) { referencingAssembly = Assembly.GetAssembly(underlyingSystemType); } } var response = new HtmlResponse(); response.Contents = stream => { var writer = new StreamWriter(stream); var view = this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model); view.ExecuteView(null, null); var body = view.Body; var sectionContents = view.SectionContents; var layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial); var root = string.IsNullOrWhiteSpace(layout); while (!root) { var viewLocation = renderContext.LocateView(layout, model); if (viewLocation == null) { throw new InvalidOperationException("Unable to locate layout: " + layout); } view = this.GetViewInstance(viewLocation, renderContext, referencingAssembly, model); view.ExecuteView(body, sectionContents); body = view.Body; sectionContents = view.SectionContents; layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial); root = !view.HasLayout; } writer.Write(body); writer.Flush(); }; return(response); }
/// <summary> /// The HtmlResponse process is the only process that invokes the workflow post router for final /// processing of the HTML. /// </summary> public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlResponse resp) { proc.ServiceManager.IfExists <IWebWorkflowService>(wws => wws.PostRouter(resp.Context, resp)); byte[] utf8data = resp.Html.to_Utf8(); resp.Context.Response.ContentType = "text/html"; resp.Context.Response.ContentEncoding = Encoding.UTF8; resp.Context.Response.ContentLength64 = utf8data.Length; resp.Context.Response.OutputStream.Write(utf8data, 0, utf8data.Length); resp.Context.Response.Close(); }
private Response HtmlResponse(string html) { var response = new HtmlResponse(); response.ContentType = "text/html; charset=utf-8"; response.Contents = s => { var writer = new StreamWriter(s, Encoding.UTF8); writer.Write(html); writer.Flush(); }; return(response); }
public static async Task <IHttpResponse> Post( [PropertyOptional(Name = StatePropertyName)] string state, [PropertyOptional(Name = CodePropertyName)] string code, [PropertyOptional(Name = TokenPropertyName)] string token, [PropertyOptional(Name = UserPropertyName)] string user, IAzureApplication application, IHttpRequest request, IProvideUrl urlHelper, IInvokeApplication endpoints, RedirectResponse onRedirectResponse, BadRequestResponse onBadCredentials, HtmlResponse onCouldNotConnect, HtmlResponse onGeneralFailure) { var method = EastFive.Azure.Auth.Method.ByMethodName( AppleProvider.IntegrationName, application); var requestParams = new Dictionary <string, string>(); if (state.HasBlackSpace()) { requestParams.Add(AppleProvider.responseParamState, state); } if (code.HasBlackSpace()) { requestParams.Add(AppleProvider.responseParamCode, code); } if (token.HasBlackSpace()) { requestParams.Add(AppleProvider.responseParamIdToken, token); } if (user.HasBlackSpace()) { requestParams.Add(AppleProvider.responseParamUser, user); } return(await ProcessRequestAsync(method, requestParams, application, request, endpoints, urlHelper, (redirect, accountIdMaybe) => { return onRedirectResponse(redirect); }, (why) => onBadCredentials().AddReason(why), (why) => { return onCouldNotConnect(why); }, (why) => { return onGeneralFailure(why); })); }
protected Response Html(string html, CookieCollection cookies) { var response = new HtmlResponse(html); if (cookies != null) { foreach (var cookie in cookies) { response.Cookies.Add(cookie.Name, cookie.Value); } } return(response); }
public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { Model = model; string etag; using (SHA1 gen = new SHA1Managed()) { etag = Convert.ToBase64String(gen.ComputeHash(System.Text.Encoding.UTF8.GetBytes((string)Model))); } HtmlResponse resp = new HtmlResponse(RetCode, ReturnContent); resp.Headers["ETag"] = etag; return(resp); }
public static async Task <IHttpResponse> Post( [Property(Name = StatePropertyName)] string state, [PropertyOptional(Name = CodePropertyName)] string code, [Property(Name = TokenPropertyName)] string token, AzureApplication application, IHttpRequest request, IProvideUrl urlHelper, IInvokeApplication endpoints, RedirectResponse onRedirectResponse, BadRequestResponse onBadCredentials, HtmlResponse onCouldNotConnect, HtmlResponse onGeneralFailure) { var method = EastFive.Azure.Auth.Method.ByMethodName( AzureADB2CProvider.IntegrationName, application); var requestParams = request.RequestUri .ParseQuery() .Distinct(kvp => kvp.Key) .ToDictionary(); if (state.HasBlackSpace()) { requestParams.Add(StatePropertyName, state); } if (code.HasBlackSpace()) { requestParams.Add(CodePropertyName, code); } if (token.HasBlackSpace()) { requestParams.Add(TokenPropertyName, token); } return(await ProcessRequestAsync(method, requestParams, application, request, endpoints, urlHelper, (redirect, accountIdMaybe) => { return onRedirectResponse(redirect); }, (why) => onBadCredentials().AddReason(why), (why) => { return onCouldNotConnect(why); }, (why) => { return onGeneralFailure(why); })); }
/// <summary> /// The HtmlResponse process is the only process that invokes the workflow post router for final /// processing of the HTML. /// </summary> public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlResponse resp) { proc.ServiceManager.IfExists <IWebWorkflowService>(wws => wws.PostRouter(resp.Context, resp)); // resp.Context.Response.ContentLength64 = resp.Html.Length; if (resp.Context.Request.AcceptEncoding) { resp.Context.Response.WriteCompressed(resp.Html, "text/html"); } else { resp.Context.Response.Write(resp.Html, "text/html"); } }
public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var viewName = viewLocationResult.Location + "/" + viewLocationResult.Name; var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider, User = renderContext?.Context?.CurrentUser }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.FindView(actionContext, viewName, false); if (viewResult.View == null) { throw new ArgumentNullException($"{viewName} does not match any available view"); } var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw, new HtmlHelperOptions() ); viewResult.View.RenderAsync(viewContext).Wait(); var response = new HtmlResponse { Contents = stream => { using (var writer = new StreamWriter(stream)) { writer.Write(sw.ToString()); writer.Flush(); } } }; return(response); } }
public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var response = new HtmlResponse(); var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result => ConvertMarkdown(viewLocationResult)); response.Contents = stream => { var writer = new StreamWriter(stream); writer.Write(html); writer.Flush(); }; return(response); }
public ResponseModel LoadUrl(string Url) { if (string.IsNullOrEmpty(Url)) { return(null); } HtmlResponse resp = HtmlContent(Url); List <string> imageUrls = GetListOfImageUrls(resp.Url, resp.Content); string[] words = GetWords(resp.Content); Dictionary <string, int> wordCountMap = BuildWordCount(words); int totalWordCount = words != null? words.Length: 0; return(new ResponseModel(imageUrls, wordCountMap, totalWordCount)); }
public static async Task <IHttpResponse> GetAsync( [QueryParameter(Name = AuthenticationPropertyName)] IRef <Authentication> authenticationRef, [Accepts(Media = "text/html")] MediaTypeWithQualityHeaderValue accept, ContentTypeResponse <Authentication> onFound, HtmlResponse onHtmlWanted, NotFoundResponse onNotFound) { if (!accept.IsDefaultOrNull()) { return(onHtmlWanted(Properties.Resources.loginHtml)); } return(await authenticationRef.StorageGetAsync( (authentication) => { return onFound(authentication); }, () => onNotFound())); }
/// <summary> /// Renders the view. /// </summary> /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param> /// <param name="model">The model that should be passed into the view</param> /// <param name="renderContext"></param> /// <returns>A response.</returns> public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { //@(section)?[\s]*(?<name>[A-Za-z]*)[\s]*{(?<content>[^\}]*)}? Assembly referencingAssembly = null; if (model != null) { var underlyingSystemType = model.GetType().UnderlyingSystemType; if (underlyingSystemType != null) { referencingAssembly = Assembly.GetAssembly(underlyingSystemType); } } var response = new HtmlResponse(); response.Contents = stream => { var writer = new StreamWriter(stream); NancyRazorViewBase view = this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model); view.ExecuteView(null, null); var body = view.Body; var sectionContents = view.SectionContents; var root = !view.HasLayout; var layout = view.Layout; while (!root) { view = this.GetViewInstance(renderContext.LocateView(layout, model), renderContext, referencingAssembly, model); view.ExecuteView(body, sectionContents); body = view.Body; sectionContents = view.SectionContents; root = !view.HasLayout; } writer.Write(body); writer.Flush(); }; return(response); }
public void ParseRestRoot() { const string RestRootHtml = @" <html> <head> <title>Directory of /3270/rest/</title> </head> <body> <h1>Directory of /3270/rest/</h1> <p> <tt> <a href=""/3270/rest/json"">json/</a> </tt>REST JSON interface </p> <p> <tt> <a href=""html/Query()"">html/</a> </tt>REST HTML interface </p> <p> <tt> <a href=""stext/Query()"">stext/</a> </tt>REST plain text interface with status line </p> <p> <tt> <a href=""text/Query()"">text/</a> </tt>REST plain text interface </p> <hr> <i>wc3270 v3.5ga10 Mon Jan 16 17:54:50 CST 2017 pdm - <a href=""http://x3270.bgp.nu/"">x3270.bgp.nu</a> </i> </body> </html> "; HtmlResponse htmlResponse; Assert.True(HtmlResponse.TryParseRestRoot(RestRootHtml, out htmlResponse)); Assert.That(htmlResponse.StatusText == "Directory of /3270/rest/"); Assert.That(htmlResponse.InfoText == "wc3270 v3.5ga10 Mon Jan 16 17:54:50 CST 2017 pdm"); Assert.That(htmlResponse.ErrorText == string.Empty); }
public PostRouteWorkflowData(IServiceManager serviceManager, HttpListenerContext context, HtmlResponse htmlResponse) { ServiceManager = serviceManager; Context = context; HtmlResponse = htmlResponse; }
public bool PostRouter(HttpListenerContext context, HtmlResponse response) { WorkflowState state = postRouteWorkflow.Execute(new PostRouteWorkflowData(ServiceManager, context, response)); return state == WorkflowState.Done; }
/// <summary> /// Renders the view. /// </summary> /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param> /// <param name="model">The model that should be passed into the view</param> /// <param name="renderContext">The render context.</param> /// <returns>A response.</returns> public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var response = new HtmlResponse(); var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result => { return ConvertMarkdown(viewLocationResult); }); var renderHtml = this.engineWrapper.Render(html, model, new MarkdownViewEngineHost(new NancyViewEngineHost(renderContext), renderContext, this.Extensions)); response.Contents = stream => { var writer = new StreamWriter(stream); writer.Write(renderHtml); writer.Flush(); }; return response; }
/// <summary> /// Renders the view. /// </summary> /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param> /// <param name="model">The model that should be passed into the view</param> /// <param name="renderContext"></param> /// <returns>A response.</returns> public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { Assembly referencingAssembly = null; if (model != null) { var underlyingSystemType = model.GetType().UnderlyingSystemType; if (underlyingSystemType != null) { referencingAssembly = Assembly.GetAssembly(underlyingSystemType); } } var response = new HtmlResponse(); response.Contents = stream => { var writer = new StreamWriter(stream); var view = this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model); view.ExecuteView(null, null); var body = view.Body; var sectionContents = view.SectionContents; var root = !view.HasLayout; var layout = view.Layout; while (!root) { view = this.GetViewInstance(renderContext.LocateView(layout, model), renderContext, referencingAssembly, model); view.ExecuteView(body, sectionContents); body = view.Body; sectionContents = view.SectionContents; root = !view.HasLayout; } writer.Write(body); writer.Flush(); }; return response; }
/// <summary> /// The HtmlResponse process is the only process that invokes the workflow post router for final /// processing of the HTML. /// </summary> public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlResponse resp) { proc.ServiceManager.IfExists<IWebWorkflowService>(wws => wws.PostRouter(resp.Context, resp)); byte[] utf8data = resp.Html.to_Utf8(); resp.Context.Response.ContentType = "text/html"; resp.Context.Response.ContentEncoding = Encoding.UTF8; resp.Context.Response.ContentLength64 = utf8data.Length; resp.Context.Response.OutputStream.Write(utf8data, 0, utf8data.Length); resp.Context.Response.Close(); }