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

Signing in Nintex Mobile: Authentication

Authentication Nintex Mobile supports three ways of authentication. ·          Corporate Account : Choose this method when we want to connect directly to your on-premises SharePoint instance. ·          Microsoft Account :  Choose this method when we SharePoint server is not available on the internet and you are using Nintex Live as a gateway between the Nintex Mobile apps and your on-premises intranet.  ·          Office 365 Account: Choose this method when we want to connect the Nintex Mobile apps to your Office 365 tenancy running Nintex Forms for Office 365. Signing in with a Corporate Account A Corporate account is used when connecting directly to your SharePoint environment over a Your VPN, If associate know the URL of your SharePoint server, and associate have a secure connection to it, we may want to use your corporate accou...

Business-critical processes with SharePoint and SQL

SharePoint 2010 provides the ability to connect to backend business systems, surface business data in SharePoint and make it accessible by, and useful to, employees across the organization. Almost every company of significant size uses ERP and CRM solutions to run core business processes. Over time, companies have developed detailed practices around using such systems to support vertical disciplines within the organization (e.g. product planning, financial performance management, supply-chain management, etc.),  yet challenges remain with regard to driving visibility and collaboration, based on business data, across different disciplines and teams. These challenges stem from the fact that only a fraction of employees are licensed and trained to use those backend systems, and from the high cost and complexity of integrating such systems across different functions and teams. With SharePoint and SQL, once the relevant business data is surfaced in an enterprise-wide...

Powershell Script to Restrict Group Creation on Office 365

$GroupName = "<SecurityGroupName>" $AllowGroupCreation = "False" Connect-AzureAD $settingsObjectID = (Get-AzureADDirectorySetting | Where-object -Property Displayname -Value "Group.Unified" -EQ).id if(!$settingsObjectID) { $template = Get-AzureADDirectorySettingTemplate | Where-object {$_.displayname -eq "group.unified"}     $settingsCopy = $template.CreateDirectorySetting()     New-AzureADDirectorySetting -DirectorySetting $settingsCopy     $settingsObjectID = (Get-AzureADDirectorySetting | Where-object -Property Displayname -Value "Group.Unified" -EQ).id } $settingsCopy = Get-AzureADDirectorySetting -Id $settingsObjectID $settingsCopy["EnableGroupCreation"] = $AllowGroupCreation if($GroupName) { $settingsCopy["GroupCreationAllowedGroupId"] = (Get-AzureADGroup -SearchString $GroupName).objectid }  else { $settingsCopy["GroupCreationAllowedGroupId"] = $GroupName } Set-AzureADDirectorySetting -Id $...