Skip to main content

Build and Deploy a custom theme in SharePoint 2019: Using C# and Site features

Custom Theme and Branding are common to use cases and all kinds of business users like to have the personalized team and collaboration sites. today I am posting C# code that will help to build custom features for SharePoint 2019 site.  

If need any assistance, I would be happy to help: kamal_pandey@outlook.com 

-----------------------------Code to build custom features----------

using System;

using System.Collections.Generic;

using System.Globalization;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Utilities;


namespace SharePointBranding.Code

{

    public class BrandingManager

    {

        public SPWeb Web { get; set; }


        public BrandingManager(SPWeb web)

        {

            Web = web;

        }


        public void SetMasterPage(string masterPageUrl, string logoUrl)

        {

            masterPageUrl = GetMasterPageServerRelativeUrl(masterPageUrl);

            Web.MasterUrl = masterPageUrl;

            //Web.CustomMasterUrl = masterPageUrl;

            //Web.SiteLogoUrl = logoUrl;

            //Web.Update();

        }


        private string GetMasterPageServerRelativeUrl(string masterPageUrl)

        {

            return masterPageUrl.StartsWith("/") ? masterPageUrl : SPUrlUtility.CombineUrl(Web.ServerRelativeUrl, masterPageUrl);

        }


        public void InstallThemes(IEnumerable<string> themeNames, string masterUrl)

        {

            masterUrl = GetMasterPageServerRelativeUrl(masterUrl);

            var designCatalog = Web.GetCatalog(SPListTemplateType.DesignCatalog);



            //usually sharepoint default themes display order starts with 10 and then incremented by 10. So they are 10,20,30 and so on

            var displayOrderCounter = 1000;


            foreach (var themeName in themeNames)

            {


                var themeTitle = themeName.Replace(".spcolor", "");

                var themeItem = designCatalog.AddItem();

                themeItem["Name"] = themeTitle;

                themeItem["Title"] = themeTitle;

                themeItem["MasterPageUrl"] = new SPFieldUrlValue(masterUrl); //the master page should have a 'preview' file associated

                themeItem["ThemeUrl"] = new SPFieldUrlValue(Web.Site.ServerRelativeUrl.TrimEnd('/') + "/_catalogs/theme/15/" + themeName);

                themeItem["DisplayOrder"] = displayOrderCounter;

                themeItem.Update();

                displayOrderCounter += 10;

            }


        }


        public void ApplyTheme(SPTheme theme)

        {

            theme.ApplyTo(Web, false);

            Web.Update();



            SetCurrentTheme(theme.Name);

        }

        private void SetCurrentTheme(string name)

        {

            var designCatalog = Web.GetCatalog(SPListTemplateType.DesignCatalog);

            name = name.Replace(".spcolor", "");


            //get Current list item

            var query = new SPQuery();

            query.Query = "<Where><Eq><FieldRef Name='Name'/><Value Type='Text'>Current</Value></Eq></Where>";

            query.RowLimit = 1;

            var items = designCatalog.GetItems(query);


            if (items != null && items.Count == 1)

            {

                //get newly apply theme item

                var query2 = new SPQuery();

                query2.Query = string.Format("<Where><Eq><FieldRef Name='Name'/><Value Type='Text'>{0}</Value></Eq></Where>", name);

                query2.RowLimit = 1;

                var items2 = designCatalog.GetItems(query2);


                if (items2 != null && items2.Count == 1)

                {

                    items[0].Delete();


                    SPListItem newCurrentItem = designCatalog.AddItem();

                    newCurrentItem["Title"] = SPResource.GetString(CultureInfo.CurrentUICulture, Strings.DesignGalleryCurrentItemName);

                    newCurrentItem["Name"] = SPResource.GetString(CultureInfo.CurrentUICulture, Strings.DesignGalleryCurrentItemName);

                    newCurrentItem["MasterPageUrl"] = items2[0]["MasterPageUrl"];

                    newCurrentItem["ThemeUrl"] = items2[0]["ThemeUrl"];

                    newCurrentItem["ImageUrl"] = items2[0]["ImageUrl"];

                    newCurrentItem["FontSchemeUrl"] = items2[0]["FontSchemeUrl"];

                    newCurrentItem["DisplayOrder"] = 0;

                    newCurrentItem.Update();

                }

            }

        }


        public void UnInstallThemes(List<string> themes)

        {

            var designCatalog = Web.GetCatalog(SPListTemplateType.DesignCatalog);


            foreach (var theme in themes)

            {

                var themeName = theme.Replace(".spcolor", "");

                var query = new SPQuery();

                query.Query = string.Format("<Where><Eq><FieldRef Name='Name'/><Value Type='Text'>{0}</Value></Eq></Where>", themeName);


                var itemsToDelete = new List<int>();

                var items = designCatalog.GetItems(query);

                foreach (SPListItem item in items)

                {

                    itemsToDelete.Add(item.ID);

                }


                foreach (var itemId in itemsToDelete)

                {

                    designCatalog.GetItemById(itemId).Delete();

                }

            }

        }

Comments

Popular posts from this blog

PowerShell For create Sub site in office 365

#Add references to SharePoint client assemblies and authenticate to Office 365 site Add-Type -Path "\Software\SharePoint 2013 Client Browser v1.7\Microsoft.SharePoint.Client.dll" Add-Type -Path "\Software\SharePoint 2013 Client Browser v1.7\Microsoft.SharePoint.Client.Runtime.dll" $Username = Read-Host -Prompt "Please enter your username" $Password = Read-Host -Prompt "Please enter your password" -AsSecureString $Site = "https://XXXXXXX.sharepoint.com/sites/Test2/" $Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site) $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password) $Context.Credentials = $Creds $csvLocation = "C:\Users\PS_SiteCollectionsToCreate.csv" $csv = Import-Csv $csvLocation #List Custom Templates $Templates = $Context.Site.GetWebTemplates("1033","0") $Context.Load($Templates) $Context.ExecuteQuery() $Templates | Whe...