Update() private method

private Update ( ) : void
return void
Beispiel #1
0
 public static bool CreateDocumentLibrary(string libraryName)
 {
     using (ClientContext clientContext = GetContextObject())
     {
         Web web = clientContext.Web;
         clientContext.Load(web, website => website.ServerRelativeUrl);
         clientContext.ExecuteQuery();
         Regex  regex               = new Regex(Configuration.SiteUrl, RegexOptions.IgnoreCase);
         string documentLibrary     = regex.Replace(Configuration.FileUrl, string.Empty);
         ListCreationInformation cr = new ListCreationInformation();
         cr.Title             = libraryName;
         cr.TemplateType      = 101;
         cr.QuickLaunchOption = QuickLaunchOptions.On;
         var dlAdd = web.Lists.Add(cr);
         web.QuickLaunchEnabled = true;
         web.Update();
         clientContext.Load(dlAdd);
         clientContext.ExecuteQuery();
         NavigationNodeCreationInformation nr = new NavigationNodeCreationInformation();
         nr.Title      = libraryName;
         nr.AsLastNode = true;
         nr.Url        = Configuration.SiteUrl + libraryName + "/Forms/AllItems.aspx";
         var dlAdd1 = web.Navigation.QuickLaunch.Add(nr);
         web.QuickLaunchEnabled = true;
         web.Update();
         clientContext.Load(dlAdd1);
         clientContext.ExecuteQuery();
     }
     return(true);
 }
Beispiel #2
0
        /// <summary>
        /// Configures the Master Page settings of the specified Web.
        /// </summary>
        /// <param name="web">Web object to process</param>
        /// <param name="mpServerRelativeUrl">server-relative path to master page file; if null/empty, Web will inherit MPs from parent</param>
        /// <param name="mpOption">0 - All Masters; 1: Site Master Only; 2: System Master Only</param>
        public static void SetMasterPages(Web web, string mpServerRelativeUrl, bool inheritMaster, MasterPageOptions mpOption)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Setting Master Pages for: {0} ...", web.Url), true);

                web.Context.Load(web.AllProperties);
                web.Context.ExecuteQueryRetry();

                if (mpOption == MasterPageOptions.BothMasterPages || mpOption == MasterPageOptions.SiteMasterPageOnly)
                {
                    web.CustomMasterUrl = mpServerRelativeUrl;
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                    web.SetPropertyBagValue(Constants.PropertyBagInheritsCustomMaster, (inheritMaster ? "True" : "False"));
                    Logger.LogSuccessMessage(String.Format("Set Site Master Page to {0}{1}", (inheritMaster ? "inherit " : ""), mpServerRelativeUrl), false);
                }
                if (mpOption == MasterPageOptions.BothMasterPages || mpOption == MasterPageOptions.SystemMasterPageOnly)
                {
                    web.MasterUrl = mpServerRelativeUrl;
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                    web.SetPropertyBagValue(Constants.PropertyBagInheritsMaster, (inheritMaster ? "True" : "False"));
                    Logger.LogSuccessMessage(String.Format("Set System Master Page to {0}{1}", (inheritMaster ? "inherit " : ""), mpServerRelativeUrl), false);
                }
                Logger.LogSuccessMessage(String.Format("Set Master Pages for: {0}", web.Url), false);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("SetMasterPages() failed for {0}: Error={1}", web.Url, ex.Message), false);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Creates group with restricted access permissions on client site collection to allow functionality in matter landing page
        /// </summary>
        /// <param name="siteUrl">URL of the client site collection to create group at</param>
        /// <param name="onlineCredentials">credentials to access site</param>
        internal static void CreateRestrictedGroup(string siteUrl, SharePointOnlineCredentials onlineCredentials)
        {
            try
            {
                Console.WriteLine("Creating " + ConfigurationManager.AppSettings["restrictedAccessGroupName"] + " group.");

                using (ClientContext clientContext = new ClientContext(siteUrl))
                {
                    clientContext.Credentials = onlineCredentials;
                    Site collSite = clientContext.Site;
                    Web  site     = clientContext.Web;

                    //Create group
                    GroupCollection collGroup = site.SiteGroups;
                    clientContext.Load(collGroup, group => group.Include(properties => properties.Title));
                    clientContext.Load(site.RoleDefinitions);
                    clientContext.ExecuteQuery();

                    Group currentGrp = (from grp in collGroup where grp.Title == ConfigurationManager.AppSettings["restrictedAccessGroupName"] select grp).FirstOrDefault();
                    if (currentGrp != null)
                    {
                        collGroup.Remove(currentGrp);
                    }

                    GroupCreationInformation grpInfo = new GroupCreationInformation();
                    grpInfo.Title       = ConfigurationManager.AppSettings["restrictedAccessGroupName"];
                    grpInfo.Description = ConfigurationManager.AppSettings["restrictedAccessGroupDescription"];
                    collGroup.Add(grpInfo);
                    site.Update();
                    clientContext.Load(collGroup);
                    clientContext.ExecuteQuery();

                    currentGrp = (from grp in collGroup where grp.Title == ConfigurationManager.AppSettings["restrictedAccessGroupName"] select grp).FirstOrDefault();

                    AssignPermissionToGroup(clientContext, collSite, site, currentGrp);

                    //Add everyone to group
                    User allUsers = clientContext.Web.EnsureUser(ConfigurationManager.AppSettings["allUsers"]);
                    clientContext.Load(allUsers);
                    clientContext.ExecuteQuery();

                    currentGrp.Users.AddUser(allUsers);
                    site.Update();
                    clientContext.Load(currentGrp);
                    clientContext.ExecuteQuery();

                    Console.WriteLine("Created " + ConfigurationManager.AppSettings["restrictedAccessGroupName"] + " group successfully");
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception occurred while creating group: " + exception.Message);
            }
        }
        /// <summary>
        /// Uploads site logo to host web
        /// </summary>
        /// <param name="web"></param>
        public static void SetLogoToWeb(Web web, string logoFile)
        {
            // Instance to site assets
            List assetLibrary = web.Lists.GetByTitle("Site Assets");

            web.Context.Load(assetLibrary, l => l.RootFolder);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = System.IO.File.ReadAllBytes(logoFile);
            newFile.Url       = Path.GetFileName(logoFile);
            newFile.Overwrite = true;
            Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();

            // Load relative URL
            web.Context.Load(web, w => w.ServerRelativeUrl);
            web.Context.ExecuteQuery();

            // Set the properties accordingly
            web.SiteLogoUrl = web.ServerRelativeUrl + "/SiteAssets/" + Path.GetFileName(logoFile);
            web.Update();
            web.Context.ExecuteQuery();
        }
Beispiel #5
0
            public SPContentType CreateAsPartOfGroup(string groupName)
            {
                if (Web.ContentTypes[Name] != null)
                {
                    return(Web.ContentTypes[Name]);
                }

                var contentType = new SPContentType(Web.AvailableContentTypes[ParentContentType], Web.ContentTypes, Name)
                {
                    Group = groupName
                };

                foreach (var fieldInfo in FieldDefinitions.Select(fieldDef => new { fieldDef.IsHidden, Field = fieldDef.CreateIn(Web.Fields, groupName) }))
                {
                    contentType.FieldLinks.Add(new SPFieldLink(fieldInfo.Field)
                    {
                        Hidden = fieldInfo.IsHidden
                    });
                }

                if (!string.IsNullOrEmpty(NewFormUrl))
                {
                    contentType.NewFormUrl = NewFormUrl;
                }

                Web.ContentTypes.Add(contentType);
                Web.Update();

                contentType.Update();
                return(contentType);
            }
        public static void SetMasterPages(Web web, MasterPageInfo mpi, bool isRoot)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Setting Master Pages to: {0} & {1}...", mpi.MasterPageUrl, mpi.CustomMasterPageUrl), false);

                Logger.LogInfoMessage(String.Format("MasterUrl (before): {0}", web.MasterUrl), false);
                Logger.LogInfoMessage(String.Format("CustomMasterUrl (before): {0}", web.CustomMasterUrl), false);

                web.Context.Load(web.AllProperties);
                web.Context.ExecuteQuery();

                web.MasterUrl       = mpi.MasterPageUrl;
                web.CustomMasterUrl = mpi.CustomMasterPageUrl;
                web.AllProperties[Constants.PropertyBagInheritMaster]       = ((!isRoot && mpi.InheritMaster) ? "True" : "False");
                web.AllProperties[Constants.PropertyBagInheritCustomMaster] = ((!isRoot && mpi.InheritCustomMaster) ? "True" : "False");
                web.Update();
                web.Context.ExecuteQuery();

                Logger.LogSuccessMessage(String.Format("MasterUrl (after): {0}", web.MasterUrl), false);
                Logger.LogSuccessMessage(String.Format("CustomMasterUrl (after): {0}", web.CustomMasterUrl), false);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("SetMasterPages() failed for {0}: Error={1}", web.Url, ex.Message), false);
            }
        }
Beispiel #7
0
 public override bool Perform()
 {
     LogMessage("Removing management of personal views from Contribute2 permission level", 2);
     try
     {
         Web.AllowUnsafeUpdates = true;
         SPRoleDefinition roleDef = Web.RoleDefinitions["Contribute2"];
         if (roleDef.BasePermissions.ToString().Contains(SPBasePermissions.ManagePersonalViews.ToString()))
         {
             roleDef.BasePermissions &= ~SPBasePermissions.ManagePersonalViews;
             roleDef.Update();
             Web.Update();
             LogMessage("Removed management of personal views from Contribute2 permission level", MessageKind.SUCCESS, 4);
         }
         else
         {
             LogMessage("Management of personal views already removed from Contribute2 permission level.", MessageKind.SKIPPED, 4);
         }
         Web.AllowUnsafeUpdates = false;
     }
     catch (Exception ex)
     {
         LogMessage(ex.Message, MessageKind.FAILURE, 4);
     }
     return(true);
 }
Beispiel #8
0
        /// <summary>
        /// Create Column Taxonomy
        /// </summary>
        /// <param name="group"></param>
        /// <param name="termSet"></param>
        /// <param name="multiValue"></param>
        /// <param name="requiered"></param>
        /// <returns></returns>
        public bool CreateTaxonomy(string group, string termSet, bool multiValue = false, bool requiered = false)
        {
            try
            {
                var session   = new TaxonomySession(Web.Site);
                var termStore = session.TermStores[0];
                var groupTx   = termStore.Groups[group];
                var trmSet    = groupTx.TermSets[termSet];

                var taxonomyField =
                    (TaxonomyField)Web.Fields.CreateNewField("TaxonomyFieldType", Name);
                taxonomyField.SspId               = termStore.Id;
                taxonomyField.Group               = GroupName;
                taxonomyField.TermSetId           = trmSet.Id;
                taxonomyField.Open                = true;
                taxonomyField.AllowMultipleValues = multiValue;
                taxonomyField.Required            = requiered;
                Web.Fields.Add(taxonomyField);
                Web.Update();
                return(true);
            }
            catch (Exception exception)
            {
                Logger.Error(string.Concat("ColumnaSitio Create Taxonomy:", exception.Message));
                return(false);
            }
        }
Beispiel #9
0
 public static void InitialiseAllocatedSite(this Web value, ProvisionedSite provisionedSite, Task task, string serverRelativeUrl)
 {
     value.Title             = task.SiteTitle;
     value.ServerRelativeUrl = serverRelativeUrl;
     value.DeleteListFromWebByTitle(SharePointListNames.SharedDocuments);
     value.Update();
 }
Beispiel #10
0
        public void CreateSite(ClientContext context,
                               string UrlOfSiteRelativeToRoot,
                               string NameOfSite,
                               string Description)
        {
            Web rootWeb = context.Site.RootWeb;

            context.Load(rootWeb, w => w.CustomMasterUrl);

            WebCreationInformation wci = new WebCreationInformation();

            wci.Url         = UrlOfSiteRelativeToRoot;
            wci.Title       = NameOfSite;
            wci.Description = Description;
            wci.UseSamePermissionsAsParentSite = true;
            wci.WebTemplate = "BLANKINTERNET#0";
            wci.Language    = 1033;

            Web subWeb = context.Site.RootWeb.Webs.Add(wci);

            context.ExecuteQuery();

            //Update MasterPage
            subWeb.CustomMasterUrl = rootWeb.CustomMasterUrl;
            subWeb.MasterUrl       = rootWeb.CustomMasterUrl;
            subWeb.Update();
            context.Load(subWeb);
            context.ExecuteQuery();
        }
Beispiel #11
0
        private void ApplyThemeToSite(Web hostWeb, Web newWeb)
        {
            // Let's first upload the contoso theme to host web, if it does not exist there
            var colorFile      = hostWeb.UploadThemeFile(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/TechEd/teched.spcolor")));
            var backgroundFile = hostWeb.UploadThemeFile(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/TechEd/bg.jpg")));

            newWeb.CreateComposedLookByUrl("TechEd", colorFile.ServerRelativeUrl, null, backgroundFile.ServerRelativeUrl, string.Empty);
            // Setting the Contoos theme to host web
            newWeb.SetComposedLookByUrl("TechEd");

            // Instance to site assets. Notice that this is using hard coded list name which only works in 1033 sites
            List assetLibrary = newWeb.Lists.GetByTitle("Site Assets");

            newWeb.Context.Load(assetLibrary, l => l.RootFolder);

            // Get the path to the file which we are about to deploy
            string logoFile = System.Web.Hosting.HostingEnvironment.MapPath(
                string.Format("~/{0}", "Resources/Themes/TechEd/logo.png"));

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = System.IO.File.ReadAllBytes(logoFile);
            newFile.Url       = "pnp.png";
            newFile.Overwrite = true;
            File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);

            newWeb.Context.Load(uploadFile);
            newWeb.Context.ExecuteQuery();

            newWeb.AlternateCssUrl = newWeb.ServerRelativeUrl + "/SiteAssets/contoso.css";
            newWeb.SiteLogoUrl     = newWeb.ServerRelativeUrl + "/SiteAssets/pnp.png";
            newWeb.Update();
            newWeb.Context.ExecuteQuery();
        }
Beispiel #12
0
        /// <summary>
        /// Method to add users to current group
        /// </summary>
        /// <param name="clientContext">client context</param>
        /// <param name="site">site object</param>
        /// <param name="currentGrp">group object</param>
        /// <param name="item">data storage</param>
        private static void AddUsersToCurrentGroup(ClientContext clientContext, Web site, Group currentGrp, DataStorage item)
        {
            string[] allUserEmail = item.Members.Split(new char[] { ';' });

            Console.WriteLine("Adding users to this group");
            List <User> allUsers = new List <User>();

            foreach (string userEmail in allUserEmail)
            {
                if (!string.IsNullOrEmpty(userEmail))
                {
                    User user = clientContext.Web.EnsureUser(userEmail.Trim());
                    clientContext.Load(user);
                    clientContext.ExecuteQuery();
                    allUsers.Add(user);
                }
            }
            foreach (User user in allUsers)
            {
                currentGrp.Users.AddUser(user);
            }
            site.Update();
            clientContext.Load(currentGrp);
            clientContext.ExecuteQuery();
            Console.WriteLine("Successfully added users to group " + currentGrp.Title);
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.Header != null)
                {
                    switch (template.Header.Layout)
                    {
                    case SiteHeaderLayout.Compact:
                    {
                        web.HeaderLayout = HeaderLayoutType.Compact;
                        break;
                    }

                    case SiteHeaderLayout.Standard:
                    {
                        web.HeaderLayout = HeaderLayoutType.Standard;
                        break;
                    }
                    }
                    web.HeaderEmphasis  = (SPVariantThemeType)Enum.Parse(typeof(SPVariantThemeType), template.Header.BackgroundEmphasis.ToString());
                    web.MegaMenuEnabled = template.Header.MenuStyle == SiteHeaderMenuStyle.MegaMenu;
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }
            }
            return(parser);
        }
Beispiel #14
0
        /// <summary>
        /// Upload helper function for uploading documents to SharePoint library.
        /// </summary>
        /// <param name="folderPath">Folder path of Document Library</param>
        /// <param name="listResponse">SharePoint list response</param>
        /// <param name="clientContext">Client context object for connection between SP & client</param>
        /// <param name="documentLibraryName">Name of document library in which upload is to be done</param>
        /// <param name="web">Object of site</param>
        /// <param name="folderName">Target folder name where file needs to be uploaded.</param>
        /// <param name="uploadFile">Object having file creation information</param>
        /// <returns>It returns true if upload is successful else false</returns>
        private static bool DocumentUpload(string folderPath, IList <string> listResponse, ClientContext clientContext, string documentLibraryName, Web web, string folderName, FileCreationInformation uploadFile)
        {
            bool isUploadSuccessful = false;

            using (clientContext)
            {
                if (UIUtility.FolderExists(folderPath, clientContext, documentLibraryName))
                {
                    Folder destionationFolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(destionationFolder);
                    clientContext.ExecuteQuery();
                    Microsoft.SharePoint.Client.File fileToUpload = destionationFolder.Files.Add(uploadFile);
                    destionationFolder.Update();
                    web.Update();
                    clientContext.Load(fileToUpload);
                    clientContext.ExecuteQuery();
                    isUploadSuccessful = true;
                }
                else
                {
                    listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}",
                                                   string.Format(CultureInfo.InvariantCulture, ConstantStrings.FolderStructureModified, folderName),
                                                   ConstantStrings.DOLLAR, folderName));
                }
            }
            return(isUploadSuccessful);
        }
        /// <summary>
        /// Create field to web remotely
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="id">Guid for the new field.</param>
        /// <param name="internalName">Internal name of the field</param>
        /// <param name="fieldType">Field type to be created.</param>
        /// <param name="displayName">The display name of hte field</param>
        /// <param name="group">The field group name</param>
        /// <returns>The newly created field or existing field.</returns>
        public static Field CreateField(this Web web, Guid id, string internalName, string fieldType, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true)
        {
            FieldCollection fields = web.Fields;

            web.Context.Load(fields, fc => fc.Include(f => f.Id, f => f.InternalName));
            web.Context.ExecuteQuery();

            var field = fields.FirstOrDefault(f => f.Id == id || f.InternalName == internalName);

            if (field != null)
            {
                throw new ArgumentException("id", "Field already exists");
            }

            string newFieldCAML = string.Format(FIELD_XML_FORMAT, fieldType, internalName, displayName, id, group, additionalXmlAttributes);

            LoggingUtility.LogInformation("New Field as XML: " + newFieldCAML, EventCategory.FieldsAndContentTypes);
            field = fields.AddFieldAsXml(newFieldCAML, false, AddFieldOptions.AddFieldInternalNameHint);
            web.Update();

            if (executeQuery)
            {
                web.Context.ExecuteQuery();
            }

            return(field);
        }
Beispiel #16
0
        /// <summary>
        /// Uploads used CSS and site logo to host web
        /// </summary>
        /// <param name="web"></param>
        public void UploadAndSetLogoToSite(Web web, string pathToLogo)
        {
            // Load for basic properties
            web.Context.Load(web);
            web.Context.ExecuteQuery();

            // Instance to site assets
            List assetLibrary = web.Lists.GetByTitle("Site Assets");

            web.Context.Load(assetLibrary, l => l.RootFolder);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = System.IO.File.ReadAllBytes(pathToLogo);
            newFile.Url       = "pnp.png";
            newFile.Overwrite = true;
            Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);

            // Set custom image as the logo
            web.SiteLogoUrl = web.ServerRelativeUrl + "/SiteAssets/pnp.png";
            web.Update();
            web.Context.ExecuteQuery();
        }
Beispiel #17
0
        private static void LocalizeSiteAndList(ClientContext cc, Web web)
        {
            // Localize site title
            web.TitleResource.SetValueForUICulture("en-US", "Hello World");
            web.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
            web.TitleResource.SetValueForUICulture("fr-FR", "Localize Me to French");
            // Site description
            web.DescriptionResource.SetValueForUICulture("en-US", "Localize Me site sample");
            web.DescriptionResource.SetValueForUICulture("fi-FI", "Kielikäännetty saitti");
            web.DescriptionResource.SetValueForUICulture("fr-FR", "Localize to French in description");
            web.Update();
            cc.ExecuteQuery();

            // Localize custom list which was created previously
            List list = cc.Web.Lists.GetByTitle("LocalizeMe");
            cc.Load(list);
            cc.ExecuteQuery();
            list.TitleResource.SetValueForUICulture("en-US", "Localize Me");
            list.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
            list.TitleResource.SetValueForUICulture("fr-FR", "French text for title");
            // Description
            list.DescriptionResource.SetValueForUICulture("en-US", "This is localization CSOM usage example list.");
            list.DescriptionResource.SetValueForUICulture("fi-FI", "Tämä esimerkki näyttää miten voit kielikääntää listoja.");
            list.DescriptionResource.SetValueForUICulture("fr-FR", "I have no idea how to translate this to French.");
            list.Update();
            cc.ExecuteQuery();
        }
Beispiel #18
0
        /// <summary>
        /// Adds a new child Web (site) to a parent Web.
        /// </summary>
        /// <param name="parentWeb">The parent Web (site) to create under</param>
        /// <param name="title">The title of the new site. </param>
        /// <param name="leafUrl">A string that represents the URL leaf name.</param>
        /// <param name="description">The description of the new site. </param>
        /// <param name="template">The name of the site template to be used for creating the new site. </param>
        /// <param name="language">The locale ID that specifies the language of the new site. </param>
        /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param>
        /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param>
        public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true)
        {
            // TODO: Check for any other illegal characters in SharePoint
            if (leafUrl.Contains('/') || leafUrl.Contains('\\'))
            {
                throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl");
            }

            LoggingUtility.Internal.TraceInformation((int)EventId.CreateWeb, CoreResources.WebExtensions_CreateWeb, leafUrl, template);
            WebCreationInformation creationInfo = new WebCreationInformation()
            {
                Url         = leafUrl,
                Title       = title,
                Description = description,
                UseSamePermissionsAsParentSite = inheritPermissions,
                WebTemplate = template,
                Language    = language
            };

            Web newWeb = parentWeb.Webs.Add(creationInfo);

            newWeb.Navigation.UseShared = inheritNavigation;
            newWeb.Update();

            parentWeb.Context.ExecuteQueryRetry();

            return(newWeb);
        }
Beispiel #19
0
        private void ForceRecrawlOf(Web web, ClientContext context)
        {
            Log.Info("Scheduling full recrawl of: " + web.Url);
            context.Credentials = _credentials;

            context.Load(web, x => x.AllProperties, x => x.Webs);
            context.ExecuteQuery();
            var version = 0;
            var subWebs = web.Webs;

            var allProperties = web.AllProperties;

            if (allProperties.FieldValues.ContainsKey("vti_searchversion"))
            {
                version = (int)allProperties["vti_searchversion"];
            }
            version++;
            allProperties["vti_searchversion"] = version;
            web.Update();
            context.ExecuteQuery();
            foreach (var subWeb in subWebs)
            {
                ForceRecrawlOf(subWeb, context);
            }
        }
Beispiel #20
0
        private static void RemovePublishingPage(SPPublishing.PublishingPage publishingPage, PublishingPage page, ClientContext ctx, Web web)
        {
            if (publishingPage != null && publishingPage.ServerObjectIsNull.Value == false)
            {
                if (!web.IsPropertyAvailable("RootFolder"))
                {
                    web.Context.Load(web.RootFolder);
                    web.Context.ExecuteQueryRetry();
                }

                if (page.Overwrite)
                {
                    if (page.WelcomePage && web.RootFolder.WelcomePage.Contains(page.FileName + ".aspx"))
                    {
                        //set the welcome page to a Temp page to allow remove the page
                        web.RootFolder.WelcomePage = "home.aspx";
                        web.RootFolder.Update();
                        web.Update();

                        ctx.Load(publishingPage);
                        ctx.ExecuteQuery();
                    }

                    publishingPage.ListItem.DeleteObject();
                    ctx.ExecuteQuery();
                }
                else
                {
                    return;
                }
            }
        }
Beispiel #21
0
        private static void LocalizeSiteAndList(ClientContext cc, Web web)
        {
            // Localize site title
            web.TitleResource.SetValueForUICulture("en-US", "Localize Me");
            web.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
            web.TitleResource.SetValueForUICulture("fr-FR", "Localize Me to French");
            // Site description
            web.DescriptionResource.SetValueForUICulture("en-US", "Localize Me site sample");
            web.DescriptionResource.SetValueForUICulture("fi-FI", "Kielikäännetty saitti");
            web.DescriptionResource.SetValueForUICulture("fr-FR", "Localize to French in description");
            web.Update();
            cc.ExecuteQuery();

            // Localize custom list which was created previously
            List list = cc.Web.Lists.GetByTitle("LocalizeMe");

            cc.Load(list);
            cc.ExecuteQuery();
            list.TitleResource.SetValueForUICulture("en-US", "Localize Me");
            list.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
            list.TitleResource.SetValueForUICulture("fr-FR", "French text for title");
            // Description
            list.DescriptionResource.SetValueForUICulture("en-US", "This is localization CSOM usage example list.");
            list.DescriptionResource.SetValueForUICulture("fi-FI", "Tämä esimerkki näyttää miten voit kielikääntää listoja.");
            list.DescriptionResource.SetValueForUICulture("fr-FR", "I have no idea how to translate this to French.");
            list.Update();
            cc.ExecuteQuery();
        }
Beispiel #22
0
        /// <summary>
        /// Adds a new child Web (site) to a parent Web.
        /// </summary>
        /// <param name="parentWeb">The parent Web (site) to create under</param>
        /// <param name="title">The title of the new site. </param>
        /// <param name="leafUrl">A string that represents the URL leaf name.</param>
        /// <param name="description">The description of the new site. </param>
        /// <param name="template">The name of the site template to be used for creating the new site. </param>
        /// <param name="language">The locale ID that specifies the language of the new site. </param>
        /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param>
        /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param>
        public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true)
        {
            if (leafUrl.ContainsInvalidUrlChars())
            {
                throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl");
            }

            Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_CreateWeb, leafUrl, template);
            WebCreationInformation creationInfo = new WebCreationInformation()
            {
                Url         = leafUrl,
                Title       = title,
                Description = description,
                UseSamePermissionsAsParentSite = inheritPermissions,
                WebTemplate = template,
                Language    = language
            };

            Web newWeb = parentWeb.Webs.Add(creationInfo);

            newWeb.Navigation.UseShared = inheritNavigation;
            newWeb.Update();

            parentWeb.Context.ExecuteQueryRetry();

            return(newWeb);
        }
        /// <summary>
        /// Add Calendar Web Part to client site
        /// </summary>
        /// <param name="clientContext">SharePoint Client Context</param>
        /// <param name="matter">Matter object containing Matter data</param>
        internal static void AddCalendarList(ClientContext clientContext, Matter matter)
        {
            string calendarName = string.Concat(matter.MatterName, ConfigurationManager.AppSettings["CalendarNameSuffix"]);

            try
            {
                Web web = clientContext.Web;
                clientContext.Load(web, item => item.ListTemplates);
                clientContext.ExecuteQuery();
                ListTemplate listTemplate = null;
                foreach (var calendar in web.ListTemplates)
                {
                    if (calendar.Name == Constants.CalendarName)
                    {
                        listTemplate = calendar;
                    }
                }

                ListCreationInformation listCreationInformation = new ListCreationInformation();
                listCreationInformation.TemplateType = listTemplate.ListTemplateTypeKind;
                listCreationInformation.Title        = calendarName;
                // Added URL property for URL consolidation changes
                listCreationInformation.Url = Constants.TitleListPath + matter.MatterGuid + ConfigurationManager.AppSettings["CalendarNameSuffix"];
                web.Lists.Add(listCreationInformation);
                web.Update();
                clientContext.ExecuteQuery();
                MatterProvisionHelperFunction.BreakPermission(clientContext, matter.MatterName, matter.CopyPermissionsFromParent, calendarName);
            }
            catch (Exception exception)
            {
                //// Generic Exception
                MatterProvisionHelperFunction.DeleteMatter(clientContext, matter);
                MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Method to revert creation of site column and Content Type
 /// </summary>
 /// <param name="clientContext">Client Context</param>
 /// <param name="siteColumns">List of site columns</param>
 /// <param name="contentType">Name of Content Type</param>
 /// <param name="contentTypegroup">Name of Content Type group</param>
 /// <returns>Success or Message</returns>
 internal static void RevertSiteColumns(ClientContext clientContext, List <string> siteColumns, string contentType, string contentTypegroup)
 {
     try
     {
         Console.WriteLine("Deleting existing site columns and content type");
         Web web = clientContext.Web;
         ContentTypeCollection contentTypeCollection = web.ContentTypes;
         ContentType           parentContentType     = null;
         clientContext.Load(contentTypeCollection, contentTypeItem => contentTypeItem.Include(type => type.Group, type => type.Name).Where(f => f.Group == contentTypegroup));
         FieldCollection fieldCollection = web.Fields;
         clientContext.Load(fieldCollection, field => field.Include(attribute => attribute.Group, attribute => attribute.Title).Where(p => p.Group == contentTypegroup));
         clientContext.ExecuteQuery();
         parentContentType = (from contentTypes in contentTypeCollection where contentTypes.Name == contentType select contentTypes).FirstOrDefault();
         if (null != parentContentType)
         {
             parentContentType.DeleteObject();
         }
         foreach (string columns in siteColumns)
         {
             Field revertColumn = (from field in fieldCollection where field.Title == columns select field).FirstOrDefault();
             if (null != revertColumn)
             {
                 revertColumn.DeleteObject();
             }
         }
         web.Update();
         clientContext.ExecuteQuery();
         Console.WriteLine("Deleted existing site columns and content type");
     }
     catch (Exception exception)
     {
         Console.WriteLine("Failed to delete existing site columns.");
         ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
     }
 }
Beispiel #25
0
        private static void RemovePublishingPage(SPPublishing.PublishingPage publishingPage, PublishingPage page, ClientContext ctx, Web web)
        {
            if (publishingPage != null && publishingPage.ServerObjectIsNull.Value == false)
            {
                if (!web.IsPropertyAvailable("RootFolder"))
                {
                    web.Context.Load(web.RootFolder);
                    web.Context.ExecuteQueryRetry();
                }

                if (page.Overwrite)
                {
                    if (page.WelcomePage && web.RootFolder.WelcomePage.Contains(page.FileName + ".aspx"))
                    {
                        //set the welcome page to a Temp page to allow remove the page
                        web.RootFolder.WelcomePage = "home.aspx";
                        web.RootFolder.Update();
                        web.Update();

                        ctx.Load(publishingPage);
                        ctx.ExecuteQuery();
                    }

                    publishingPage.ListItem.DeleteObject();
                    ctx.ExecuteQuery();
                }
                else
                {
                    return;
                }
            }
        }
Beispiel #26
0
 static void SetAlternateCssAndSiteIcon()
 {
     site.AlternateCssUrl = AppRootFolderAbsoluteUrl + "content/styles.css?v=1.2";
     site.SiteLogoUrl     = AppRootFolderAbsoluteUrl + "content/AppIcon.png";
     site.Update();
     clientContext.ExecuteQuery();
 }
Beispiel #27
0
        /// <summary>
        /// Creates the OneNote in List/Library
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="clientAddressPath">Client URL</param>
        /// <param name="oneNoteLocation">OneNote URL</param>
        /// <param name="oneNoteTitle">OneNote Title</param>
        /// <param name="listName">List/library name</param>
        /// <returns></returns>
        public static string AddOneNote(ClientContext clientContext, string clientAddressPath, string oneNoteLocation, string listName, string oneNoteTitle)
        {
            string returnValue = String.Empty;

            if (null != clientContext && !string.IsNullOrWhiteSpace(clientAddressPath) && !string.IsNullOrWhiteSpace(oneNoteLocation) && !string.IsNullOrWhiteSpace(listName))
            {
                Uri    clientUrl   = new Uri(clientAddressPath);
                string oneNotePath = HttpContext.Current.Server.MapPath(Constants.ONENOTERELATIVEFILEPATH);
                byte[] oneNoteFile = System.IO.File.ReadAllBytes(oneNotePath);
                Web    web         = clientContext.Web;
                Microsoft.SharePoint.Client.File file = web.GetFolderByServerRelativeUrl(oneNoteLocation).Files.Add(new FileCreationInformation()
                {
                    Url           = string.Concat(listName, Constants.EXTENSIONONENOTETABLEOFCONTENT),
                    Overwrite     = true,
                    ContentStream = new IO.MemoryStream(oneNoteFile)
                });
                web.Update();
                clientContext.Load(file);
                clientContext.ExecuteQuery();
                ListItem oneNote = file.ListItemAllFields;
                oneNote["Title"] = oneNoteTitle;
                oneNote.Update();
                returnValue = string.Concat(clientUrl.Scheme, Constants.COLON, Constants.FORWARDSLASH, Constants.FORWARDSLASH, clientUrl.Authority, file.ServerRelativeUrl, Constants.WEBSTRING);
            }
            return(returnValue);
        }
 private static void AssignGroupPermissions(ClientContext clientContext, Web web)
 {
     if (null == clientContext)
     {
         throw new ArgumentNullException("clientContext");
     }
     if (null == web)
     {
         throw new ArgumentNullException("web");
     }
     try
     {
         var roleAssignments = web.RoleAssignments;
         clientContext.Load(roleAssignments);
         clientContext.ExecuteQuery();
         // Owners
         var owner     = web.RoleDefinitions.GetByType(RoleType.Administrator);
         var rdbOwners = new RoleDefinitionBindingCollection(clientContext)
         {
             owner
         };
         web.RoleAssignments.Add(web.AssociatedOwnerGroup, rdbOwners);
         web.Update();
         // Contributors.
         var contributor = web.RoleDefinitions.GetByType(RoleType.Contributor);
         var rdbMembers  = new RoleDefinitionBindingCollection(clientContext)
         {
             contributor
         };
         web.RoleAssignments.Add(web.AssociatedMemberGroup, rdbMembers);
         web.Update();
         // Readers
         var reader      = web.RoleDefinitions.GetByType(RoleType.Reader);
         var rdbVisitors = new RoleDefinitionBindingCollection(clientContext)
         {
             reader
         };
         web.RoleAssignments.Add(web.AssociatedVisitorGroup, rdbVisitors);
         web.Update();
         clientContext.ExecuteQuery();
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
         throw;
     }
 }
Beispiel #29
0
        public void SetProperty(ClientContext context, Web webToConfigure, KeyValuePair<string, string> property)
        {
            var webProperties = webToConfigure.AllProperties;
            webProperties[property.Key] = property.Value;

            webToConfigure.Update();
            context.ExecuteQuery();
        }
Beispiel #30
0
        static private void SetBingMapsKey()
        {
            ClientContext context = new ClientContext("https://bordahq.sharepoint.com/hq");
            Web           web     = context.Web;

            web.AllProperties["BING_MAPS_KEY"] = "AjSyOhKZ3wJzqrbCJyma41p8wKncW6gSl3aQii-Joj5vvMdjnGlcBuE8BZZSe5RY";
            web.Update();
            context.ExecuteQuery();
        }
Beispiel #31
0
 public void NuevaActividad_Aceptar(object sender, EventArgs e)
 {
     if (IsValid)
     {
         {
             Web.Update(); EndOperation(1);
         }
     }
 }
        private async Task SetInitialProjectStatusAsync(ClientContext ctx, Web web)
        {
            var allProperties = web.AllProperties;

            allProperties["ProjectStatus"] = "In Process";

            web.Update();
            ctx.ExecuteQuery();
        }
Beispiel #33
0
 public void Update()
 {
     if (_hasChanges)
     {
         _web.Update();
         _web.Context.ExecuteQuery();
         _hasChanges = false;
     }
 }
Beispiel #34
0
 private static void RecursivelyUpdateWebLogo(Web currentWeb)
 {
     Console.WriteLine("Changing " + currentWeb.Title + " site logo URL from " + currentWeb.SiteLogoUrl + " to " + siteLogoUrl + ".");
     Console.WriteLine();
     currentWeb.SiteLogoUrl = siteLogoUrl;
     currentWeb.Update();
     WebCollection subWebs = currentWeb.Webs;
     clientContext.Load(subWebs);
     clientContext.ExecuteQuery();
     foreach (Web subWeb in subWebs)
     {
         RecursivelyUpdateWebLogo(subWeb);
     }
 }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.IsMultilingual = true;
                web.Context.Load(web, w => w.SupportedUILanguageIds);
                web.Update();
                web.Context.ExecuteQuery();

                var isDirty = false;

                foreach (var id in web.SupportedUILanguageIds)
                {
                    var found = template.SupportedUILanguages.Any(sl => sl.LCID == id);

                    if (!found)
                    {
                        web.RemoveSupportedUILanguage(id);
                        isDirty = true;
                    }
                }
                if (isDirty)
                {
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                foreach (var id in template.SupportedUILanguages)
                {
                    web.AddSupportedUILanguage(id.LCID);
                }
                web.Update();
                web.Context.ExecuteQueryRetry();
            }

            return parser;
        }
        public static void SetPropertyBagValue(Web web, string key, string value)
        {
            var context = web.Context;

            if (!web.IsPropertyAvailable("AllProperties"))
            {
                context.Load(web);
                context.Load(web, w => w.AllProperties);
                context.ExecuteQueryWithTrace();
            }

            // weird, this is incorrect
            // https://lixuan0125.wordpress.com/2013/10/18/add-and-retrieve-property-bag-by-csom/

            // if (!web.AllProperties.FieldValues.ContainsKey(key))
            //    web.AllProperties.FieldValues.Add(key, value);
            //else

            web.AllProperties[key] = value;

            web.Update();
            context.ExecuteQueryWithTrace();
        }
Beispiel #37
0
        private void ApplyThemeToSite(Web hostWeb, Web newWeb)
        {
            // Let's first upload the contoso theme to host web, if it does not exist there
            newWeb.DeployThemeToSubWeb(hostWeb, "TechEd",
                            HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/TechEd/teched.spcolor")),
                            null,
                            HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/TechEd/bg.jpg")),
                            string.Empty);

            // Setting the Contoos theme to host web
            newWeb.SetThemeToWeb("TechEd");

            // Instance to site assets. Notice that this is using hard coded list name which only works in 1033 sites
            List assetLibrary = newWeb.Lists.GetByTitle("Site Assets");
            newWeb.Context.Load(assetLibrary, l => l.RootFolder);

            // Get the path to the file which we are about to deploy
            string logoFile = System.Web.Hosting.HostingEnvironment.MapPath(
                                string.Format("~/{0}", "Resources/Themes/TechEd/logo.png"));

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(logoFile);
            newFile.Url = "pnp.png";
            newFile.Overwrite = true;
            File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
            newWeb.Context.Load(uploadFile);
            newWeb.Context.ExecuteQuery();

            newWeb.AlternateCssUrl = newWeb.ServerRelativeUrl + "/SiteAssets/contoso.css";
            newWeb.SiteLogoUrl = newWeb.ServerRelativeUrl + "/SiteAssets/pnp.png";
            newWeb.Update();
            newWeb.Context.ExecuteQuery();
        }
        private static void UpdateSecurity(ClientContext ctx, Web web)
        {
            Group pscOwners = web.SiteGroups.GetByName("PSC Owners");
            Group pscMembers = web.SiteGroups.GetByName("PSC Members");
            Group pscVisitors = web.SiteGroups.GetByName("PSC Visitors");

            web.AssociateDefaultGroups(pscOwners, pscMembers, pscVisitors);
            web.Update();
            ctx.ExecuteQueryRetry();

            Group defaultOwners = web.SiteGroups.GetByName(web.Title + " Owners");
            Group defaultMembers = web.SiteGroups.GetByName(web.Title + " Members");
            Group defaultVisitors = web.SiteGroups.GetByName(web.Title + " Visitors");

            if (defaultOwners != null)
                web.SiteGroups.Remove(defaultOwners);
            if (defaultMembers != null)
                web.SiteGroups.Remove(defaultMembers);
            if (defaultVisitors != null)
                web.SiteGroups.Remove(defaultVisitors);

            try
            {
                web.Update();
                ctx.ExecuteQueryRetry();
            }
            catch (Exception)
            {
                //It's OK-- group doesn't exist
            }
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Changed by Paolo Pialorsi to embrace the new sub-site attributes for break role inheritance and copy role assignments
                // if this is a sub site then we're not provisioning security as by default security is inherited from the root site
                //if (web.IsSubSite() && !template.Security.BreakRoleInheritance)
                //{
                //    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning);
                //    return parser;
                //}

                if (web.IsSubSite() && template.Security.BreakRoleInheritance)
                {
                    web.BreakRoleInheritance(template.Security.CopyRoleAssignments, template.Security.ClearSubscopes);
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                var siteSecurity = template.Security;

                var ownerGroup = web.AssociatedOwnerGroup;
                var memberGroup = web.AssociatedMemberGroup;
                var visitorGroup = web.AssociatedVisitorGroup;


                web.Context.Load(ownerGroup, o => o.Title, o => o.Users);
                web.Context.Load(memberGroup, o => o.Title, o => o.Users);
                web.Context.Load(visitorGroup, o => o.Title, o => o.Users);

                web.Context.ExecuteQueryRetry();

                if (!ownerGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope, parser);
                }
                if (!memberGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope, parser);
                }
                if (!visitorGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope, parser);
                }

                foreach (var siteGroup in siteSecurity.SiteGroups)
                {
                    Group group;
                    var allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName));
                    web.Context.ExecuteQueryRetry();

                    string parsedGroupTitle = parser.ParseString(siteGroup.Title);
                    string parsedGroupOwner = parser.ParseString(siteGroup.Owner);
                    string parsedGroupDescription = parser.ParseString(siteGroup.Description);

                    if (!web.GroupExists(parsedGroupTitle))
                    {
                        scope.LogDebug("Creating group {0}", parsedGroupTitle);
                        group = web.AddGroup(
                            parsedGroupTitle,
                            parsedGroupDescription,
                            parsedGroupTitle == parsedGroupOwner);
                        group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                        group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                        group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;

                        if (parsedGroupTitle != parsedGroupOwner)
                        {
                            Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                            if (ownerPrincipal == null)
                            {
                                ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                            }
                            group.Owner = ownerPrincipal;

                        }
                        group.Update();
                        web.Context.Load(group, g => g.Id, g => g.Title);
                        web.Context.ExecuteQueryRetry();
                        parser.AddToken(new GroupIdToken(web, group.Title, group.Id));
                    }
                    else
                    {
                        group = web.SiteGroups.GetByName(parsedGroupTitle);
                        web.Context.Load(group,
                            g => g.Title,
                            g => g.Description,
                            g => g.AllowMembersEditMembership,
                            g => g.AllowRequestToJoinLeave,
                            g => g.AutoAcceptRequestToJoinLeave,
                            g => g.Owner.LoginName);
                        web.Context.ExecuteQueryRetry();
                        var isDirty = false;
                        if (!String.IsNullOrEmpty(group.Description) && group.Description != parsedGroupDescription)
                        {
                            group.Description = parsedGroupDescription;
                            isDirty = true;
                        }
                        if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership)
                        {
                            group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                            isDirty = true;
                        }
                        if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave)
                        {
                            group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave)
                        {
                            group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.Owner.LoginName != parsedGroupOwner)
                        {
                            if (parsedGroupTitle != parsedGroupOwner)
                            {
                                Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                                if (ownerPrincipal == null)
                                {
                                    ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                                }
                                group.Owner = ownerPrincipal;
                            }
                            else
                            {
                                group.Owner = group;
                            }
                            isDirty = true;
                        }
                        if (isDirty)
                        {
                            scope.LogDebug("Updating existing group {0}", group.Title);
                            group.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                    if (group != null && siteGroup.Members.Any())
                    {
                        AddUserToGroup(web, group, siteGroup.Members, scope, parser);
                    }
                }

                foreach (var admin in siteSecurity.AdditionalAdministrators)
                {
                    var parsedAdminName = parser.ParseString(admin.Name);
                    var user = web.EnsureUser(parsedAdminName);
                    user.IsSiteAdmin = true;
                    user.Update();
                    web.Context.ExecuteQueryRetry();
                }

                if (!web.IsSubSite() && siteSecurity.SiteSecurityPermissions != null) // Only manage permissions levels on sitecol level
                {
                    var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any())
                    {
                        foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions)
                        {
                            var roleDefinitions = existingRoleDefinitions as RoleDefinition[] ?? existingRoleDefinitions.ToArray();
                            var siteRoleDefinition = roleDefinitions.FirstOrDefault(erd => erd.Name == parser.ParseString(templateRoleDefinition.Name));
                            if (siteRoleDefinition == null)
                            {
                                scope.LogDebug("Creation role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                var roleDefinitionCI = new RoleDefinitionCreationInformation();
                                roleDefinitionCI.Name = parser.ParseString(templateRoleDefinition.Name);
                                roleDefinitionCI.Description = parser.ParseString(templateRoleDefinition.Description);
                                BasePermissions basePermissions = new BasePermissions();

                                foreach (var permission in templateRoleDefinition.Permissions)
                                {
                                    basePermissions.Set(permission);
                                }

                                roleDefinitionCI.BasePermissions = basePermissions;

                                web.RoleDefinitions.Add(roleDefinitionCI);
                                web.Context.ExecuteQueryRetry();
                            }
                            else
                            {
                                var isDirty = false;
                                if (siteRoleDefinition.Description != parser.ParseString(templateRoleDefinition.Description))
                                {
                                    siteRoleDefinition.Description = parser.ParseString(templateRoleDefinition.Description);
                                    isDirty = true;
                                }
                                var templateBasePermissions = new BasePermissions();
                                templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p));
                                if (siteRoleDefinition.BasePermissions != templateBasePermissions)
                                {
                                    isDirty = true;
                                    foreach (var permission in templateRoleDefinition.Permissions)
                                    {
                                        siteRoleDefinition.BasePermissions.Set(permission);
                                    }
                                }
                                if (isDirty)
                                {
                                    scope.LogDebug("Updating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                    siteRoleDefinition.Update();
                                    web.Context.ExecuteQueryRetry();
                                }
                            }
                        }
                    }

                    var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions);
                    var groups = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any())
                    {
                        foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments)
                        {
                            Principal principal = groups.FirstOrDefault(g => g.LoginName == parser.ParseString(roleAssignment.Principal));
                            if (principal == null)
                            {
                                principal = web.EnsureUser(parser.ParseString(roleAssignment.Principal));
                            }

                            var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context);

                            var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == parser.ParseString(roleAssignment.RoleDefinition));

                            if (roleDefinition != null)
                            {
                                roleDefinitionBindingCollection.Add(roleDefinition);
                            }
                            web.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                }
            }
            return parser;
        }
Beispiel #40
0
        /// <summary>
        /// Uploads site logo to host web
        /// </summary>
        /// <param name="web"></param>
        public static void SetLogoToWeb(Web web, string logoFile)
        {
            // Instance to site assets
            List assetLibrary = web.Lists.GetByTitle("Site Assets");
            web.Context.Load(assetLibrary, l => l.RootFolder);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(logoFile);
            newFile.Url = Path.GetFileName(logoFile);
            newFile.Overwrite = true;
            Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();

            // Load relative URL
            web.Context.Load(web, w => w.ServerRelativeUrl);
            web.Context.ExecuteQuery();

            // Set the properties accordingly
            web.SiteLogoUrl = web.ServerRelativeUrl + "/SiteAssets/" + Path.GetFileName(logoFile);
            web.Update();
            web.Context.ExecuteQuery();
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.ComposedLook != null &&
                    !template.ComposedLook.Equals(ComposedLook.Empty))
                {
                    bool executeQueryNeeded = false;

                    // Apply alternate CSS
                    if (!string.IsNullOrEmpty(template.ComposedLook.AlternateCSS))
                    {
                        var alternateCssUrl = parser.ParseString(template.ComposedLook.AlternateCSS);
                        web.AlternateCssUrl = alternateCssUrl;
                        web.Update();
                        executeQueryNeeded = true;
                    }

                    // Apply Site logo
                    if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo))
                    {
                        var siteLogoUrl = parser.ParseString(template.ComposedLook.SiteLogo);
                        web.SiteLogoUrl = siteLogoUrl;
                        web.Update();
                        executeQueryNeeded = true;
                    }

                    if (executeQueryNeeded)
                    {
                        web.Context.ExecuteQueryRetry();
                    }

                    if (String.IsNullOrEmpty(template.ComposedLook.ColorFile) &&
                        String.IsNullOrEmpty(template.ComposedLook.FontFile) &&
                        String.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
                    {
                        // Apply OOB theme
                        web.SetComposedLookByUrl(template.ComposedLook.Name);
                    }
                    else
                    {
                        // Apply custom theme
                        string colorFile = null;
                        if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile))
                        {
                            colorFile = parser.ParseString(template.ComposedLook.ColorFile);
                        }
                        string backgroundFile = null;
                        if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
                        {
                            backgroundFile = parser.ParseString(template.ComposedLook.BackgroundFile);
                        }
                        string fontFile = null;
                        if (!string.IsNullOrEmpty(template.ComposedLook.FontFile))
                        {
                            fontFile = parser.ParseString(template.ComposedLook.FontFile);
                        }

                        string masterUrl = null;
                        if (!string.IsNullOrEmpty(template.ComposedLook.MasterPage))
                        {
                            masterUrl = parser.ParseString(template.ComposedLook.MasterPage);
                        }
                        web.CreateComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
                        web.SetComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
                    }
                }
            }
            return parser;
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.WebSettings != null)
                {
                    var webSettings = template.WebSettings;
#if !CLIENTSDKV15
                    web.NoCrawl = webSettings.NoCrawl;

                    String requestAccessEmailValue = parser.ParseString(webSettings.RequestAccessEmail);
                    if (!String.IsNullOrEmpty(requestAccessEmailValue) && requestAccessEmailValue.Length >= 255)
                    {
                        requestAccessEmailValue = requestAccessEmailValue.Substring(0, 255);
                    }
                    if (!String.IsNullOrEmpty(requestAccessEmailValue))
                    {
                        web.RequestAccessEmail = requestAccessEmailValue;
                    }
#endif
                    var masterUrl = parser.ParseString(webSettings.MasterPageUrl);
                    if (!string.IsNullOrEmpty(masterUrl))
                    {
                        web.MasterUrl = masterUrl;
                    }
                    var customMasterUrl = parser.ParseString(webSettings.CustomMasterPageUrl);
                    if (!string.IsNullOrEmpty(customMasterUrl))
                    {
                        web.CustomMasterUrl = customMasterUrl;
                    }
                    web.Description = parser.ParseString(webSettings.Description);
                    web.SiteLogoUrl = parser.ParseString(webSettings.SiteLogo);
                    var welcomePage = parser.ParseString(webSettings.WelcomePage);
                    if (!string.IsNullOrEmpty(welcomePage))
                    {
                        web.RootFolder.WelcomePage = welcomePage;
                        web.RootFolder.Update();
                    }
                    web.AlternateCssUrl = parser.ParseString(webSettings.AlternateCSS);

                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }
            }

            return parser;
        }
Beispiel #43
0
 private static void SetAlternateCssUrlForWeb(ClientContext context, ShWeb configWeb, Web webToConfigure)
 {
     if (!string.IsNullOrEmpty(configWeb.AlternateCssUrl))
     {
         Log.Debug("Setting AlternateCssUrl for web " + configWeb.Name);
         webToConfigure.AlternateCssUrl = ContentUploadManager.GetPropertyValueWithTokensReplaced(configWeb.AlternateCssUrl, context);
         webToConfigure.Update();
         context.ExecuteQuery();
     }
 }
Beispiel #44
0
        void ProvisionSample3(Web web)
        {
            //Delete list if it already exists
            ListCollection lists = web.Lists;
            IEnumerable<List> results = web.Context.LoadQuery<List>(lists.Where(list => list.Title == "CSR-Confidential-Documents"));
            web.Context.ExecuteQuery();
            List existingList = results.FirstOrDefault();

            if (existingList != null)
            {
                existingList.DeleteObject();
                web.Context.ExecuteQuery();
            }

            //Create list
            ListCreationInformation creationInfo = new ListCreationInformation();
            creationInfo.Title = "CSR-Confidential-Documents";
            creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary;
            List newlist = web.Lists.Add(creationInfo);
            newlist.Update();
            web.Context.Load(newlist);
            web.Context.Load(newlist.Fields);
            web.Context.ExecuteQuery();

            //Add field
            FieldCollection fields = web.Fields;
            web.Context.Load(fields, fc => fc.Include(f => f.InternalName));
            web.Context.ExecuteQuery();
            Field field = fields.FirstOrDefault(f => f.InternalName == "Confidential");
            if (field == null)
            {
                field = newlist.Fields.AddFieldAsXml("<Field Type=\"YES/NO\" Name=\"Confidential\" DisplayName=\"Confidential\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\" />", false, AddFieldOptions.DefaultValue);
                web.Update();
                web.Context.ExecuteQuery();
            }
            newlist.Fields.Add(field);
            newlist.Update();
            web.Context.ExecuteQuery();

            //Upload sample docs
            UploadTempDoc(newlist, "Doc1.doc");
            UploadTempDoc(newlist, "Doc2.doc");
            UploadTempDoc(newlist, "Doc3.ppt");
            UploadTempDoc(newlist, "Doc4.ppt");
            UploadTempDoc(newlist, "Doc5.xls");
            UploadTempDoc(newlist, "Doc6.xls");
            Microsoft.SharePoint.Client.ListItem item1 = newlist.GetItemById(1);
            item1["Confidential"] = 1;
            item1.Update();
            Microsoft.SharePoint.Client.ListItem item2 = newlist.GetItemById(2);
            item2["Confidential"] = 1;
            item2.Update();
            Microsoft.SharePoint.Client.ListItem item3 = newlist.GetItemById(3);
            item3["Confidential"] = 0;
            item3.Update();
            Microsoft.SharePoint.Client.ListItem item4 = newlist.GetItemById(4);
            item4["Confidential"] = 1;
            item4.Update();
            Microsoft.SharePoint.Client.ListItem item5 = newlist.GetItemById(5);
            item5["Confidential"] = 0;
            item5.Update();
            Microsoft.SharePoint.Client.ListItem item6 = newlist.GetItemById(6);
            item6["Confidential"] = 1;
            item6.Update();
            web.Context.ExecuteQuery();

            //Create sample view
            ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation();
            sampleViewCreateInfo.Title = "CSR Sample View";
            sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkFilename", "Modified", "Editor", "Confidential" };
            sampleViewCreateInfo.SetAsDefaultView = true;
            Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo);
            sampleView.Update();
            web.Context.Load(newlist, l => l.DefaultViewUrl);
            web.Context.ExecuteQuery();

            //Register JS files via JSLink properties
            RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/ConfidentialDocuments.js");
        }
 /// <summary>
 /// Upload helper function for uploading documents to SharePoint library.
 /// </summary>
 /// <param name="folderPath">Folder path of Document Library</param>
 /// <param name="listResponse">SharePoint list response</param>
 /// <param name="clientContext">Client context object for connection between SP & client</param>
 /// <param name="documentLibraryName">Name of document library in which upload is to be done</param>
 /// <param name="web">Object of site</param>
 /// <param name="folderName">Target folder name where file needs to be uploaded.</param>
 /// <param name="uploadFile">Object having file creation information</param>
 /// <returns>It returns true if upload is successful else false</returns>
 private static bool DocumentUpload(string folderPath, IList<string> listResponse, ClientContext clientContext, string documentLibraryName, Web web, string folderName, FileCreationInformation uploadFile)
 {
     bool isUploadSuccessful = false;
     using (clientContext)
     {
         if (UIUtility.FolderExists(folderPath, clientContext, documentLibraryName))
         {
             Folder destionationFolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
             clientContext.Load(destionationFolder);
             clientContext.ExecuteQuery();
             Microsoft.SharePoint.Client.File fileToUpload = destionationFolder.Files.Add(uploadFile);
             destionationFolder.Update();
             web.Update();
             clientContext.Load(fileToUpload);
             clientContext.ExecuteQuery();
             isUploadSuccessful = true;
         }
         else
         {
             listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}",
                                         string.Format(CultureInfo.InvariantCulture, ConstantStrings.FolderStructureModified, folderName),
                                         ConstantStrings.DOLLAR, folderName));
         }
     }
     return isUploadSuccessful;
 }
        /// <summary>
        /// Removes a property bag value
        /// </summary>
        /// <param name="web">The web to process</param>
        /// <param name="key">They key to remove</param>
        /// <param name="checkIndexed"></param>
        private static void RemovePropertyBagValueInternal(Web web, string key, bool checkIndexed)
        {
            // In order to remove a property from the property bag, remove it both from the AllProperties collection by setting it to null
            // -and- by removing it from the FieldValues collection. Bug in CSOM?
            web.AllProperties[key] = null;
            web.AllProperties.FieldValues.Remove(key);

            web.Update();

            web.Context.ExecuteQueryRetry();
            if (checkIndexed)
                RemoveIndexedPropertyBagKey(web, key); // Will only remove it if it exists as an indexed property
        }
Beispiel #47
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {

            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ComposedLooks);
            if (template.ComposedLook != null &&
                !template.ComposedLook.Equals(ComposedLook.Empty))
            {
                bool executeQueryNeeded = false;

                // Apply alternate CSS
                if (!string.IsNullOrEmpty(template.ComposedLook.AlternateCSS))
                {
                    var alternateCssUrl = template.ComposedLook.AlternateCSS.ToParsedString();
                    web.AlternateCssUrl = alternateCssUrl;
                    web.Update();
                    executeQueryNeeded = true;
                }

                // Apply Site logo
                if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo))
                {
                    var siteLogoUrl = template.ComposedLook.SiteLogo.ToParsedString();
                    web.SiteLogoUrl = siteLogoUrl;
                    web.Update();
                    executeQueryNeeded = true;
                }

                if (executeQueryNeeded)
                {
                    web.Context.ExecuteQueryRetry();
                }

                if (String.IsNullOrEmpty(template.ComposedLook.ColorFile) &&
                    String.IsNullOrEmpty(template.ComposedLook.FontFile) &&
                    String.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
                {
                    // Apply OOB theme
                    web.SetComposedLookByUrl(template.ComposedLook.Name);
                }
                else
                {
                    // Apply custom theme
                    string colorFile = null;
                    if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile))
                    {
                        colorFile = template.ComposedLook.ColorFile.ToParsedString();
                    }
                    string backgroundFile = null;
                    if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
                    {
                        backgroundFile = template.ComposedLook.BackgroundFile.ToParsedString();
                    }
                    string fontFile = null;
                    if (!string.IsNullOrEmpty(template.ComposedLook.FontFile))
                    {
                        fontFile = template.ComposedLook.FontFile.ToParsedString();
                    }

                    string masterUrl = null;
                    if (!string.IsNullOrEmpty(template.ComposedLook.MasterPage))
                    {
                        masterUrl = template.ComposedLook.MasterPage.ToParsedString();
                    }
                    web.CreateComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
                    web.SetComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
                }
            }
        }
 public void SetDepartmentTitle(ClientContext context, Web web)
 {
     web.Title = "Department A";
     web.Update();
     context.ExecuteQuery();
 }
Beispiel #49
0
        /// <summary>
        /// Method to add users to current group
        /// </summary>
        /// <param name="clientContext">client context</param>
        /// <param name="site">site object</param>
        /// <param name="currentGrp">group object</param>
        /// <param name="item">data storage</param>
        private static void AddUsersToCurrentGroup(ClientContext clientContext, Web site, Group currentGrp, DataStorage item)
        {
            string[] allUserEmail = item.Members.Split(new char[] { ';' });

            Console.WriteLine("Adding users to this group");
            List<User> allUsers = new List<User>();
            foreach (string userEmail in allUserEmail)
            {
                if (!string.IsNullOrEmpty(userEmail))
                {
                    User user = clientContext.Web.EnsureUser(userEmail.Trim());
                    clientContext.Load(user);
                    clientContext.ExecuteQuery();
                    allUsers.Add(user);
                }
            }
            foreach (User user in allUsers)
            {
                currentGrp.Users.AddUser(user);
            }
            site.Update();
            clientContext.Load(currentGrp);
            clientContext.ExecuteQuery();
            Console.WriteLine("Successfully added users to group " + currentGrp.Title);
        }
Beispiel #50
0
        /// <summary>
        /// Method to check if a group exists and create a new one
        /// </summary>
        /// <param name="collGroup">group collection</param>
        /// <param name="item">data storage</param>
        /// <param name="site">site object</param>
        /// <param name="clientContext">client context</param>
        /// <returns>returns group object</returns>
        private static Group CheckAndCreateGroup(GroupCollection collGroup, DataStorage item, Web site, ClientContext clientContext)
        {
            Group currentGrp = (from grp in collGroup where grp.Title == item.GroupName select grp).FirstOrDefault();
            if (currentGrp != null)
            {
                Console.WriteLine("Deleting group " + item.GroupName + " as it is already present");
                collGroup.Remove(currentGrp);
            }

            //Creating group
            Console.WriteLine("Creating group " + item.GroupName);
            GroupCreationInformation grpInfo = new GroupCreationInformation();
            grpInfo.Title = item.GroupName;
            grpInfo.Description = item.GroupDesc;
            collGroup.Add(grpInfo);
            site.Update();
            clientContext.Load(collGroup);
            clientContext.ExecuteQuery();
            Console.WriteLine("Successfully created group " + item.GroupName);
            currentGrp = (from grp in collGroup where grp.Title == item.GroupName select grp).FirstOrDefault();
            return currentGrp;
        }
Beispiel #51
0
        /// <summary>
        /// Uploads used CSS and site logo to host web
        /// </summary>
        /// <param name="web"></param>
        public void UploadAndSetLogoToSite(Web web, string pathToLogo)
        {
            // Load for basic properties
            web.Context.Load(web);
            web.Context.ExecuteQuery();

            // Instance to site assets
            List assetLibrary = web.Lists.GetByTitle("Site Assets");
            web.Context.Load(assetLibrary, l => l.RootFolder);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(pathToLogo);
            newFile.Url = "pnp.png";
            newFile.Overwrite = true;
            Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);

            // Set custom image as the logo 
            web.SiteLogoUrl = web.ServerRelativeUrl + "/SiteAssets/pnp.png";
            web.Update();
            web.Context.ExecuteQuery();
        }
Beispiel #52
0
        /// <summary>
        /// Sets a key/value pair in the web property bag
        /// </summary>
        /// <param name="web">Web that will hold the property bag entry</param>
        /// <param name="key">Key for the property bag entry</param>
        /// <param name="value">Value for the property bag entry</param>
        private static void SetPropertyBagValueInternal(Web web, string key, object value)
        {
            var props = web.AllProperties;
            web.Context.Load(props);
            web.Context.ExecuteQuery();

            props[key] = value;

            web.Update();
            web.Context.ExecuteQuery();
        }
Beispiel #53
0
        public static void SetMasterPages(Web web, MasterPageInfo mpi, bool isRoot)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Setting Master Pages to: {0} & {1}...", mpi.MasterPageUrl, mpi.CustomMasterPageUrl), false);

                Logger.LogInfoMessage(String.Format("MasterUrl (before): {0}", web.MasterUrl), false);
                Logger.LogInfoMessage(String.Format("CustomMasterUrl (before): {0}", web.CustomMasterUrl), false);

                web.Context.Load(web.AllProperties);
                web.Context.ExecuteQuery();

                web.MasterUrl = mpi.MasterPageUrl;
                web.CustomMasterUrl = mpi.CustomMasterPageUrl;
                web.AllProperties[Constants.PropertyBagInheritMaster] = ((!isRoot && mpi.InheritMaster) ? "True" : "False");
                web.AllProperties[Constants.PropertyBagInheritCustomMaster] = ((!isRoot && mpi.InheritCustomMaster) ? "True" : "False");
                web.Update();
                web.Context.ExecuteQuery();

                Logger.LogSuccessMessage(String.Format("MasterUrl (after): {0}", web.MasterUrl), false);
                Logger.LogSuccessMessage(String.Format("CustomMasterUrl (after): {0}", web.CustomMasterUrl), false);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("SetMasterPages() failed for {0}: Error={1}", web.Url, ex.Message), false);
            }
        }
Beispiel #54
0
 /// <summary>
 /// Upload helper function for uploading documents to SharePoint library.
 /// </summary>
 /// <param name="folderPath">Folder path of Document Library</param>
 /// <param name="listResponse">SharePoint list response</param>
 /// <param name="clientContext">Client context object for connection between SP & client</param>
 /// <param name="documentLibraryName">Name of document library in which upload is to be done</param>
 /// <param name="web">Object of site</param>
 /// <param name="folderName">Target folder name where file needs to be uploaded.</param>
 /// <param name="uploadFile">Object having file creation information</param>
 /// <returns>It returns true if upload is successful else false</returns>
 private GenericResponseVM DocumentUpload(string folderPath, IList<string> listResponse, ClientContext clientContext, string documentLibraryName, Web web, string folderName, FileCreationInformation uploadFile)
 {            
     GenericResponseVM genericResponse = null;
     using (clientContext)
     {
         if (FolderExists(folderPath, clientContext, documentLibraryName))
         {
             Folder destionationFolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
             clientContext.Load(destionationFolder);
             clientContext.ExecuteQuery();
             Microsoft.SharePoint.Client.File fileToUpload = destionationFolder.Files.Add(uploadFile);
             destionationFolder.Update();
             web.Update();
             clientContext.Load(fileToUpload);
             clientContext.ExecuteQuery();                    
         }
         else
         {                   
             genericResponse = new GenericResponseVM()
             {
                 Code = errorSettings.FolderStructureModified,
                 Value = folderName,
                 IsError = true
             };
         }
     }
     return genericResponse;
 }
        private void DeployWebWorkflowAssociationDefinition(WebModelHost modelHost, Web web, WorkflowAssociationDefinition definition)
        {
            var context = web.Context;
            var existingWorkflowAssotiation = FindExistringWorkflowAssotiation(modelHost, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = existingWorkflowAssotiation,
                ObjectType = typeof(WorkflowAssociation),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            if (existingWorkflowAssotiation == null
                ||
                (existingWorkflowAssotiation.ServerObjectIsNull.HasValue &&
                 existingWorkflowAssotiation.ServerObjectIsNull.Value))
            {
                var workflowTemplate = GetWorkflowTemplate(modelHost, definition);

                if (workflowTemplate == null ||
                    (workflowTemplate.ServerObjectIsNull.HasValue && workflowTemplate.ServerObjectIsNull.Value))
                {
                    throw new SPMeta2Exception(
                        string.Format("Cannot find workflow template by definition:[{0}]", definition));
                }

                var historyList = web.QueryAndGetListByTitle(definition.HistoryListTitle);
                var taskList = web.QueryAndGetListByTitle(definition.TaskListTitle);

                var newWorkflowAssotiation = web.WorkflowAssociations.Add(new WorkflowAssociationCreationInformation
                {
                    Name = definition.Name,
                    Template = workflowTemplate,
                    HistoryList = historyList,
                    TaskList = taskList
                });

                MapProperties(definition, newWorkflowAssotiation);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newWorkflowAssotiation,
                    ObjectType = typeof(WorkflowAssociation),
                    ObjectDefinition = definition,
                    ModelHost = modelHost
                });

                web.Update();
                context.ExecuteQueryWithTrace();
            }
            else
            {
                MapProperties(definition, existingWorkflowAssotiation);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = existingWorkflowAssotiation,
                    ObjectType = typeof(WorkflowAssociation),
                    ObjectDefinition = definition,
                    ModelHost = modelHost
                });

                // no update
                // gives weird null ref exception

                // Enhance WorkflowAssociationDefinition - add more tests on updatability #871
                // https://github.com/SubPointSolutions/spmeta2/issues/871

                //existingWorkflowAssotiation.Update();
                //web.Update();
                context.ExecuteQueryWithTrace();
            }
        }
        private void DeployAtWebLevel(object modelHost, Web web, SearchSettingsDefinition definition)
        {
            var csomModelHost = modelHost.WithAssertAndCast<CSOMModelHostBase>("modelHost", value => value.RequireNotNull());

            var context = web.Context;

            context.Load(web);
            context.Load(web, w => w.AllProperties);

            context.ExecuteQueryWithTrace();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = web,
                ObjectType = typeof(Web),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            var searchSettings = GetCurrentSearchConfigAtWebLevel(web);

            if (searchSettings != null)
            {
                if (definition.UseParentResultsPageUrl.HasValue)
                    searchSettings.Inherit = definition.UseParentResultsPageUrl.Value;

                if (!string.IsNullOrEmpty(definition.UseCustomResultsPageUrl))
                {
                    var url = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                    {
                        Context = csomModelHost,
                        Value = definition.UseCustomResultsPageUrl
                    }).Value;

                    searchSettings.ResultsPageAddress = url;
                }

                SetCurrentSearchConfigAtWebLevel(csomModelHost, web, searchSettings);
            }

            if (!string.IsNullOrEmpty(definition.SearchCenterUrl))
            {
                SetSearchCenterUrlAtWebLevel(csomModelHost, web, definition.SearchCenterUrl);
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = web,
                ObjectType = typeof(Web),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            web.Update();
            context.ExecuteQueryWithTrace();
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser,
            ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;

                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                foreach (PublishingPage page in template.Publishing.PublishingPages)
                {
                    string parsedFileName = parser.ParseString(page.FileName);
                    string parsedFullFileName = parser.ParseString(page.FullFileName);

                    Microsoft.SharePoint.Client.Publishing.PublishingPage existingPage =
                        web.GetPublishingPage(parsedFileName + ".aspx");

                    if (!web.IsPropertyAvailable("RootFolder"))
                    {
                        web.Context.Load(web.RootFolder);
                        web.Context.ExecuteQueryRetry();
                    }

                    if (existingPage != null && existingPage.ServerObjectIsNull.Value == false)
                    {
                        if (!page.Overwrite)
                        {
                            scope.LogDebug(
                                CoreResources.Provisioning_ObjectHandlers_PublishingPages_Skipping_As_Overwrite_false,
                                parsedFileName);
                            continue;
                        }

                        if (page.WelcomePage && web.RootFolder.WelcomePage.Contains(parsedFullFileName))
                        {
                            //set the welcome page to a Temp page to allow page deletion
                            web.RootFolder.WelcomePage = "home.aspx";
                            web.RootFolder.Update();
                            web.Update();
                            context.ExecuteQueryRetry();
                        }
                        existingPage.ListItem.DeleteObject();
                        context.ExecuteQuery();
                    }

                    web.AddPublishingPage(
                        parsedFileName,
                        page.Layout,
                        parser.ParseString(page.Title)
                        );
                    Microsoft.SharePoint.Client.Publishing.PublishingPage publishingPage =
                        web.GetPublishingPage(parsedFullFileName);
                    Microsoft.SharePoint.Client.File pageFile = publishingPage.ListItem.File;
                    pageFile.CheckOut();

                    if (page.Properties != null && page.Properties.Count > 0)
                    {
                        context.Load(pageFile, p => p.Name, p => p.CheckOutType);
                        context.ExecuteQueryRetry();
                        var parsedProperties = page.Properties.ToDictionary(p => p.Key, p => parser.ParseString(p.Value));
                        pageFile.SetFileProperties(parsedProperties, false);
                    }

                    if (page.WebParts != null && page.WebParts.Count > 0)
                    {
                        Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager mgr =
                            pageFile.GetLimitedWebPartManager(
                                Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);
                        context.Load(mgr);
                        context.ExecuteQueryRetry();

                        AddWebPartsToPublishingPage(page, context, mgr, parser);
                    }

                    List pagesLibrary = publishingPage.ListItem.ParentList;
                    context.Load(pagesLibrary);
                    context.ExecuteQueryRetry();

                    ListItem pageItem = publishingPage.ListItem;
                    web.Context.Load(pageItem, p => p.File.CheckOutType);
                    web.Context.ExecuteQueryRetry();

                    if (pageItem.File.CheckOutType != CheckOutType.None)
                    {
                        pageItem.File.CheckIn(String.Empty, CheckinType.MajorCheckIn);
                    }

                    if (page.Publish && pagesLibrary.EnableMinorVersions)
                    {
                        pageItem.File.Publish(String.Empty);
                        if (pagesLibrary.EnableModeration)
                        {
                            pageItem.File.Approve(String.Empty);
                        }
                    }

                    if (page.WelcomePage)
                    {
                        SetWelcomePage(web, pageFile);
                    }

                    context.ExecuteQueryRetry();
                }
            }
            return parser;
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.WebSettings != null)
                {
                    // Check if this is not a noscript site as we're not allowed to update some properties
                    bool isNoScriptSite = web.IsNoScriptSite();

                    web.EnsureProperty(w => w.HasUniqueRoleAssignments);

                    var webSettings = template.WebSettings;
            #if !ONPREMISES
                    if (!isNoScriptSite)
                    {
                        web.NoCrawl = webSettings.NoCrawl;
                    }
                    else
                    {
                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipNoCrawlUpdate);
                    }

                    if (!web.IsSubSite() || (web.IsSubSite() && web.HasUniqueRoleAssignments))
                    {
                        String requestAccessEmailValue = parser.ParseString(webSettings.RequestAccessEmail);
                        if (!String.IsNullOrEmpty(requestAccessEmailValue) && requestAccessEmailValue.Length >= 255)
                        {
                            requestAccessEmailValue = requestAccessEmailValue.Substring(0, 255);
                        }
                        if (!String.IsNullOrEmpty(requestAccessEmailValue))
                        {
                            web.RequestAccessEmail = requestAccessEmailValue;

                            web.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
            #endif
                    var masterUrl = parser.ParseString(webSettings.MasterPageUrl);
                    if (!string.IsNullOrEmpty(masterUrl))
                    {
                        if (!isNoScriptSite)
                        {
                            web.MasterUrl = masterUrl;
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipMasterPageUpdate);
                        }
                    }
                    var customMasterUrl = parser.ParseString(webSettings.CustomMasterPageUrl);
                    if (!string.IsNullOrEmpty(customMasterUrl))
                    {
                        if (!isNoScriptSite)
                        {
                            web.CustomMasterUrl = customMasterUrl;
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipCustomMasterPageUpdate);
                        }
                    }
                    if (webSettings.Title != null)
                    {
                        web.Title = parser.ParseString(webSettings.Title);
                    }
                    if (webSettings.Description != null)
                    {
                        web.Description = parser.ParseString(webSettings.Description);
                    }
                    if (webSettings.SiteLogo != null)
                    {
                        web.SiteLogoUrl = parser.ParseString(webSettings.SiteLogo);
                    }
                    var welcomePage = parser.ParseString(webSettings.WelcomePage);
                    if (!string.IsNullOrEmpty(welcomePage))
                    {
                        web.RootFolder.WelcomePage = welcomePage;
                        web.RootFolder.Update();
                    }
                    if (webSettings.AlternateCSS != null)
                    {
                        web.AlternateCssUrl = parser.ParseString(webSettings.AlternateCSS);
                    }

                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }
            }

            return parser;
        }
        /// <summary>
        /// Sets a key/value pair in the web property bag
        /// </summary>
        /// <param name="web">Web that will hold the property bag entry</param>
        /// <param name="key">Key for the property bag entry</param>
        /// <param name="value">Value for the property bag entry</param>
        private static void SetPropertyBagValueInternal(Web web, string key, object value)
        {
            web.AllProperties.ClearObjectData();

            var props = web.AllProperties;

            // Get the value, if the web properties are already loaded
            if (props.FieldValues.Count > 0)
            {
                props[key] = value;
            }
            else
            {
                // Load the web properties
                web.Context.Load(props);
                web.Context.ExecuteQueryRetry();

                props[key] = value;
            }

            web.Update();
            web.Context.ExecuteQueryRetry();
        }
Beispiel #60
0
        private void ForceRecrawlOf(Web web, ClientContext context)
        {
            Log.Info("Scheduling full recrawl of: " + web.Url);
            context.Credentials = _credentials;

            context.Load(web, x => x.AllProperties, x => x.Webs);
            context.ExecuteQuery();
            var version = 0;
            var subWebs = web.Webs;

            var allProperties = web.AllProperties;
            if (allProperties.FieldValues.ContainsKey("vti_searchversion"))
            {
                version = (int)allProperties["vti_searchversion"];
            }
            version++;
            allProperties["vti_searchversion"] = version;
            web.Update();
            context.ExecuteQuery();
            foreach (var subWeb in subWebs)
            {
                ForceRecrawlOf(subWeb, context);
            }
        }