Skip to content

Instantly share code, notes, and snippets.

@jstemerdink
Last active August 20, 2016 12:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jstemerdink/12abac6f4ae8a5b7023f81b63c0adc6e to your computer and use it in GitHub Desktop.

Allow the new EPiServer Forms in your WebForms solution pt.2

Read the blog here

Powered by ReSharper image

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FormContainerBlockControl.ascx.cs" Inherits="EPiServerWebForms.Views.Blocks.FormContainerBlockControl" %>
<%@ Import Namespace="EPiServerWebForms.Business.MvcHelpers" %>
<% MvcUtility.RenderPartial("FormsContentArea", this.FakeArea, this.FakeContext); %>
public partial class FormContainerBlockControl : BlockControlBase<FormContainerBlock>
{
private Injected<IEPiServerFormsImplementationConfig> formConfig;
private Injected<LocalizationService> localizationService;
private Injected<IRequiredClientResourceList> requiredClientResourceList;
private Injected<VisitorIdentifyService> visitorIdentifyService;
protected ContentArea FakeArea { get; private set; }
protected ControllerContext FakeContext { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
this.FakeContext = MvcUtility.GetFormControllerContext();
this.SetResources(this.FakeContext);
// this.Page.Form.ID = this.CurrentBlock.Form.FormGuid.ToString();
if (!PageEditing.PageIsInEditMode)
{
try
{
GhostForm form = this.Page.Form as GhostForm;
if (form != null)
{
form.RenderFormTag = false;
}
}
catch (InvalidOperationException)
{
}
}
ContentArea contentArea = new ContentArea();
contentArea.Items.Add(new ContentAreaItem { ContentLink = this.CurrentBlock.Content.ContentLink });
this.FakeArea = contentArea;
this.DataBind();
}
protected void Page_PreRender(object sender, EventArgs e)
{
this.SetVisitorIdentifierIfNeeded(this.FakeContext.HttpContext);
}
/// <summary>
/// Serialize some localized text messages to clientside context
/// </summary>
/// <returns></returns>
private string GetCommonMessages()
{
var data =
new
{
viewMode =
new
{
malformStepConfiguration =
this.localizationService.Service.GetString(
"/episerver/forms/viewmode/malformstepconfigruation"),
commonValidationFail =
this.localizationService.Service.GetString(
"/episerver/forms/viewmode/commonvalidationfail")
},
fileUpload =
new
{
overFileSize =
this.localizationService.Service.GetString(
"/episerver/forms/messages/fileupload/overFileSize"),
invalidFileType =
this.localizationService.Service.GetString(
"/episerver/forms/messages/fileupload/invalidfiletype"),
postedFile =
this.localizationService.Service.GetString(
"/episerver/forms/messages/fileupload/postedfile")
}
};
return data.ToJson();
}
/// <summary>
/// Gets external resources (script, css) for the given Form container object
/// </summary>
private void GetFormExternalResources(out List<string> scripts, out List<string> css)
{
scripts = new List<string>();
css = new List<string>();
List<IViewModeExternalResources> allInstances =
ServiceLocator.Current.GetAllInstances<IViewModeExternalResources>().ToList();
if (!allInstances.Any())
{
return;
}
foreach (IViewModeExternalResources externalResources in allInstances.Where(r => r.Resources != null))
{
scripts.AddRange(
externalResources.Resources.Where(t => "script".Equals(t.Item1, StringComparison.OrdinalIgnoreCase))
.Select(t => t.Item2));
css.AddRange(
externalResources.Resources.Where(t => "css".Equals(t.Item1, StringComparison.OrdinalIgnoreCase))
.Select(t => t.Item2));
}
}
/// <summary>
/// Sets the resources.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
private void SetResources(ControllerContext controllerContext)
{
ContextMode contextMode = controllerContext.RequestContext.GetContextMode();
bool flag1 = (contextMode == ContextMode.Default) || (contextMode == ContextMode.Preview);
if (flag1)
{
if (this.formConfig.Service.InjectFormOwnStylesheet)
{
string webResourceUrl = ModuleHelper.GetWebResourceUrl(
typeof(FormContainerBlockController),
"EPiServer.Forms.ClientResources.ViewMode.EPiServerForms.css");
this.requiredClientResourceList.Service.Require(
new ClientResource
{
Name = "EPiServerForms.css",
Dependencies = new List<string> { "EPiServerForms_prerequisite.js" },
ResourceType = ClientResourceType.Html,
InlineContent =
"<link rel='stylesheet' type='text/css' data-epiforms-resource='EPiServerForms.css' href='"
+ webResourceUrl + "' />"
}).AtHeader();
}
if (!this.formConfig.Service.WorkInNonJSMode)
{
string scriptContent1 =
"var epi = epi||{}; epi.EPiServer = epi.EPiServer||{}; epi.EPiServer.Forms = epi.EPiServer.Forms||{};\nepi.EPiServer.Forms.InjectFormOwnJQuery = "
+ this.formConfig.Service.InjectFormOwnJQuery.ToString().ToLowerInvariant()
+ ";epi.EPiServer.Forms.OriginalJQuery = typeof jQuery !== 'undefined' ? jQuery : undefined;";
this.requiredClientResourceList.Service.RequireScriptInline(
scriptContent1,
"EPiServerForms_saveOriginalJQuery.js",
new List<string>()).AtHeader();
if (this.formConfig.Service.InjectFormOwnJQuery)
{
this.requiredClientResourceList.Service.RequireScript(
ModuleHelper.GetWebResourceUrl(
typeof(FormContainerBlockController),
"EPiServer.Forms.ClientResources.ViewMode.jquery-1.12.4.min.js"),
"Forms.jquery.js",
new List<string> { "EPiServerForms_saveOriginalJQuery.js" }).AtHeader();
}
string webResourceContent = ModuleHelper.GetWebResourceContent(
typeof(FormContainerBlockController),
"EPiServer.Forms.ClientResources.ViewMode.EPiServerForms_prerequisite.js");
List<string> scripts;
List<string> css;
this.GetFormExternalResources(out scripts, out css);
string scriptContent2 =
webResourceContent.Replace(
"___CurrentPageLink___",
FormsExtensions.GetCurrentPageLink().ToString())
.Replace("___CurrentPageLanguage___", FormsExtensions.GetCurrentPageLanguage())
.Replace("___ExternalScriptSources___", scripts.ToJson())
.Replace("___ExternalCssSources___", css.ToJson())
.Replace(
"___UploadExtensionBlackList___",
this.formConfig.Service.DefaultUploadExtensionBlackList)
.Replace("___Messages___", this.GetCommonMessages())
.Replace("___LocalizedResources___", FormsExtensions.GetLocalizedResources().ToJson());
this.requiredClientResourceList.Service.RequireScriptInline(
scriptContent2,
"EPiServerForms_prerequisite.js",
new List<string> { "Forms.jquery.js" }).AtHeader();
string resourceName = EPiServerFrameworkSection.Instance.ClientResources.Debug
? "EPiServer.Forms.ClientResources.ViewMode.EPiServerForms.js"
: "EPiServer.Forms.ClientResources.ViewMode.EPiServerForms.min.js";
this.requiredClientResourceList.Service.RequireScript(
ModuleHelper.GetWebResourceUrl(typeof(FormContainerBlockController), resourceName),
"EPiServerForms.js",
new List<string> { "Forms.jquery.js", "EPiServerForms_prerequisite.js" }).AtFooter();
}
}
}
/// <summary>
/// Check if Visitor is identified. If not, build the identifier and set to the Cookie.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
private void SetVisitorIdentifierIfNeeded(HttpContextBase httpContext)
{
IVisitorIdentifyProvider identifyProvider =
this.visitorIdentifyService.Service.GetVisitorIdentifyProvider(httpContext);
if (!string.IsNullOrWhiteSpace(identifyProvider.GetVisitorIdentifier()))
{
return;
}
identifyProvider.SetVisitorIdentifier(null);
}
}
@using EPiServer.Core
@model ContentArea
@Html.DisplayForModel()
public class GhostForm : HtmlForm
{
protected bool render;
public bool RenderFormTag
{
get { return this.render; }
set { this.render = value; }
}
public GhostForm()
{
//By default, show the form tag
this.render = true;
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
//Only render the tag when render is set to true
if (this.render)
{
base.RenderBeginTag(writer);
}
}
protected override void RenderEndTag(HtmlTextWriter writer)
{
//Only render the tag when render is set to true
if (this.render)
{
base.RenderEndTag(writer);
}
}
}
public static class MvcUtility
{
private static readonly ILogger Log = LogManager.GetLogger();
public static ControllerContext GetFormControllerContext()
{
try
{
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "FormContainerBlock");
routeData.Values.Add("action", "Index");
return new ControllerContext(new RequestContext(httpContextBase, routeData), new FormContainerBlockController());
}
catch (ArgumentNullException argumentNullException)
{
Log.Critical("Cannot create controllercontext for the FormContainerBlock: \r\n {0}", argumentNullException);
}
return null;
}
public static void RenderPartial(string partialViewName, object model, ControllerContext controllerContext)
{
if (model == null)
{
return;
}
try
{
IView view = FindPartialView(controllerContext, partialViewName);
ViewContext viewContext = new ViewContext(
controllerContext,
view,
new ViewDataDictionary { Model = model },
new TempDataDictionary(),
controllerContext.RequestContext.HttpContext.Response.Output);
view.Render(viewContext, controllerContext.RequestContext.HttpContext.Response.Output);
}
catch (InvalidOperationException invalidOperationException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, invalidOperationException);
}
catch (NotImplementedException notImplementedException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, notImplementedException);
}
catch (ArgumentNullException argumentNullException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, argumentNullException);
}
}
// Render a partial view
public static void RenderPartial(string partialViewName, object model)
{
if (model == null)
{
return;
}
try
{
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
RouteData routeData = new RouteData();
//routeData.Values.Add("controller", "Dummy");
routeData.Values.Add("controller", "FormContainerBlock");
routeData.Values.Add("action", "Index");
//ControllerContext controllerContext = new ControllerContext(new RequestContext(httpContextBase, routeData), new DummyController());
ControllerContext controllerContext = new ControllerContext(new RequestContext(httpContextBase, routeData), new FormContainerBlockController());
IView view = FindPartialView(controllerContext, partialViewName);
ViewContext viewContext = new ViewContext(
controllerContext,
view,
new ViewDataDictionary { Model = model },
new TempDataDictionary(),
httpContextBase.Response.Output);
view.Render(viewContext, httpContextBase.Response.Output);
}
catch (InvalidOperationException invalidOperationException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, invalidOperationException);
}
catch (NotImplementedException notImplementedException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, notImplementedException);
}
catch (ArgumentNullException argumentNullException)
{
Log.Critical("Cannot render partial view for: {0} \r\n {1}", partialViewName, argumentNullException);
}
}
// Find the view, if not throw an exception
private static IView FindPartialView(ControllerContext controllerContext, string partialViewName)
{
ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);
if (result.View != null)
{
return result.View;
}
StringBuilder locationsText = new StringBuilder();
foreach (string location in result.SearchedLocations)
{
locationsText.AppendLine();
locationsText.Append(location);
}
throw new InvalidOperationException(
string.Format("Partial view {0} not found. Locations Searched: {1}", partialViewName, locationsText));
}
}
<%@ Master Language="C#" AutoEventWireup="false" CodeBehind="Root.master.cs" Inherits="EPiServerWebForms.Views.MasterPages.Root" %>
<%@ Import Namespace="System.Web.Optimization" %>
<!DOCTYPE html>
<html lang="<%= CurrentPage.LanguageBranch %>">
<head runat="server">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%: CurrentPage.MetaTitle %></title>
<EPiServer:CanonicalLink runat="server" />
<EPiServer:AlternateLinks runat="server" />
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/js") %>
<%: Styles.Render("~/bundles/css") %>
</asp:PlaceHolder>
<EPiServer:RequiredClientResources RenderingArea="Header" ID="RequiredResourcesHeader" runat="server" />
</head>
<body>
<%--<form runat="server" enctype="multipart/form-data" class="EPiServerForms " data-epiforms-type="form" ClientIDMode="Static">--%>
<Alloy:GhostForm runat="server">
<%--<form runat="server">--%>
<EPiServer:FullRefreshPropertiesMetaData runat="server" />
<div class="container">
<asp:ContentPlaceHolder ID="Content" runat="server" />
</div>
<%--</form>--%>
</Alloy:GhostForm>
<EPiServer:RequiredClientResources RenderingArea="Footer" ID="RequiredResourcesFooter" runat="server" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment