private void ApplyTheme(ClientContext workCTX, string cFilename, string cLocalFile)
        {
            try
            {
                Web ww = workCTX.Web;
                ww.EnsureList("SiteAssets", ListTemplateType.DocumentLibrary, "");
                List lstSiteAssets = ww.Lists.GetByTitle("SiteAssets");
                workCTX.Load(lstSiteAssets);
                workCTX.ExecuteQuery();
                lstSiteAssets.EnsureFile(workCTX, cFilename, cLocalFile);
                string cWebfile = "/SiteAssets/" + cFilename;
                ListItem workItem = lstSiteAssets.GetListItemByFileName(workCTX, cFilename);
                workCTX.Load(workItem, wf => wf.File.ServerRelativeUrl);
                workCTX.ExecuteQuery();
                cWebfile = workItem.File.ServerRelativeUrl;

                ww.ApplyTheme(cWebfile, null, null, true);
                workCTX.ExecuteQuery();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
Exemple #2
0
        public void SetThemeBasedOnName(ClientContext ctx, Web web, Web rootWeb, string themeName)
        {
            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);
            ctx.Load(themeList);
            ctx.ExecuteQuery();

            CamlQuery query = new CamlQuery();
            string camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";
            // Let's update the theme name accordingly
            camlString = string.Format(camlString, themeName);
            query.ViewXml = camlString;
            var found = themeList.GetItems(query);
            ctx.Load(found);
            ctx.ExecuteQuery();
            if (found.Count > 0)
            {
                Microsoft.SharePoint.Client.ListItem themeEntry = found[0];
                //Set the properties for applying custom theme which was jus uplaoded
                string spColorURL = null;
                if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                {
                    spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                }
                string spFontURL = null;
                if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                {
                    spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                }
                string backGroundImage = null;
                if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                {
                    backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                }

                // Set theme for demonstration
                web.ApplyTheme(spColorURL,
                                    spFontURL,
                                    backGroundImage,
                                    false);

                // Let's also update master page, if needed
                if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                {
                    web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url); ;
                }

                ctx.ExecuteQuery();
            }
        }
Exemple #3
0
 public void ApplyTheme(string colorPaletteUrl, string fontSchemeUrl, string backgroundImageUrl, bool shareGenerated)
 {
     if (string.IsNullOrEmpty(fontSchemeUrl))
     {
         fontSchemeUrl = null;
     }
     if (string.IsNullOrEmpty(backgroundImageUrl))
     {
         backgroundImageUrl = null;
     }
     _web.ApplyTheme(colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated);
     _web.Context.ExecuteQuery();
 }
        protected void Create_Click(object sender, EventArgs e)
        {
            // Let's first create the site collection using impersonation
            SiteManager.SiteManagerClient managerClient = GetSiteManagerClient();
            SiteManager.SiteData          newSite       = new SiteManager.SiteData()
            {
                Description           = txtDescription.Text,
                LcId                  = "1033",
                OwnerLogin            = txtAdminPrimary.Text,
                SecondaryContactLogin = txtAdminSecondary.Text,
                Title                 = txtTitle.Text,
                Url         = string.Format("sites/" + txtUrl.Text),
                WebTemplate = listSites.SelectedValue
            };
            // Create the site collection by calling the WCF end point in SP farm. Starting from April CU (2014), this is supported also with CSOM
            string newSiteUrl = managerClient.CreateSiteCollection(newSite);

            // Let's also set the site regiional settings to en-UK using the WCF end point, since this is not exposed usign CSOM
            managerClient.SetSiteLocale(newSiteUrl, "fi-fi");

            // Let's also brand the just created site collection properly using app identity
            // Using app identity, since we don't know if the requestor account has permissions to just created site collection
            Uri    targetSite = new Uri(newSiteUrl);
            string realm      = TokenHelper.GetRealmFromTargetUrl(targetSite);
            var    token      = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetSite.Authority, realm).AccessToken;

            using (var ctx = TokenHelper.GetClientContextWithAccessToken(targetSite.ToString(), token))
            {
                // Deploy theme to web, so that we can set that for the site
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                DeployThemeToWeb(ctx, web);

                //Set the properties for applying custom theme which was jus uplaoded
                string spColorURL      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spcolor");
                string spFontURL       = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spfont");
                string backGroundImage = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contosobg.jpg");

                // Use the Red theme for demonstration
                web.ApplyTheme(spColorURL,
                               spFontURL,
                               backGroundImage,
                               false);
                ctx.ExecuteQuery();

                // Redirect to just created site
                Response.Redirect(newSiteUrl);
            }
        }
        private static void ApplyTheme(ClientContext clientContext)
        {
            Web currentWeb = clientContext.Web;

            clientContext.Load(currentWeb);
            clientContext.ExecuteQuery();

            //Apply Sketch theme
            currentWeb.ApplyTheme(
                URLCombine(currentWeb.ServerRelativeUrl, "/_catalogs/theme/15/palette007.spcolor"),
                URLCombine(currentWeb.ServerRelativeUrl, "/_catalogs/theme/15/fontscheme002.spfont"),
                URLCombine(currentWeb.ServerRelativeUrl, "/_layouts/15/images/image_bg007.jpg"),
                false);
            clientContext.ExecuteQuery();
        }
Exemple #6
0
        protected void Create_Click(object sender, EventArgs e)
        {
            // Let's first create the site collection using impersonation
            SiteManager.SiteManagerClient managerClient = GetSiteManagerClient();
            SiteManager.SiteData          newSite       = new SiteManager.SiteData()
            {
                Description           = txtDescription.Text,
                LcId                  = "1033",
                OwnerLogin            = txtAdminPrimary.Text,
                SecondaryContactLogin = txtAdminSecondary.Text,
                Title                 = txtTitle.Text,
                Url         = string.Format("sites/" + txtUrl.Text),
                WebTemplate = listSites.SelectedValue
            };
            // Create the site collection by calling the WCF end point in SP farm
            string url = managerClient.CreateSiteCollection(newSite);

            // Let's also brand the just created site collection properly using app identity
            // Using app identity, since we don't know if the requestor account has permissions to just created site collection
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            // Connect just created site collection and upload the branding in
            using (var ctx = CreateAppOnlyClientContextForUrl(spContext, url))
            {
                // Deploy theme to web, so that we can set that for the site
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                DeployThemeToWeb(ctx, web);

                //Set the properties for applying custom theme which was jus uplaoded
                string spColorURL      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spcolor");
                string spFontURL       = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spfont");
                string backGroundImage = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contosobg.jpg");

                // Use the Red theme for demonstration
                web.ApplyTheme(spColorURL,
                               spFontURL,
                               backGroundImage,
                               false);
                ctx.ExecuteQuery();

                // Redirect to just created site
                Response.Redirect(url);
            }
        }
Exemple #7
0
        protected override async Task OnProvisioningAsync()
        {
            await Web.EnsurePropertyAvailable(w => w.ServerRelativeUrl);

            var backgroundImageUrl = await EnsureServerRelativeOrNull(BackgroundImageUrl);

            var colorPaletteUrl = await EnsureServerRelativeOrNull(ColorPaletteUrl);

            var fontSchemeUrl = await EnsureServerRelativeOrNull(FontSchemeUrl);

            Web.ApplyTheme(
                colorPaletteUrl,
                fontSchemeUrl,
                backgroundImageUrl,
                ShareGenerated
                );

            await ClientContext.ExecuteQueryAsync();
        }
Exemple #8
0
        private void AddComposedLooks(Microsoft.SharePoint.Client.ClientContext context, ShWeb configWeb, Web web, ShComposedLook composedLook)
        {
            if (composedLook != null)
            {
                Log.Debug("Setting Composed Look for web " + configWeb.Name);
                var themeUrl = string.Empty;
                var fontSchemeUrl = string.Empty;

                List themeList = web.GetCatalog(124);
                web.Context.Load(themeList);
                web.Context.ExecuteQuery();

                // We are assuming that the theme exists
                CamlQuery query = new CamlQuery();
                string camlString = @"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                        </Query>
                </View>";
                camlString = string.Format(camlString, composedLook.Name);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                web.Context.Load(found);
                web.Context.ExecuteQuery();

                if (found.Count == 0)
                {
                    if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
                    {
                        context.Load(web);
                        context.ExecuteQuery();
                    }

                    ListItemCreationInformation itemInfo = new ListItemCreationInformation();
                    Microsoft.SharePoint.Client.ListItem item = themeList.AddItem(itemInfo);
                    item["Name"] = composedLook.Name;
                    item["Title"] = composedLook.Title;
                    if (!string.IsNullOrEmpty(composedLook.ThemeUrl))
                    {
                        themeUrl = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", System.IO.Path.GetFileName(composedLook.ThemeUrl)));
                        item["ThemeUrl"] = themeUrl;
                    }
                    if (!string.IsNullOrEmpty(composedLook.FontSchemeUrl))
                    {
                        fontSchemeUrl = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", System.IO.Path.GetFileName(composedLook.FontSchemeUrl)));
                        item["FontSchemeUrl"] = fontSchemeUrl;
                    }
                    if (string.IsNullOrEmpty(composedLook.MasterPageUrl))
                    {
                        item["MasterPageUrl"] = Url.Combine(web.ServerRelativeUrl, "/_catalogs/masterpage/seattle.master");
                    }
                    else
                    {
                        item["MasterPageUrl"] = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/masterpage/{0}", Path.GetFileName(composedLook.MasterPageUrl)));
                    }
                    item["DisplayOrder"] = 11;
                    item.Update();
                    context.ExecuteQuery();
                }
                else
                {
                    Microsoft.SharePoint.Client.ListItem item = found[0];
                    themeUrl = MakeAsRelativeUrl((item["ThemeUrl"] as FieldUrlValue).Url);
                    fontSchemeUrl = MakeAsRelativeUrl((item["FontSchemeUrl"] as FieldUrlValue).Url);
                }

                web.ApplyTheme(themeUrl, fontSchemeUrl, null, false);
                context.ExecuteQuery();
            }
        }
Exemple #9
0
        private static void SetThemeToWebImplementation(this Web web, Web rootWeb, string themeName)
        {
            if (rootWeb == null)
            {
                throw new ArgumentNullException("rootWeb");
            }

            if (string.IsNullOrEmpty(themeName))
            {
                throw new ArgumentNullException("themeName");
            }

            LoggingUtility.Internal.TraceInformation((int)EventId.SetTheme, "Setting theme '{0}' for '{1}'", themeName, web.Context.Url);

            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog((int)ListTemplateType.DesignCatalog);

            rootWeb.Context.Load(themeList);
            LoggingUtility.Internal.TraceVerbose("Getting theme list (catalog 124)");
            rootWeb.Context.ExecuteQuery();

            // Double checking that theme exists
            if (rootWeb.ThemeEntryExists(themeName, themeList))
            {
                // Let's update the theme name accordingly
                CamlQuery query = new CamlQuery();
                // Find the theme by themeName
                string camlString = string.Format(CAML_QUERY_FIND_BY_FILENAME, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                rootWeb.Context.Load(found);
                LoggingUtility.Internal.TraceVerbose("Getting theme: {0}", themeName);
                rootWeb.Context.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];

                    //Set the properties for applying custom theme which was just uploaded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = UrlUtility.MakeRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = UrlUtility.MakeRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = UrlUtility.MakeRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    LoggingUtility.Internal.TraceVerbose("Apply theme '{0}', '{1}', '{2}'.", spColorURL, spFontURL, backGroundImage);
                    // Set theme for demonstration
                    // TODO: Why is shareGenerated false? If deploying to root an inheriting, then maybe use shareGenerated = true.
                    web.ApplyTheme(spColorURL,
                                   spFontURL,
                                   backGroundImage,
                                   false);
                    web.Context.ExecuteQuery();
                    LoggingUtility.Internal.TraceVerbose("Theme applied");

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        var masterUrl = UrlUtility.MakeRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);

                        web.SetMasterPageForSiteByUrl(masterUrl);
                        web.SetCustomMasterPageForSiteByUrl(masterUrl);
                    }
                }
                else
                {
                    LoggingUtility.Internal.TraceError((int)EventId.ThemeMissing, "Theme '{0}' not found.", themeName);
                }
            }
            else
            {
                LoggingUtility.Internal.TraceError((int)EventId.ThemeMissing, "Theme '{0}' does not exist.", themeName);
            }
        }
        public void SetThemeBasedOnName(ClientContext cc, Web web, string themeName)
        {
            Web rootWeb;
            if (EnsureWeb(cc, web, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant() !=
                    EnsureSite(cc, cc.Site, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant())
            {
                // get instances to root web, since we are processign currently sub site
                rootWeb = cc.Site.RootWeb;
                cc.Load(rootWeb);
                cc.ExecuteQuery();
            }
            else
            {
                rootWeb = web;
            }

            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);
            cc.Load(themeList);
            cc.ExecuteQuery();

            // Double checking that theme exists
            if (ThemeEntryExists(cc, rootWeb, themeList, themeName))
            {
                CamlQuery query = new CamlQuery();
                string camlString = @"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";
                // Let's update the theme name accordingly
                camlString = string.Format(camlString, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                cc.Load(found);
                cc.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];
                    //Set the properties for applying custom theme which was jus uplaoded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    // Set theme for demonstration
                    web.ApplyTheme(spColorURL,
                                        spFontURL,
                                        backGroundImage,
                                        false);

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url); ;
                    }

                    cc.ExecuteQuery();
                }
            }
        }
Exemple #11
0
        private void ApplyBranding(ValuesToApply valuesToApply, ClientContext ctx, Web web)
        {
            var shouldExecute = false;

            if (!string.IsNullOrEmpty(valuesToApply.SiteTitle))
            {
                shouldExecute = true;
                web.Title     = valuesToApply.SiteTitle;
                Console.WriteLine("Set web title to " + valuesToApply.SiteTitle);
            }
            if (!string.IsNullOrEmpty(valuesToApply.SiteLogoUrl))
            {
                shouldExecute   = true;
                web.SiteLogoUrl = valuesToApply.SiteLogoUrl;
                OnNotify(ProvisioningNotificationLevels.Verbose, $"Set web logo to {web.SiteLogoUrl}");
            }
            if (!string.IsNullOrEmpty(valuesToApply.DefaultMasterPageUrl))
            {
                shouldExecute = true;
                web.MasterUrl = valuesToApply.DefaultMasterPageUrl;
                OnNotify(ProvisioningNotificationLevels.Verbose, $"Set web default master page url to {web.MasterUrl}");
            }
            if (!string.IsNullOrEmpty(valuesToApply.CustomMasterPageUrl))
            {
                shouldExecute       = true;
                web.CustomMasterUrl = valuesToApply.CustomMasterPageUrl;
                OnNotify(ProvisioningNotificationLevels.Verbose, $"Set web default master page url to {web.CustomMasterUrl}");
            }
            if (!string.IsNullOrEmpty(valuesToApply.AlternateCssUrl))
            {
                shouldExecute       = true;
                web.AlternateCssUrl = valuesToApply.AlternateCssUrl;
                OnNotify(ProvisioningNotificationLevels.Verbose, $"Set web alternate css url to {web.AlternateCssUrl}");
            }
            if (shouldExecute)
            {
                web.Update();
                try
                {
                    ctx.ExecuteQueryRetry();
                    shouldExecute = false;
                }
                catch
                {
                    OnNotify(ProvisioningNotificationLevels.Verbose, "Failed to apply branding. Make sure all the files you need are either in the site or the package. Note that images for composed looks are often the cause of this problem.");
                }
            }
            if (!string.IsNullOrEmpty(valuesToApply.ThemeUrl))
            {
                shouldExecute = true;
                web.ApplyTheme(valuesToApply.ThemeUrl, valuesToApply.FontSchemeUrl, valuesToApply.ImageUrl, false);
                OnNotify(ProvisioningNotificationLevels.Verbose, $"Set theme to {valuesToApply.ThemeUrl}");
            }
            if (shouldExecute)
            {
                web.Update();
                try
                {
                    ctx.ExecuteQueryRetry();
                }
                catch
                {
                    OnNotify(ProvisioningNotificationLevels.Verbose, "Failed to apply branding. Make sure all the files you need are either in the site or the package. Note that images for composed looks are often the cause of this problem.");
                }
            }
        }
        public void SetComposedLook(ClientContext context, ShWeb configWeb, Web web, ShComposedLook composedLook)
        {
            if (composedLook != null)
            {
                Log.Debug("Setting Composed Look for web " + configWeb.Name);
                var themeUrl      = string.Empty;
                var fontSchemeUrl = string.Empty;

                List themeList = web.GetCatalog(124);
                web.Context.Load(themeList);
                web.Context.ExecuteQuery();

                // We are assuming that the theme exists
                string camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                        </Query>
                </View>";
                camlString = string.Format(camlString, composedLook.Name);

                CamlQuery query = new CamlQuery();
                query.ViewXml = camlString;
                var themeItems = themeList.GetItems(query);
                web.Context.Load(themeItems);
                web.Context.ExecuteQuery();

                if (themeItems.Count == 0)
                {
                    if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
                    {
                        context.Load(web, w => w.ServerRelativeUrl);
                        context.ExecuteQuery();
                    }

                    var      itemInfo = new ListItemCreationInformation();
                    ListItem item     = themeList.AddItem(itemInfo);
                    item["Name"]  = composedLook.Name;
                    item["Title"] = composedLook.Title;
                    if (!string.IsNullOrEmpty(composedLook.ThemeUrl))
                    {
                        themeUrl         = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", Path.GetFileName(composedLook.ThemeUrl)));
                        item["ThemeUrl"] = themeUrl;
                    }
                    if (!string.IsNullOrEmpty(composedLook.FontSchemeUrl))
                    {
                        fontSchemeUrl         = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", Path.GetFileName(composedLook.FontSchemeUrl)));
                        item["FontSchemeUrl"] = fontSchemeUrl;
                    }
                    if (string.IsNullOrEmpty(composedLook.MasterPageUrl))
                    {
                        item["MasterPageUrl"] = Url.Combine(web.ServerRelativeUrl, "/_catalogs/masterpage/seattle.master");
                    }
                    else
                    {
                        item["MasterPageUrl"] = Url.Combine(web.ServerRelativeUrl, string.Format("/_catalogs/masterpage/{0}", Path.GetFileName(composedLook.MasterPageUrl)));
                    }
                    item["DisplayOrder"] = 11;
                    item.Update();
                    context.ExecuteQuery();
                }
                else
                {
                    ListItem item = themeItems[0];
                    var      themeUrlFieldValue      = item["ThemeUrl"] as FieldUrlValue;
                    var      fontSchemeUrlFieldValue = item["FontSchemeUrl"] as FieldUrlValue;
                    if (themeUrlFieldValue != null)
                    {
                        themeUrl = UriUtilities.GetRelativeUrl(themeUrlFieldValue.Url);
                    }
                    if (fontSchemeUrlFieldValue != null)
                    {
                        fontSchemeUrl = UriUtilities.GetRelativeUrl(fontSchemeUrlFieldValue.Url);
                    }
                }

                web.ApplyTheme(themeUrl, fontSchemeUrl, null, false);
                context.ExecuteQuery();
            }
        }
Exemple #13
0
        public static void ProvisionFiles()
        {
            string        srcSiteUrl       = "http://win-f33ohjutmmi/sites/cms";
            ClientContext clientContextSRC = new ClientContext(srcSiteUrl);
            Site          srcSite          = clientContextSRC.Site;

            clientContextSRC.Load(srcSite, s => s.ServerRelativeUrl, s => s.Url);
            clientContextSRC.ExecuteQuery();

            Web srcRootWeb    = clientContextSRC.Site.RootWeb;
            Web srcCurrentWeb = clientContextSRC.Web;

            clientContextSRC.Load(srcRootWeb, rw => rw.Id);
            clientContextSRC.ExecuteQuery();
            clientContextSRC.Load(srcCurrentWeb, cw => cw.Id);
            clientContextSRC.ExecuteQuery();

            string srcMasterUrl = String.Format("{0}/_catalogs/masterpage/APCMS.master", srcSite.ServerRelativeUrl);
            File   apcmsSrcFile = null;

            string srcLayoutUrl       = String.Format("{0}/_catalogs/masterpage/BridgePage.aspx", srcSite.ServerRelativeUrl);
            File   apcmsLayoutSrcFile = null;

            string srcColourFileUrl  = String.Format("{0}/_catalogs/theme/15/PaletteAPCMS.spcolor", srcSite.ServerRelativeUrl);
            File   apcmsColorSrcFile = null;


            ClientResult <System.IO.Stream> rs       = null;
            ClientResult <System.IO.Stream> rsLayout = null;
            ClientResult <System.IO.Stream> rsColor  = null;

            if (srcRootWeb.Id.ToString() == srcCurrentWeb.Id.ToString())
            {
                //load master page and page layout
                List   masterPageGallery = srcRootWeb.Lists.GetByTitle("Master Page Gallery");
                Folder rootFolder        = masterPageGallery.RootFolder;

                apcmsSrcFile       = srcCurrentWeb.GetFileByServerRelativeUrl(srcMasterUrl);
                apcmsLayoutSrcFile = srcCurrentWeb.GetFileByServerRelativeUrl(srcLayoutUrl);

                clientContextSRC.Load(apcmsSrcFile);
                clientContextSRC.Load(apcmsLayoutSrcFile);

                clientContextSRC.ExecuteQuery();

                rs       = apcmsSrcFile.OpenBinaryStream();
                rsLayout = apcmsLayoutSrcFile.OpenBinaryStream();

                clientContextSRC.ExecuteQuery();

                //load color file
                List themeGallery = srcRootWeb.Lists.GetByTitle("Theme Gallery");
                rootFolder = themeGallery.RootFolder;

                apcmsColorSrcFile = srcCurrentWeb.GetFileByServerRelativeUrl(srcColourFileUrl);

                clientContextSRC.Load(apcmsColorSrcFile);
                clientContextSRC.ExecuteQuery();
                rsColor = apcmsColorSrcFile.OpenBinaryStream();

                clientContextSRC.ExecuteQuery();
            }


            string        siteUrl       = "http://win-f33ohjutmmi/sites/pltest";
            ClientContext clientContext = new ClientContext(siteUrl);

            Site site = clientContext.Site;

            clientContext.Load(site, s => s.ServerRelativeUrl, s => s.Url);
            clientContext.ExecuteQuery();

            Web rootWeb    = clientContext.Site.RootWeb;
            Web currentWeb = clientContext.Web;

            clientContext.Load(rootWeb, rw => rw.Id);
            clientContext.ExecuteQuery();
            clientContext.Load(currentWeb, cw => cw.Id);
            clientContext.ExecuteQuery();

            #region upload and set master page, also upload the page layout

            string masterUrl = String.Format("{0}/_catalogs/masterpage/APCMS.master", site.ServerRelativeUrl);
            string colorUrl  = String.Format("{0}/_catalogs/theme/15/PaletteAPCMS.spcolor", site.ServerRelativeUrl);


            if (rootWeb.Id.ToString() == currentWeb.Id.ToString())
            {
                List   masterPageGallery = rootWeb.Lists.GetByTitle("Master Page Gallery");
                Folder rootFolder        = masterPageGallery.RootFolder;
                //master page
                FileCreationInformation fci = new FileCreationInformation();
                fci.ContentStream = rs.Value;
                fci.Url           = "APCMS.master";
                fci.Overwrite     = true;

                Microsoft.SharePoint.Client.File fileToUpload = rootFolder.Files.Add(fci);

                clientContext.Load(fileToUpload);

                fileToUpload.Publish("");

                currentWeb.CustomMasterUrl = masterUrl;
                currentWeb.Update();
                clientContext.ExecuteQuery();

                //page layout
                fci = new FileCreationInformation();
                fci.ContentStream = rsLayout.Value;
                fci.Url           = "BridgePage.aspx";
                fci.Overwrite     = true;

                fileToUpload = rootFolder.Files.Add(fci);

                fileToUpload.Publish("");
                clientContext.ExecuteQuery();

                ListItem item = fileToUpload.ListItemAllFields;

                ContentType targetDocumentSetContentType = GetContentType(clientContext, rootWeb, "Page Layout");
                item["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
                item.Update();
                clientContext.ExecuteQuery();

                targetDocumentSetContentType            = GetContentType(clientContext, rootWeb, "Article Page");
                item["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", targetDocumentSetContentType.Name, targetDocumentSetContentType.Id.ToString());
                item.Update();
                clientContext.ExecuteQuery();

                //color file
                List themeGallery = rootWeb.Lists.GetByTitle("Theme Gallery");
                clientContext.Load(themeGallery.RootFolder.Folders); //load the sub folder first !!!
                clientContext.ExecuteQuery();                        //must call

                rootFolder        = themeGallery.RootFolder.Folders[0];
                fci               = new FileCreationInformation();
                fci.ContentStream = rsColor.Value;
                fci.Url           = "PaletteAPCMS.spcolor";
                fci.Overwrite     = true;

                fileToUpload = rootFolder.Files.Add(fci);

                clientContext.ExecuteQuery();

                clientContext.Load(fileToUpload);

                rootWeb.ApplyTheme(colorUrl, null, null, true);
                rootWeb.Update();

                clientContext.ExecuteQuery();
            }

            #endregion
        }
        protected void ApplyTheme()
        {
            using (var clientContext = TokenHelper.GetClientContextWithContextToken(_HostWeb, _ContextToken, Request.Url.Authority))
            {
                // Apply our new theme

                // First, copy theme files to a temporary location (the web's Site Assets Library)
                Web  hostWebObj     = clientContext.Web;
                Site hostSiteObj    = clientContext.Site;
                Web  hostRootWebObj = hostSiteObj.RootWeb;

                // Get the necessary lists & libraries
                List   themeLibrary  = hostRootWebObj.Lists.GetByTitle("Theme Gallery");
                Folder themeFolder   = themeLibrary.RootFolder.Folders.GetByUrl("15");
                List   looksGallery  = hostRootWebObj.Lists.GetByTitle("Composed Looks");
                List   masterLibrary = hostRootWebObj.Lists.GetByTitle("Master Page Gallery");
                List   assetLibrary  = hostRootWebObj.Lists.GetByTitle("Site Assets");

                clientContext.Load(themeFolder, f => f.ServerRelativeUrl);
                clientContext.Load(masterLibrary, l => l.RootFolder);
                clientContext.Load(assetLibrary, l => l.RootFolder);

                // First, upload the theme files to the theme gallery
                DirectoryInfo themeDir = new DirectoryInfo(Server.MapPath("/Theme"));
                foreach (var themeFile in themeDir.EnumerateFiles())
                {
                    FileCreationInformation newFile = new FileCreationInformation();
                    newFile.Content   = System.IO.File.ReadAllBytes(themeFile.FullName);
                    newFile.Url       = themeFile.Name;
                    newFile.Overwrite = true;

                    // Sort by file extension into the correct library
                    switch (themeFile.Extension)
                    {
                    case ".spcolor":
                    case ".spfont":
                        Microsoft.SharePoint.Client.File uploadTheme = themeFolder.Files.Add(newFile);
                        clientContext.Load(uploadTheme);
                        break;

                    case ".master":
                    case ".html":
                        Microsoft.SharePoint.Client.File updloadMaster = masterLibrary.RootFolder.Files.Add(newFile);
                        clientContext.Load(updloadMaster);
                        break;

                    default:
                        Microsoft.SharePoint.Client.File uploadAsset = assetLibrary.RootFolder.Files.Add(newFile);
                        clientContext.Load(uploadAsset);
                        break;
                    }
                }

                // Execute the file upload
                clientContext.ExecuteQuery();

                // Create a new composed look for our theme
                string themeFolderUrl  = themeFolder.ServerRelativeUrl;
                string masterFolderUrl = masterLibrary.RootFolder.ServerRelativeUrl;

                ListItemCreationInformation          newLook     = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem newLookItem = looksGallery.AddItem(newLook);
                newLookItem["Title"] = "Theme Sample Look";
                newLookItem["Name"]  = "Theme Sample Look";

                FieldUrlValue masterFieldValue = new FieldUrlValue();
                masterFieldValue.Url         = masterFolderUrl + "/seattle.master";
                newLookItem["MasterPageUrl"] = masterFieldValue;

                FieldUrlValue colorFieldValue = new FieldUrlValue();
                colorFieldValue.Url     = themeFolderUrl + "/ThemeSample.spcolor";
                newLookItem["ThemeUrl"] = colorFieldValue;

                FieldUrlValue fontFieldValue = new FieldUrlValue();
                fontFieldValue.Url           = themeFolderUrl + "/ThemeSample.spfont";
                newLookItem["FontSchemeUrl"] = fontFieldValue;

                newLookItem.Update();

                // Apply master page
                hostWebObj.CustomMasterUrl = masterFieldValue.Url;

                // Must update between this step and the next - ApplyTheme errors if master is updated in the same query.
                hostWebObj.Update();
                clientContext.ExecuteQuery();

                // Apply theme
                hostWebObj.ApplyTheme(
                    colorFieldValue.Url, // URL of the Color Palette file (this is the only required theme component),
                    fontFieldValue.Url,  // URL to the Font Specification file (optional)
                    null,                // Background Image URL (optional, null here),
                    false                // false stores the composed theme files in this web only. True would share with the site collection (to which we are not currently granted permissions)
                    );

                // Need to call update to apply the change to the host web
                hostWebObj.Update();

                // Execute the Update Method
                clientContext.ExecuteQuery();
            }
        }
Exemple #15
0
        private static void SetThemeToWebImplementation(this Web web, Web rootWeb, string themeName)
        {
            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);

            rootWeb.Context.Load(themeList);
            rootWeb.Context.ExecuteQuery();

            // Double checking that theme exists
            if (rootWeb.ThemeEntryExists(themeName, themeList))
            {
                CamlQuery query      = new CamlQuery();
                string    camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";

                // Let's update the theme name accordingly
                camlString    = string.Format(camlString, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                rootWeb.Context.Load(found);
                rootWeb.Context.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];
                    //Set the properties for applying custom theme which was jus uplaoded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = UrlUtility.MakeRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = UrlUtility.MakeRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = UrlUtility.MakeRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    // Set theme for demonstration
                    web.ApplyTheme(spColorURL,
                                   spFontURL,
                                   backGroundImage,
                                   false);

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        web.MasterUrl = UrlUtility.MakeRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);;
                    }

                    web.Context.ExecuteQuery();
                }
            }
        }
Exemple #16
0
        public void SetThemeBasedOnName(ClientContext cc, Web web, string themeName)
        {
            Web rootWeb;

            if (EnsureWeb(cc, web, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant() !=
                EnsureSite(cc, cc.Site, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant())
            {
                // get instances to root web, since we are processign currently sub site
                rootWeb = cc.Site.RootWeb;
                cc.Load(rootWeb);
                cc.ExecuteQuery();
            }
            else
            {
                rootWeb = web;
            }

            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);

            cc.Load(themeList);
            cc.ExecuteQuery();

            // Double checking that theme exists
            if (ThemeEntryExists(cc, rootWeb, themeList, themeName))
            {
                CamlQuery query      = new CamlQuery();
                string    camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";
                // Let's update the theme name accordingly
                camlString    = string.Format(camlString, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                cc.Load(found);
                cc.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];
                    //Set the properties for applying custom theme which was jus uplaoded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    // Set theme for demonstration
                    web.ApplyTheme(spColorURL,
                                   spFontURL,
                                   backGroundImage,
                                   false);

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);;
                    }

                    cc.ExecuteQuery();
                }
            }
        }
Exemple #17
0
        public void SetThemeBasedOnName(ClientContext ctx, Web web, Web rootWeb, string themeName)
        {
            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);

            ctx.Load(themeList);
            ctx.ExecuteQuery();

            CamlQuery query      = new CamlQuery();
            string    camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";

            // Let's update the theme name accordingly
            camlString    = string.Format(camlString, themeName);
            query.ViewXml = camlString;
            var found = themeList.GetItems(query);

            ctx.Load(found);
            ctx.ExecuteQuery();
            if (found.Count > 0)
            {
                Microsoft.SharePoint.Client.ListItem themeEntry = found[0];
                //Set the properties for applying custom theme which was jus uplaoded
                string spColorURL = null;
                if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                {
                    spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                }
                string spFontURL = null;
                if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                {
                    spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                }
                string backGroundImage = null;
                if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                {
                    backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                }

                // Set theme for demonstration
                web.ApplyTheme(spColorURL,
                               spFontURL,
                               backGroundImage,
                               false);

                // Let's also update master page, if needed
                if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                {
                    web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);;
                }

                ctx.ExecuteQuery();
            }
        }
Exemple #18
0
 public static void ApplyTheme(string colorPaletteUrl, string fontSchemeUrl, string backgroundImageUrl, bool shareGenerated, Web web, ClientContext clientContext)
 {
     web.ApplyTheme(colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated);
     clientContext.ExecuteQuery();
 }