Tuesday, March 7, 2017

Provision and automatic update of embedded resources to App_LocalResources folder under Sharepoint Template/Layouts or Template/ControlTemplates sub folders

In one of my previous posts I showed how to include embedded provision resources (located in {SharepointRoot}\Resources) to wsp package so they will be provisioned and updated automatically (see Provision and automatic update of embedded resources to Resources folder in Sharepoint hive). However on practice we also often add UI resources specific to concrete application layouts page (page located under Template/Layouts subfolder) or user control (under Template/ControlTemplates). E.g. if we have a page /Template/Layouts/Test/foo.aspx then UI resource will be located in /Template/Layouts/Test/App_LocalResources/foo.aspx.resx. Note that it has the same name as parent page plus .resx extension. In this case we can use the following declarative syntax in foo.aspx layout:

   1: <asp:Literal Text="<%$Resources:Test%>" runat="server" />

and ASP.Net will automatically get resource string with key Test from foo.aspx.resx file.

This approach simplifies localization of UI components in Sharepoint. The problem is that if we add our resource file as Content to Visual Studio project it will be added to result manifest.xml of wsp package during publishing. However if we will change it’s type to Embedded resource it won’t be added (which is needed if we want to use resource strings also from C# code), i.e. in this case we will need to update it manually (i.e. behavior is the same as for root resources described in the article mentioned above).

In order to fix this issue, i.e. in order to force Visual Studio to add embedded resx file from App_LocalResources folder to wsp package we will use the same approach described in Provision and automatic update of embedded resources to Resources folder in Sharepoint hive. But syntax of SharePointProjectItem.spdata file will be different. In case of local UI resources it will look like this:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <ProjectItem Type="Microsoft.VisualStudio.SharePoint.GenericElement"
   3: SupportedTrustLevels="All"
   4: SupportedDeploymentScopes="Web, Site, WebApplication, Farm, Package"
   5: xmlns="http://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel">
   6:   <Files>
   7:     <ProjectItemFile Source="..\..\..\Layouts\Test\App_LocalResources\foo.aspx.resx"
   8:         Target="Layouts\Test\App_LocalResources" Type="TemplateFile" />
   9:   </Files>
  10: </ProjectItem>

After that if you will publish wsp package reference on embedded resource will be added there:

   1: <TemplateFiles>
   2:     ...
   3:     <TemplateFile Location="Layouts\Test\App_LocalResources\foo.aspx.resx" />
   4: </TemplateFiles>

I.e. we will have all embedded resources provisioned automatically.

No comments:

Post a Comment