SharePoint 2013 custom master page with code behind

Sometime we need to set control value dynamically on our custom master page in SharePoint. The one way is to write custom JavaScript code using Client Side Object Model (CSOM) and we can add that JavaScript on master page.  The other way to create custom class file and attach that file with master page.

Follow below steps to create master page with code behind in SharePoint Project.

1) Create module file in SharePoint solution. I have given module name as CustomMasterPage.

1

2) Rename the sample.txt with “MyCustomMaster.master”. Add your master page content in “MyCustomMaster.master” file.

3) Now click on module(CustomMasterPage) and add new class file. My class file name is “CustomCode.cs”

2

4)Inherit that class from publishingpagelayout class.

public partial class CustomCode : PublishingLayoutPage
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnHomePageOk_Click(object sender, EventArgs e)
{

}
}

5)Open the master page and add following line at the top.
<%@Master language=”C#” Inherits=”TestProject.Branding.MasterPages.CustomMasterPage.MyCustom,TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ca7bafa503889ee6″ %>

In above line give change namespace as per your need with master page reference, change assembly name as per your need and give public key token.

Create Site Column, Content Type for multilingual site in SharePoint 2013

To create site column, content type and page layout for multilingual site first we have add resource file in our SharePoint project. The basic mechanism of localizing a SharePoint 2013 feature is same as we have in SharePoint 2010 and in Moss 2007.

Resource File

To deploy resource file to 15 hives, first we have to map project with the SharePoint Resource folder. Select your project – >Add->SharePoint Mapped Folder

b2

 

Select resource folder. Now right click on the mapped folder and select add new item and add resource file. I have added resource file for German and English. In resource file name you have to specify language code. Refer below image.

b1

Add your localize string in resource file. You will need to set the Build Action in the resx property to ‘Content’ otherwise a deployment to hive won’t take place. Below is my resource file.

b3

Form feature property set the Default Resource File to the resource file name and also set “Require Resource” to TRUE.

Site Column

To add site column select your project, add new item and select site column. Open Element.xml file of site column.

<Elementsxmlns=”http://schemas.microsoft.com/sharepoint/”>

<Field

ID=”{37e7b0d2-f12d-4204-a652-97fdf4b034e6}”

Name=”EventName”

DisplayName=”$Resources:EventName”

Type=”Text”

Required=”FALSE”

Group=”Events”>

</Field>

</Elements>

 

Now you have to set display name of site column from resource file name. Instead of “EventName” you have to change your name from resource file. By doing so display name is different for English and German site. Name is internal name of site column field. If you want to access site column from code behind than you have to use internal name of site column.

Content Type

To add content type selects your project, add new content type and select base content type. Open Element.xml file of

 

<ContentTypeID=”0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00D6DCE36F9DE043FE925DBA1E365BB75B”

Name=”$Resources:EventType”

Group=”Events”

Description=”$Resources:EventTypeDescription”

Inherits=”TRUE”

Version=”0″>

<FieldRefs>

<FieldRefID=”{37e7b0d2-f12d-4204-a652-97fdf4b034e6}”

Required=”FALSE”Name=”EventName” />

</FieldRefs>

</ContentType>

 

Set content type name from resource file. For content type we do not have display name property. We cannot set internal name for content type. If you want to access content type from code behind than you have to access with content type id.

 

Below is reference link for resource file

http://cann0nf0dder.wordpress.com/2013/05/16/resource-files-within-sharepoint-2010/

http://msreddysharepoint.blogspot.com/2013/01/resource-files-in-sharepoint-2010-and.html

Create List for multilingual site in SharePoint 2013

In our previous blog we have seen that how to create site column, content type for multilingual site. Now we will create custom list for all multilingual site with different name on feature activation.

 

try
{
    using (SPSite site = new SPSite(RootSiteUrl))
    {
        SPWebCollection allWebs = site.AllWebs;
        foreach (SPWeb currentWeb in allWebs)
        {
           if (PublishingWeb.IsPublishingWeb(currentWeb))
           {
               using (currentWeb)
               {
                 CreateListInstance(currentWeb.Url, "$Resources:EventNotification,EventListName", "", true, true);
               }
           }
         }
    }
}
catch (Exception ex)
{
     Logger.LogError(ex.Message, "List Error", ex.StackTrace);
}

Here the SPWeb object will give all multilingual site and sub site object. The above code will create list in all sub sites. If you want to avoid any sub site then you can specify that sub site name in if condition.

In the above code “EventNotification” is the name of the resource file and “EventListName” is the name attribute of resource file. It will get the value of “EventListName” from the resource file and create list with that name. In the above code CreateListInstance is the method to creates list which is below.

 

private void CreateListInstance(string absoluteSiteUrl, string dispalyNameFromResx, string description, bool allowContentType, bool allowVersioning)
{
     SPList list = null;
     try
     {
                SPSecurity.RunWithElevatedPrivileges(() =>
                 {
                     using (SPSite site = new SPSite(absoluteSiteUrl))
                     {
                         using (SPWeb web = site.OpenWeb())
                         {
                             if (web.Lists.TryGetList(dispalyNameFromResx) == null)
                             {
                                 Guid listId = web.Lists.Add(dispalyNameFromResx, description, SPListTemplateType.GenericList);
                                 list = web.Lists[listId];
                                 list.EnableVersioning = allowVersioning;
                                 list.ContentTypesEnabled = allowContentType;
                                 list.EnableModeration = false;
                                 list.Update();
                             }
                         }
                     }
                 });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message, "List create error", ex.StackTrace);
            }
}

 

Accessing resource file value in JavaScript in Multilingual site in SharePoint 2013

Writing server side code to get resource file value in JavaScript is the easy way and most people using server side code to get resource file value. But when there is a requirement to write advanced JavaScript based development and to get resource file value in the JavaScript file (.js) at that time we need to write the JavaScript code. Below is the JavaScript code to get resource file value.

Resource File Image:

b3

 Javascript Code:

$(document).ready(function () {

    var eventName = "";

    //load the authoring resource file depending on the current language
    function loadResourceJs() {
        currentUiCluture = STSHtmlEncode(Strings.STS.L_CurrentUICulture_Name);
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getResourceVal);
    }

    //get resource strings from ‘EventNotification’ resource file depending on the current language
    function getResourceVal() {
        var resourceUrl = '/_layouts/15/ScriptResx.ashx?culture=' + currentUiCluture + '&name=EventNotification;

        $.getScript(resourceUrl, function () {
            eventName = Res['eventName'];
        });
    }

    SP.SOD.executeOrDelayUntilScriptLoaded(loadResourceJs, 'core.js');
});

 

The resource file should be deployed in the 15 hive and resource file should be language specific resource file. Here Culture is the locale language for the resource file. If the language is de-de then it will get the value from German resource file and if the language is en-us then it will get the value from English resource file.