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...

SharePoint Capacity Management and Sizing Overview

Capacity management   is an ongoing process, because no implementation remains static with regard to content and usage. You need to plan for growth and change, so that your SharePoint Server 2013–based environment can continue to deliver an effective business solution. Capacity Planning  is only one part of the capacity management cycle. It is the initial set of activities that brings the design architect to the point where there is an initial architecture that the architect believes will best serve the SharePoint Server 2013 deployment. The capacity management model includes additional steps to help you validate and tune the initial architecture, and provides a feedback loop for re-planning and optimizing the production environment until it can support design goals with optimal choices of hardware, topology, and configuration. Capacity management versus capacity planning Capacity management extends the concept of capacity planning to express a cyclical appr...

SharePoint Framework extensions to Call Azure Function

In this article, we will talk about prerequisites, how to call Azure Function from SPFX extension, How to Create HHTP function, connect Visual Styuid editor to Azure and publish them, and Set Up CORS on the Azure Function, Create SharePoint Framework Extension, Azure Function, etc. Prerequisites :  Azure Subscriptions   VS code  Spfx Development Env  -   Step by steps details: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-development-environment  Follow the below steps to create Azure Functions in the Azure portal.  Steps by steps guide:  https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient-enterpriseapi    Reference :  https://docs.microsoft.com/en-us/answers/questions/430645/how-to-access-sharepoint-rest-api-in-my-function-a.html Step-1 : Login to Azure Portal (https://portal.azure.com/)   Step-2 : As highlighted below, click on the  + Create a resource, and click on “Comput...