Commit cfa3d12c authored by Viet Hoang's avatar Viet Hoang

Merge branch 'handle-errors-of-a-specific-site' into 'develop'

Handle errors of a specific site

See merge request viet.hoang/vhs!21
parents a6f5da04 c0efb1a4
......@@ -5,4 +5,5 @@ For more information, please visit the blogs:
* [Media Provider For Graysale](https://buoctrenmay.wordpress.com/2017/05/24/how-to-enable-grayscale-feature-on-sitecore-xp-8/)
* [Pre-population Item Version](https://buoctrenmay.wordpress.com/2017/05/27/pre-population-item-version-module-for-sitecore-development/)
* [How to inject the custom icons to Sitecore 8](https://buoctrenmay.wordpress.com/2017/06/17/how-to-inject-the-custom-icons-to-sitecore-8/)
* [How to get public URL of a media item inside Sitecore](https://buoctrenmay.wordpress.com/2017/07/08/how-to-get-public-url-of-a-media-item-inside-sitecore/)
\ No newline at end of file
* [How to get public URL of a media item inside Sitecore](https://buoctrenmay.wordpress.com/2017/07/08/how-to-get-public-url-of-a-media-item-inside-sitecore/)
* [Report viewer restriction on Sitecore Experience Analytics Dashboard](https://buoctrenmay.wordpress.com/2017/10/06/report-viewer-restriction-on-sitecore-experience-analytics-dashboard/)
\ No newline at end of file
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor patch:before="processor[@type='Sitecore.Pipelines.HttpRequest.ExecuteRequest, Sitecore.Kernel']"
type="Vhs.HandleErrorProcessors.Pipelines.HttpRequestBegin.HandleItemNotFound, Vhs.HandleErrorProcessors">
<RelativeUrlPrefixesToIgnore hint="list">
<Prefix>/~/</Prefix>
<Prefix>/-/</Prefix>
</RelativeUrlPrefixesToIgnore>
</processor>
</httpRequestBegin>
<mvc.exception>
<processor patch:before="*[@type='Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage, Sitecore.Mvc']"
type="Vhs.HandleErrorProcessors.Pipelines.MvcException.HandleMvcException, Vhs.HandleErrorProcessors" />
</mvc.exception>
</pipelines>
</sitecore>
</configuration>
\ No newline at end of file
namespace Vhs.HandleErrorProcessors
{
public struct Constants
{
public struct SiteInfo
{
public struct Properties
{
public static string EnableHandleCustomErrors = "enableHandleCustomErrors";
public static string NotFoundItem = "notFoundItem";
public static string FallbackNotFoundItem = "fallbackNotFoundItem";
public static string CustomErrorFile = "customErrorFile";
}
}
}
}
\ No newline at end of file
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Links;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using Vhs.HandleErrorProcessors.Services;
namespace Vhs.HandleErrorProcessors.Pipelines.HttpRequestBegin
{
public class HandleItemNotFound : HttpRequestProcessor
{
public List<string> RelativeUrlPrefixesToIgnore { get; set; }
public HandleItemNotFound()
{
RelativeUrlPrefixesToIgnore = new List<string>();
}
public override void Process(HttpRequestArgs args)
{
var enableHandleCustomErrors = MainUtil.GetBool(Context.Site.Properties[Constants.SiteInfo.Properties.EnableHandleCustomErrors], false);
if (!enableHandleCustomErrors)
{
return;
}
if (Context.Item != null || StartsWithPrefixToIgnore(args.Url.FilePath))
{
return;
}
var notFoundContent = GetNotFoundPageContent(args);
if (!string.IsNullOrWhiteSpace(notFoundContent))
{
args.Context.Response.TrySkipIisCustomErrors = true;
args.Context.Response.StatusCode = 404;
args.Context.Response.StatusDescription = "Page Not Found";
args.Context.Response.Write(notFoundContent);
args.Context.Response.End();
}
Log.Warn("The not found page: '{0}' shows no content when rendered!", args.Url);
}
protected bool StartsWithPrefixToIgnore(string url)
{
return !string.IsNullOrWhiteSpace(url) && RelativeUrlPrefixesToIgnore.Any(prefix => url.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
}
protected string GetNotFoundPageContent(HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
var domain = GetDomain(args);
var notFoundItem = NotFoundItemService.GetItemBySiteProperty(Context.Site, Constants.SiteInfo.Properties.NotFoundItem);
var url = notFoundItem != null ? LinkManager.GetItemUrl(notFoundItem) : NotFoundItemService.GetRelativeFilePathBySiteProperty(Context.Site, Constants.SiteInfo.Properties.FallbackNotFoundItem);
if (string.IsNullOrWhiteSpace(url))
{
return string.Empty;
}
try
{
var content = WebUtil.ExecuteWebPage(string.Concat(domain, url));
return content;
}
catch (Exception ex)
{
Log.Error($"{ToString()} Error - domain: {domain}, url: {url}", ex, this);
}
return string.Empty;
}
protected string GetDomain(HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
return args.Context.Request.Url?.GetComponents(UriComponents.Scheme | UriComponents.Host, UriFormat.Unescaped);
}
}
}
\ No newline at end of file
using Sitecore.Diagnostics;
using Sitecore.Mvc.Pipelines.MvcEvents.Exception;
using System;
using System.Diagnostics;
using Sitecore;
namespace Vhs.HandleErrorProcessors.Pipelines.MvcException
{
public class HandleMvcException : ExceptionProcessor
{
public override void Process(ExceptionArgs args)
{
try
{
var site = Context.Site;
if (site == null)
{
return;
}
var enableHandleCustomErrors = MainUtil.GetBool(site.Properties[Constants.SiteInfo.Properties.EnableHandleCustomErrors], false);
if (!enableHandleCustomErrors)
{
return;
}
var context = args.ExceptionContext;
var httpContext = context.HttpContext;
var exception = context.Exception;
if (context.ExceptionHandled || httpContext == null || exception == null)
{
return;
}
var errorPageUrl = site.Properties[Constants.SiteInfo.Properties.CustomErrorFile];
if (string.IsNullOrWhiteSpace(errorPageUrl))
{
return;
}
httpContext.Server.ClearError();
httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
httpContext.Server.Execute(errorPageUrl);
}
catch (Exception ex)
{
Log.Error($"{this} {typeof(Process)} : {ex.Message}'", ex, this);
Log.Error($"{this} {typeof(Process)} : {ex.StackTrace}'", ex, this);
}
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Vhs.HandleErrorProcessors")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Vhs.HandleErrorProcessors")]
[assembly: AssemblyCopyright("Copyright © viet.hoang.sitecore@gmail.com 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("75f8ae09-b4e3-44c1-8acf-bc51f9852957")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Sites;
namespace Vhs.HandleErrorProcessors.Services
{
public class NotFoundItemService
{
protected static Item GetItemByShortPath(SiteContext siteContext, string shortPath)
{
shortPath = shortPath.StartsWith("/") ? shortPath.Substring(1) : shortPath;
var fullPath = string.Concat(StringUtil.EnsurePostfix('/', siteContext.StartPath), shortPath);
return siteContext.Database.GetItem(fullPath);
}
public static Item GetItemBySiteProperty(SiteContext siteContext, string propertyKey)
{
var property = siteContext.Properties[propertyKey];
if (string.IsNullOrWhiteSpace(property))
{
return null;
}
if (ID.IsID(property) || property.StartsWith(Sitecore.Constants.ContentPath))
{
return siteContext.Database.GetItem(property);
}
return GetItemByShortPath(siteContext, property);
}
public static string GetRelativeFilePathBySiteProperty(SiteContext siteContext, string propertyKey)
{
var propertyValue = siteContext.Properties[propertyKey];
if (!string.IsNullOrWhiteSpace(propertyValue))
{
var filePath = System.Web.HttpContext.Current.Server.MapPath(propertyValue);
if (System.IO.File.Exists(filePath))
{
return propertyValue;
}
}
return string.Empty;
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F95C59DE-8413-4EA6-A477-63ADC8D3D006}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Vhs.HandleErrorProcessors</RootNamespace>
<AssemblyName>Vhs.HandleErrorProcessors</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<Use64BitIISExpress />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Sitecore.Kernel, Version=10.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Sitecore.Kernel.NoReferences.8.2.170728\lib\NET452\Sitecore.Kernel.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Sitecore.Mvc, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Sitecore.Mvc.NoReferences.8.2.170728\lib\NET452\Sitecore.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.Services" />
<Reference Include="System.EnterpriseServices" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Web.Razor">
<HintPath>..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.Webpages">
<HintPath>..\packages\Microsoft.AspNet.Webpages.3.2.3\lib\net45\System.Web.Webpages.dll</HintPath>
</Reference>
<Reference Include="System.Web.Webpages.Deployment">
<HintPath>..\packages\Microsoft.AspNet.Webpages.3.2.3\lib\net45\System.Web.Webpages.Deployment.dll</HintPath>
</Reference>
<Reference Include="System.Web.Webpages.Razor">
<HintPath>..\packages\Microsoft.AspNet.Webpages.3.2.3\lib\net45\System.Web.Webpages.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.Helpers">
<HintPath>..\packages\Microsoft.AspNet.Webpages.3.2.3\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure">
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc">
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Content Include="App_Config\Include\z.Vhs.HandleErrorProcessors.config">
<SubType>Designer</SubType>
</Content>
<None Include="Properties\PublishProfiles\Local.pubxml" />
<None Include="Web.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="Constants.cs" />
<Compile Include="Pipelines\HttpRequestBegin\HandleItemNotFound.cs" />
<Compile Include="Pipelines\MvcException\HandleMvcException.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\NotFoundItemService.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
<None Include="Web.Release.config">
<DependentUpon>Web.config</DependentUpon>
</None>
</ItemGroup>
<ItemGroup />
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>5911</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:5911/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net46" />
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net46" />
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net46" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net46" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net46" developmentDependency="true" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
<package id="Sitecore.Kernel.NoReferences" version="8.2.170728" targetFramework="net46" developmentDependency="true" />
<package id="Sitecore.Mvc.NoReferences" version="8.2.170728" targetFramework="net46" developmentDependency="true" />
</packages>
\ No newline at end of file
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Vhs.SublayoutRenderingAndHybridPlaceholder.SublayoutRenderingId"
value="{A90C1805-2840-4763-8BA6-E05A8667BC46}" />
</settings>
<pipelines>
<mvc.buildPageDefinition>
<processor type="Vhs.SublayoutRenderingAndHybridPlaceholder.Pipelines.MvcBuildPageDefinition.SublayoutRenderingToMvcProcessor, Vhs.SublayoutRenderingAndHybridPlaceholder"
patch:after="*[@type='Sitecore.Mvc.Pipelines.Response.BuildPageDefinition.ProcessXmlBasedLayoutDefinition, Sitecore.Mvc']" />
</mvc.buildPageDefinition>
</pipelines>
</sitecore>
</configuration>
\ No newline at end of file
namespace Vhs.SublayoutRenderingAndHybridPlaceholder
{
public static class Constants
{
public struct ParameterTemplate
{
public static string SublayoutRenderingPath = "SublayoutRenderingPath";
}
}
}
\ No newline at end of file
using Sitecore.Collections;
using Sitecore.Mvc;
using Sitecore.Mvc.Presentation;
using Sitecore.Web;
using Sitecore.Web.UI.WebControls;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace Vhs.SublayoutRenderingAndHybridPlaceholder.Extensions
{
public static class SublayoutMvcAdapterExtensions
{
public static IHtmlString RenderSitecoreSublayout(this HtmlHelper html, string path)
{
var rendering = html.Sitecore().CurrentRendering;
return html.RenderSitecoreSubLayout(path, rendering.DataSource, rendering.Parameters);
}
public static IHtmlString RenderSitecoreSubLayout(this HtmlHelper html,
string path, string datasource = null, RenderingParameters parameters = null)
{
var page = new Page();
AddSublayoutToPage(page, path, datasource, parameters);
var result = ExecutePage(page);
return html.Raw(result);
}
private static void AddSublayoutToPage(Page page, string path, string datasource,
IEnumerable<KeyValuePair<string, string>> parameters)
{
var dict = new SafeDictionary<string>();
if (parameters != null)
{
parameters.ToList().ForEach(i => dict.Add(i.Key, i.Value));
}
var sublayout = new Sublayout
{
DataSource = datasource,
Path = path,
Parameters = WebUtil.BuildQueryString(dict, true, true)
};
var userControl = page.LoadControl(path) as UserControl;
RecursiveLoadControl(userControl, page);
sublayout.Controls.Add(userControl);
page.Controls.Add(sublayout);
}
public static void RecursiveLoadControl(UserControl userControl, Page page)
{
foreach (var c in userControl.Controls)
{
if (c is Sublayout)
{
var sl = (Sublayout)c;
var control = page.LoadControl(sl.Path) as UserControl;
control.Attributes.Add("sc_parameters", sl.Parameters);
control.Attributes.Add("sc_datasource", string.Empty);
RecursiveLoadControl(control, page);
sl.Controls.Add(control);
}
}
}
public static string RenderControl(Control control)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var writer = new HtmlTextWriter(sw);
control.RenderControl(writer);
return sb.ToString();
}
private static string ExecutePage(IHttpHandler page)
{
var text = new StringWriter();
HttpContext.Current.Server.Execute(page, text, true);
return text.ToString();
}