protected override void ExecuteCmdlet()
        {
            Func <TenantOperationMessage, bool> timeoutFunction = TimeoutFunction;

            Tenant.SetSiteProperties(Url, title: Title,
                                     sharingCapability: Sharing,
                                     storageMaximumLevel: StorageMaximumLevel,
                                     storageWarningLevel: StorageWarningLevel,
                                     allowSelfServiceUpgrade: AllowSelfServiceUpgrade,
                                     userCodeMaximumLevel: UserCodeMaximumLevel,
                                     userCodeWarningLevel: UserCodeWarningLevel,
                                     noScriptSite: NoScriptSite,
                                     wait: Wait, timeoutFunction: Wait ? timeoutFunction : null
                                     );

            if (Owners != null && Owners.Count > 0)
            {
                var admins = new List <UserEntity>();
                foreach (var owner in Owners)
                {
                    var userEntity = new UserEntity {
                        LoginName = owner
                    };
                    admins.Add(userEntity);
                }
                Tenant.AddAdministrators(admins, new Uri(Url));
            }
            if (MyInvocation.BoundParameters.ContainsKey("LockState"))
            {
                Tenant.SetSiteLockState(Url, LockState, Wait, Wait ? timeoutFunction : null);
            }
        }
        public static void AddAdministratorsTenant(this Web web, IEnumerable<UserEntity> adminLogins, Uri siteUrl, bool addToOwnersGroup = false)
        {
            Tenant tenant = new Tenant(web.Context);

            tenant.AddAdministrators(adminLogins, siteUrl, addToOwnersGroup);

        }
Esempio n. 3
0
        protected override void ExecuteCmdlet()
        {
            Tenant.SetSiteProperties(Url, title: Title, sharingCapability: Sharing, storageMaximumLevel: StorageMaximumLevel, allowSelfServiceUpgrade: AllowSelfServiceUpgrade, userCodeMaximumLevel: UserCodeMaximumLevel, userCodeWarningLevel: UserCodeWarningLevel);

            if (Owners != null && Owners.Count > 0)
            {
                var admins = new List <UserEntity>();
                foreach (var owner in Owners)
                {
                    var userEntity = new UserEntity {
                        LoginName = owner
                    };
                    admins.Add(userEntity);
                }
                Tenant.AddAdministrators(admins, new Uri(Url));
            }
        }
Esempio n. 4
0
        protected override void ExecuteCmdlet()
        {
            Func <TenantOperationMessage, bool> timeoutFunction = TimeoutFunction;

            if (LockState.HasValue)
            {
                Tenant.SetSiteLockState(Url, LockState.Value, Wait, Wait ? timeoutFunction : null);
                WriteWarning("You changed the lockstate of a site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect.");
            }

            if (!LockState.HasValue)
            {
                Tenant.SetSiteProperties(Url, title: Title,
                                         sharingCapability: Sharing,
                                         storageMaximumLevel: StorageMaximumLevel,
                                         storageWarningLevel: StorageWarningLevel,
                                         allowSelfServiceUpgrade: AllowSelfServiceUpgrade,
                                         userCodeMaximumLevel: UserCodeMaximumLevel,
                                         userCodeWarningLevel: UserCodeWarningLevel,
                                         noScriptSite: NoScriptSite,
                                         defaultLinkPermission: DefaultLinkPermission,
                                         defaultSharingLinkType: DefaultSharingLinkType,
                                         wait: Wait, timeoutFunction: Wait ? timeoutFunction : null
                                         );

                if (Owners != null && Owners.Count > 0)
                {
                    var admins = new List <UserEntity>();
                    foreach (var owner in Owners)
                    {
                        var userEntity = new UserEntity {
                            LoginName = owner
                        };
                        admins.Add(userEntity);
                    }
                    Tenant.AddAdministrators(admins, new Uri(Url));
                }
            }
        }
Esempio n. 5
0
        public static void AddAdministratorsTenant(this Web web, String[] adminLogins, Uri siteUrl)
        {
            Tenant tenant = new Tenant(web.Context);

            tenant.AddAdministrators(adminLogins, siteUrl);
        }
Esempio n. 6
0
        protected override void ExecuteCmdlet()
        {
            var context = ClientContext;
            var site    = ClientContext.Site;
            var siteUrl = ClientContext.Url;

            var executeQueryRequired = false;

            if (!string.IsNullOrEmpty(Identity))
            {
                context = ClientContext.Clone(Identity);
                site    = context.Site;
                siteUrl = context.Url;
            }


            if (MyInvocation.BoundParameters.ContainsKey("Classification"))
            {
                site.Classification  = Classification;
                executeQueryRequired = true;
            }
            if (MyInvocation.BoundParameters.ContainsKey("LogoFilePath"))
            {
                var webTemplate = ClientContext.Web.EnsureProperty(w => w.WebTemplate);
                if (webTemplate == "GROUP")
                {
                    if (!System.IO.Path.IsPathRooted(LogoFilePath))
                    {
                        LogoFilePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, LogoFilePath);
                    }
                    if (System.IO.File.Exists(LogoFilePath))
                    {
                        var bytes    = System.IO.File.ReadAllBytes(LogoFilePath);
                        var mimeType = System.Web.MimeMapping.GetMimeMapping(LogoFilePath);
                        var result   = OfficeDevPnP.Core.Sites.SiteCollection.SetGroupImage(context, bytes, mimeType).GetAwaiter().GetResult();
                    }
                    else
                    {
                        throw new System.Exception("Logo file does not exist");
                    }
                }
                else
                {
                    throw new System.Exception("Not an Office365 group enabled site.");
                }
            }
            if (executeQueryRequired)
            {
                context.ExecuteQueryRetry();
            }

            if (IsTenantProperty())
            {
                var tenantAdminUrl = UrlUtilities.GetTenantAdministrationUrl(context.Url);
                context = context.Clone(tenantAdminUrl);

                executeQueryRequired = false;
                Func <TenantOperationMessage, bool> timeoutFunction = TimeoutFunction;
                Tenant tenant         = new Tenant(context);
                var    siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, false);
                if (LockState.HasValue)
                {
                    tenant.SetSiteLockState(siteUrl, LockState.Value, Wait, Wait ? timeoutFunction : null);
                    WriteWarning("You changed the lockstate of this site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect.");
                }

                if (Owners != null && Owners.Count > 0)
                {
                    var admins = new List <UserEntity>();
                    foreach (var owner in Owners)
                    {
                        var userEntity = new UserEntity {
                            LoginName = owner
                        };
                        admins.Add(userEntity);
                    }
                    tenant.AddAdministrators(admins, new Uri(siteUrl));
                }
                if (Sharing.HasValue)
                {
                    siteProperties.SharingCapability = Sharing.Value;
                    executeQueryRequired             = true;
                }
                if (StorageMaximumLevel.HasValue)
                {
                    siteProperties.StorageMaximumLevel = StorageMaximumLevel.Value;
                    executeQueryRequired = true;
                }
                if (StorageWarningLevel.HasValue)
                {
                    siteProperties.StorageWarningLevel = StorageWarningLevel.Value;
                    executeQueryRequired = true;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                if (UserCodeWarningLevel.HasValue)
                {
                    siteProperties.UserCodeWarningLevel = UserCodeWarningLevel.Value;
                    executeQueryRequired = true;
                }
                if (UserCodeMaximumLevel.HasValue)
                {
                    siteProperties.UserCodeMaximumLevel = UserCodeMaximumLevel.Value;
                    executeQueryRequired = true;
                }
#pragma warning restore CS0618 // Type or member is obsolete

                if (AllowSelfServiceUpgrade.HasValue)
                {
                    siteProperties.AllowSelfServiceUpgrade = AllowSelfServiceUpgrade.Value;
                    executeQueryRequired = true;
                }
                if (NoScriptSite.IsPresent)
                {
                    siteProperties.DenyAddAndCustomizePages = (NoScriptSite == true ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled);
                    executeQueryRequired = true;
                }
                if (CommentsOnSitePagesDisabled.IsPresent)
                {
                    siteProperties.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled;
                    executeQueryRequired = true;
                }
                if (DefaultLinkPermission.HasValue)
                {
                    siteProperties.DefaultLinkPermission = DefaultLinkPermission.Value;
                    executeQueryRequired = true;
                }
                if (DefaultSharingLinkType.HasValue)
                {
                    siteProperties.DefaultSharingLinkType = DefaultSharingLinkType.Value;
                    executeQueryRequired = true;
                }
                if (DisableAppViews.HasValue)
                {
                    siteProperties.DisableAppViews = DisableAppViews.Value;
                    executeQueryRequired           = true;
                }
                if (DisableCompanyWideSharingLinks.HasValue)
                {
                    siteProperties.DisableCompanyWideSharingLinks = DisableCompanyWideSharingLinks.Value;
                    executeQueryRequired = true;
                }
                if (DisableFlows.IsPresent)
                {
                    siteProperties.DisableFlows = DisableFlows ? FlowsPolicy.Disabled : FlowsPolicy.NotDisabled;
                    executeQueryRequired        = true;
                }
                if (LocaleId.HasValue)
                {
                    siteProperties.Lcid  = LocaleId.Value;
                    executeQueryRequired = true;
                }
                if (!string.IsNullOrEmpty(NewUrl))
                {
                    siteProperties.NewUrl = NewUrl;
                    executeQueryRequired  = true;
                }
                if (RestrictedToGeo.HasValue)
                {
                    siteProperties.RestrictedToRegion = RestrictedToGeo.Value;
                    executeQueryRequired = true;
                }
                if (SocialBarOnSitePagesDisabled.IsPresent)
                {
                    siteProperties.SocialBarOnSitePagesDisabled = SocialBarOnSitePagesDisabled;
                    executeQueryRequired = true;
                }
                if (executeQueryRequired)
                {
                    siteProperties.Update();
                    tenant.Context.ExecuteQueryRetry();
                }

                if (DisableSharingForNonOwners.IsPresent)
                {
                    Office365Tenant office365Tenant = new Office365Tenant(context);
                    context.Load(office365Tenant);
                    context.ExecuteQueryRetry();
                    office365Tenant.DisableSharingForNonOwnersOfSite(siteUrl);
                    context.ExecuteQuery();
                }
            }
        }
        public override bool Execute()
        {
            bool processed = false;

            string generalSiteDirectoryUrl      = GetConfiguration("General.SiteDirectoryUrl");
            string generalSiteDirectoryListName = GetConfiguration("General.SiteDirectoryListName");
            string generalSiteCollectionUrl     = GetConfiguration("General.SiteCollectionUrl");
            string generalMailSMTPServer        = GetConfiguration("General.MailSMTPServer");
            string generalMailUser             = GetConfiguration("General.MailUser");
            string generalMailUserPassword     = GetConfiguration("General.MailUserPassword");
            string generalMailSiteAvailable    = GetConfiguration("General.MailSiteAvailable");
            string generalEncryptionThumbPrint = GetConfiguration("General.EncryptionThumbPrint");

            //Decrypt mail password
            generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint);
            string contosoCollaborationPromotedSiteName = GetConfiguration("ContosoCollaboration.PromotedSiteName");
            string contosoCollaborationPromotedSiteUrl  = GetConfiguration("ContosoCollaboration.PromotedSiteUrl");
            string contosoCollaborationThemeName        = GetConfiguration("ContosoCollaboration.ThemeName");
            //On-Prem settings
            string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication");

            try
            {
                SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager();
                //FeatureManager featureManager = new FeatureManager();
                //ListManager listManager = new ListManager();
                //PageManager pageManager = new PageManager();
                //SecurityManager securityManager = new SecurityManager();
                //NavigationManager navigationManager = new NavigationManager();
                //BrandingManager brandingManager = new BrandingManager();


                string tempSharePointUrl = this.SharePointProvisioningData.Url;
                string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl;

                // issue the final SharePoint url
                SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl);

                //update site directory status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning");

                //complete the site data
                this.SharePointProvisioningData.Template            = "STS#0";
                this.SharePointProvisioningData.SiteOwner           = this.SharePointProvisioningData.Owners[0];
                this.SharePointProvisioningData.Lcid                = 1033;
                this.SharePointProvisioningData.TimeZoneId          = 3;
                this.SharePointProvisioningData.StorageMaximumLevel = 100;
                this.SharePointProvisioningData.StorageWarningLevel = 80;

                //create the site collection
                this.AddSiteCollection(this.SharePointProvisioningData);

                //enable features
                // Document ID Service (DocID) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("b50e3104-6812-424f-a011-cc90e6327318"));
                // Search Server Web Parts and Templates (SearchMaster) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("9c0834e1-ba47-4d49-812b-7d4fb6fea211"));
                // Workflows (Workflows) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("0af5989a-3aea-4519-8ab0-85d91abe39ff"));
                // Metadata Navigation and Filtering (MetaDataNav) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("7201d6a4-a5d3-49a1-8c19-19c4bac6e668"));
                // Community Site Feature (CommunitySite) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("961d6a9c-4388-4cf2-9733-38ee8c89afd4"));
                // Project Functionality (ProjectFunctionality) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("e2f2bb18-891d-4812-97df-c265afdba297"));

                // Picture library called Media
                this.CreatedSiteContext.Web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.PictureLibrary, "Media", false);
                // Promoted Links library called Links
                this.CreatedSiteContext.Web.CreateList(new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), 170, "Links", false);

                // Update existing list settings for the documents library and the blog post library
                this.CreatedSiteContext.Web.UpdateListVersioning("Documents", true);

                //Remove the "Project Summary" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Project Summary", "home.aspx");
                //Remove the "Get started with your site" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Get started with your site", "home.aspx");
                //Remove the "Documents" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Documents", "home.aspx");

                //Add links web part to the home page
                Guid          linksID         = this.CreatedSiteContext.Web.GetListID("Links");
                WebPartEntity promotedLinksWP = new WebPartEntity();
                promotedLinksWP.WebPartXml   = WpPromotedLinks(linksID, string.Format("{0}{1}/Lists/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "Links"), string.Format("{0}{1}/SitePages/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "home.aspx"), "$Resources:core,linksList");
                promotedLinksWP.WebPartIndex = 2;
                promotedLinksWP.WebPartTitle = "Links";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", promotedLinksWP, "home.aspx", 2, 2, false);

                //Add html to the home page wiki
                this.CreatedSiteContext.Web.AddHtmlToWikiPage("SitePages", "Hello <strong>SharePoint Conference</strong> from spc403<br/><br/><br/>", "home.aspx", 1, 1);

                //add additional pages
                string siteMembersPage = "site members.aspx";
                string siteMembersUrl  = this.CreatedSiteContext.Web.AddWikiPage("Site Pages", siteMembersPage);
                this.CreatedSiteContext.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumns, siteMembersPage);
                //Add site members web parts
                WebPartEntity wpSiteUsers = new WebPartEntity();
                wpSiteUsers.WebPartXml   = WpSiteUsers("Site owners", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Owners")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site owners";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, false);

                wpSiteUsers.WebPartXml   = WpSiteUsers("Site visitors", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Visitors")));
                wpSiteUsers.WebPartIndex = 1;
                wpSiteUsers.WebPartTitle = "Site visitors";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, true);

                wpSiteUsers.WebPartXml   = WpSiteUsers("Site members", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Members")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site members";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 2, false);

                //Update the quick launch navigation
                //First delete all quicklaunch entries
                this.CreatedSiteContext.Web.DeleteAllQuickLaunchNodes();

                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,nav_Home", null, "", NavigationType.QuickLaunch);
                //csomService.AddNavigationNode(this.SiteToProvision, "$Resources:core,BlogQuickLaunchTitle", new Uri(this.BlogSite.Url), "News & Trending", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,DiscussionsTab", new Uri(string.Format("{0}/Lists/Community%20Discussion/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                string notebookPath = string.Format("{0}/SiteAssets/{1} Notebook", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Title);
                notebookPath = HttpUtility.UrlPathEncode(notebookPath, false).Replace("/", "%2F");
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,SiteNotebookLink", new Uri(string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=editnew", this.SharePointProvisioningData.Url, notebookPath)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,taskList", new Uri(string.Format("{0}/Lists/Tasks/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,calendarList", new Uri(string.Format("{0}/Lists/Calendar/calendar.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,shareddocuments_Title_15", new Uri(string.Format("{0}/Shared Documents/Forms/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,linksList", new Uri(string.Format("{0}/Lists/Links/Tiles.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,GrpMedia", new Uri(string.Format("{0}/Media/Forms/Thumbnails.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,Members_QuickLaunch", new Uri(string.Format("{0}/{1}", this.SharePointProvisioningData.Url, siteMembersUrl)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,category_SiteContents", new Uri(string.Format("{0}/_layouts/15/viewlsts.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);

                // Insert demo promoted links list item
                if (contosoCollaborationPromotedSiteName.Length > 0 || contosoCollaborationPromotedSiteUrl.Length > 0)
                {
                    AddPromotedSiteLink(this.CreatedSiteContext, this.CreatedSiteContext.Web, "Links", contosoCollaborationPromotedSiteName, contosoCollaborationPromotedSiteUrl);
                }

                if (!this.CreateOnPremises)
                {
                    // add owners to site collection administrators
                    List <UserEntity> adminLogins = new List <UserEntity>();

                    int i = 0;
                    foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                    {
                        adminLogins.Add(new UserEntity()
                        {
                            Email     = owner.Email,
                            LoginName = owner.Login,
                            Title     = owner.Name,
                        });
                        i++;
                    }

                    Tenant tenant = new Tenant(this.AppOnlyClientContext);
                    tenant.AddAdministrators(adminLogins, new Uri(this.SharePointProvisioningData.Url), true);

                    // Everyone reader
                    this.CreatedSiteContext.Web.AddReaderAccess();
                }

                // Apply themes
                string themeRoot      = Path.Combine(this.AppRootPath, String.Format(@"Themes\{0}", contosoCollaborationThemeName));
                string spColorFile    = Path.Combine(themeRoot, string.Format("{0}.spcolor", contosoCollaborationThemeName));
                string spFontFile     = Path.Combine(themeRoot, string.Format("{0}.spfont", contosoCollaborationThemeName));
                string backgroundFile = Path.Combine(themeRoot, string.Format("{0}bg.jpg", contosoCollaborationThemeName));
                string logoFile       = Path.Combine(themeRoot, string.Format("{0}logo.png", contosoCollaborationThemeName));

                // Deploy theme files to root web, if they are not there and set it as active theme for the site
                string themeColorFileString       = "";
                string themeFontFileString        = "";
                string themeBackgroundImageString = "";

                if (!String.IsNullOrEmpty(themeRoot))
                {
                    themeColorFileString = this.CreatedSiteContext.Web.UploadThemeFile(themeRoot).ServerRelativeUrl;
                }
                if (!String.IsNullOrEmpty(spColorFile))
                {
                    themeFontFileString = this.CreatedSiteContext.Web.UploadThemeFile(spColorFile).ServerRelativeUrl;
                }

                if (!String.IsNullOrWhiteSpace(backgroundFile))
                {
                    themeBackgroundImageString = this.CreatedSiteContext.Web.UploadThemeFile(backgroundFile).ServerRelativeUrl;
                }

                this.CreatedSiteContext.Web.CreateComposedLookByUrl(contosoCollaborationThemeName, themeColorFileString, themeFontFileString, themeBackgroundImageString, String.Empty);
                this.CreatedSiteContext.Web.SetComposedLookByUrl(contosoCollaborationThemeName);

                //Seems to be broken at the moment...to be investigated
                //brandingManager.SetSiteLogo(this.CreatedSiteContext, this.CreatedSiteContext.Web, logoFile);

                // Update status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available");

                // Send mail to owners
                List <String> mailTo        = new List <string>();
                string        ownerNames    = "";
                string        ownerAccounts = "";

                foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                {
                    mailTo.Add(owner.Email);

                    if (ownerNames.Length > 0)
                    {
                        ownerNames    = ownerNames + ", ";
                        ownerAccounts = ownerAccounts + ", ";
                    }
                    ownerNames    = ownerNames + owner.Name;
                    ownerAccounts = ownerAccounts + owner.Login;
                }

                // send email to notify the use of successful provisioning
                string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts);
                MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody);
            }
            catch (Exception ex)
            {
                //log error
                new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex);
            }

            return(processed);
        }
Esempio n. 8
0
        private void SetSiteProperties(Func <TenantOperationMessage, bool> timeoutFunction)
        {
            var props          = GetSiteProperties(Url);
            var updateRequired = false;

            if (ParameterSpecified(nameof(Title)))
            {
                props.Title    = Title;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DenyAddAndCustomizePages)))
            {
                props.DenyAddAndCustomizePages = DenyAddAndCustomizePages ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(LocaleId)))
            {
                props.Lcid     = LocaleId;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(AllowSelfServiceUpgrade)))
            {
                props.AllowSelfServiceUpgrade = AllowSelfServiceUpgrade;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(SharingAllowedDomainList)))
            {
                props.SharingAllowedDomainList = SharingAllowedDomainList;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(SharingBlockedDomainList)))
            {
                props.SharingBlockedDomainList = SharingBlockedDomainList;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(SharingDomainRestrictionMode)))
            {
                props.SharingDomainRestrictionMode = SharingDomainRestrictionMode;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(StorageMaximumLevel)))
            {
                props.StorageMaximumLevel = StorageMaximumLevel;
                updateRequired            = true;
            }
            if (ParameterSpecified(nameof(StorageWarningLevel)))
            {
                props.StorageWarningLevel = StorageWarningLevel;
                updateRequired            = true;
            }
            if (ParameterSpecified(nameof(SharingCapability)))
            {
                props.SharingCapability = SharingCapability;
                updateRequired          = true;
            }
            if (ParameterSpecified(nameof(DefaultLinkPermission)))
            {
                props.DefaultLinkPermission = DefaultLinkPermission;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(DefaultSharingLinkType)))
            {
                props.DefaultSharingLinkType = DefaultSharingLinkType;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(BlockDownloadOfNonViewableFiles)))
            {
                props.AllowDownloadingNonWebViewableFiles = !BlockDownloadOfNonViewableFiles;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(CommentsOnSitePagesDisabled)))
            {
                props.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DisableAppViews)))
            {
                props.DisableAppViews = DisableAppViews;
                updateRequired        = true;
            }

            if (ParameterSpecified(nameof(DisableCompanyWideSharingLinks)))
            {
                props.DisableCompanyWideSharingLinks = DisableCompanyWideSharingLinks;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DisableFlows)))
            {
                props.DisableFlows = DisableFlows;
                updateRequired     = true;
            }

            if (ParameterSpecified(nameof(OverrideTenantAnonymousLinkExpirationPolicy)))
            {
                props.OverrideTenantAnonymousLinkExpirationPolicy = OverrideTenantAnonymousLinkExpirationPolicy.ToBool();
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(AnonymousLinkExpirationInDays)) && AnonymousLinkExpirationInDays.HasValue)
            {
                props.AnonymousLinkExpirationInDays = AnonymousLinkExpirationInDays.Value;
                updateRequired = true;
            }

            if (updateRequired)
            {
                var op = props.Update();
                ClientContext.Load(op, i => i.IsComplete, i => i.PollingInterval);
                ClientContext.ExecuteQueryRetry();

                if (Wait)
                {
                    WaitForIsComplete(ClientContext, op, timeoutFunction, TenantOperationMessage.SettingSiteProperties);
                }
            }

            if (Owners != null && Owners.Count > 0)
            {
                var admins = new List <UserEntity>();
                foreach (var owner in Owners)
                {
                    var userEntity = new UserEntity {
                        LoginName = owner
                    };
                    admins.Add(userEntity);
                }
                Tenant.AddAdministrators(admins, new Uri(Url));
            }
        }
Esempio n. 9
0
        protected override void ExecuteCmdlet()
        {
            var context = ClientContext;
            var site    = ClientContext.Site;
            var siteUrl = ClientContext.Url;

            var executeQueryRequired = false;

            if (!string.IsNullOrEmpty(Identity))
            {
                context = ClientContext.Clone(Identity);
                site    = context.Site;
                siteUrl = context.Url;
            }

            if (ParameterSpecified(nameof(Classification)))
            {
                site.Classification  = Classification;
                executeQueryRequired = true;
            }
            if (ParameterSpecified(nameof(LogoFilePath)))
            {
                site.EnsureProperty(s => s.GroupId);
                if (site.GroupId != Guid.Empty)
                {
                    if (!System.IO.Path.IsPathRooted(LogoFilePath))
                    {
                        LogoFilePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, LogoFilePath);
                    }
                    if (System.IO.File.Exists(LogoFilePath))
                    {
                        var bytes = System.IO.File.ReadAllBytes(LogoFilePath);

                        var mimeType = "";
                        if (LogoFilePath.EndsWith("gif", StringComparison.InvariantCultureIgnoreCase))
                        {
                            mimeType = "image/gif";
                        }
                        if (LogoFilePath.EndsWith("jpg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            mimeType = "image/jpeg";
                        }
                        if (LogoFilePath.EndsWith("png", StringComparison.InvariantCultureIgnoreCase))
                        {
                            mimeType = "image/png";
                        }
                        var result = PnP.Framework.Sites.SiteCollection.SetGroupImageAsync(context, bytes, mimeType).GetAwaiter().GetResult();
                    }
                    else
                    {
                        throw new Exception("Logo file does not exist");
                    }
                }
                else
                {
                    throw new Exception("Not an Office365 group enabled site.");
                }
            }
            if (executeQueryRequired)
            {
                context.ExecuteQueryRetry();
            }

            if (IsTenantProperty())
            {
                var tenantAdminUrl = UrlUtilities.GetTenantAdministrationUrl(context.Url);
                context = context.Clone(tenantAdminUrl);

                executeQueryRequired = false;
                Func <TenantOperationMessage, bool> timeoutFunction = TimeoutFunction;
                Tenant tenant         = new Tenant(context);
                var    siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, false);

                if (ParameterSpecified(nameof(OverrideTenantAnonymousLinkExpirationPolicy)))
                {
                    siteProperties.OverrideTenantAnonymousLinkExpirationPolicy = OverrideTenantAnonymousLinkExpirationPolicy.ToBool();
                    executeQueryRequired = true;
                }
                if (ParameterSpecified(nameof(AnonymousLinkExpirationInDays)) && AnonymousLinkExpirationInDays.HasValue)
                {
                    siteProperties.AnonymousLinkExpirationInDays = AnonymousLinkExpirationInDays.Value;
                    executeQueryRequired = true;
                }
                if (LockState.HasValue)
                {
                    tenant.SetSiteLockState(siteUrl, LockState.Value, Wait, Wait ? timeoutFunction : null);
                    WriteWarning("You changed the lockstate of this site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect.");
                }
                if (Owners != null && Owners.Count > 0)
                {
                    var admins = new List <UserEntity>();
                    foreach (var owner in Owners)
                    {
                        var userEntity = new UserEntity {
                            LoginName = owner
                        };
                        admins.Add(userEntity);
                    }
                    tenant.AddAdministrators(admins, new Uri(siteUrl));
                }
                if (Sharing.HasValue)
                {
                    siteProperties.SharingCapability = Sharing.Value;
                    executeQueryRequired             = true;
                }
                if (StorageMaximumLevel.HasValue)
                {
                    siteProperties.StorageMaximumLevel = StorageMaximumLevel.Value;
                    executeQueryRequired = true;
                }
                if (StorageWarningLevel.HasValue)
                {
                    siteProperties.StorageWarningLevel = StorageWarningLevel.Value;
                    executeQueryRequired = true;
                }
                if (AllowSelfServiceUpgrade.HasValue)
                {
                    siteProperties.AllowSelfServiceUpgrade = AllowSelfServiceUpgrade.Value;
                    executeQueryRequired = true;
                }
                if (NoScriptSite.HasValue)
                {
                    siteProperties.DenyAddAndCustomizePages = (NoScriptSite == true ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled);
                    executeQueryRequired = true;
                }
                if (CommentsOnSitePagesDisabled.HasValue)
                {
                    siteProperties.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled.Value;
                    executeQueryRequired = true;
                }
                if (DefaultLinkPermission.HasValue)
                {
                    siteProperties.DefaultLinkPermission = DefaultLinkPermission.Value;
                    executeQueryRequired = true;
                }
                if (DefaultSharingLinkType.HasValue)
                {
                    siteProperties.DefaultSharingLinkType = DefaultSharingLinkType.Value;
                    executeQueryRequired = true;
                }
                if (DisableAppViews.HasValue)
                {
                    siteProperties.DisableAppViews = DisableAppViews.Value;
                    executeQueryRequired           = true;
                }
                if (DisableCompanyWideSharingLinks.HasValue)
                {
                    siteProperties.DisableCompanyWideSharingLinks = DisableCompanyWideSharingLinks.Value;
                    executeQueryRequired = true;
                }
                if (DisableFlows.HasValue)
                {
                    siteProperties.DisableFlows = DisableFlows.Value ? FlowsPolicy.Disabled : FlowsPolicy.NotDisabled;
                    executeQueryRequired        = true;
                }
                if (LocaleId.HasValue)
                {
                    siteProperties.Lcid  = LocaleId.Value;
                    executeQueryRequired = true;
                }
                if (RestrictedToGeo.HasValue)
                {
                    siteProperties.RestrictedToRegion = RestrictedToGeo.Value;
                    executeQueryRequired = true;
                }
                if (SocialBarOnSitePagesDisabled.HasValue)
                {
                    siteProperties.SocialBarOnSitePagesDisabled = SocialBarOnSitePagesDisabled.Value;
                    executeQueryRequired = true;
                }
                if (executeQueryRequired)
                {
                    siteProperties.Update();
                    tenant.Context.ExecuteQueryRetry();
                }

                if (DisableSharingForNonOwners.IsPresent)
                {
                    Office365Tenant office365Tenant = new Office365Tenant(context);
                    context.Load(office365Tenant);
                    context.ExecuteQueryRetry();
                    office365Tenant.DisableSharingForNonOwnersOfSite(siteUrl);
                    context.ExecuteQueryRetry();
                }
            }
        }
Esempio n. 10
0
        public static void AddAdministratorsTenant(this Web web, IEnumerable <UserEntity> adminLogins, Uri siteUrl, bool addToOwnersGroup = false)
        {
            Tenant tenant = new Tenant(web.Context);

            tenant.AddAdministrators(adminLogins, siteUrl, addToOwnersGroup);
        }
Esempio n. 11
0
        public static void AddAdministratorsTenant(this Web web, String[] adminLogins, Uri siteUrl)
        {
            Tenant tenant = new Tenant(web.Context);

            tenant.AddAdministrators(adminLogins, siteUrl);
        }
Esempio n. 12
0
        private void SetSiteProperties(Func <TenantOperationMessage, bool> timeoutFunction)
        {
            var props          = GetSiteProperties(Identity.Url);
            var updateRequired = false;

            if (ParameterSpecified(nameof(Title)))
            {
                props.Title    = Title;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DenyAddAndCustomizePages)))
            {
                props.DenyAddAndCustomizePages = DenyAddAndCustomizePages ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(LocaleId)))
            {
                props.Lcid     = LocaleId;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(AllowSelfServiceUpgrade)))
            {
                props.AllowSelfServiceUpgrade = AllowSelfServiceUpgrade;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(SharingAllowedDomainList)))
            {
                props.SharingAllowedDomainList = SharingAllowedDomainList;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(SharingBlockedDomainList)))
            {
                props.SharingBlockedDomainList = SharingBlockedDomainList;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(SharingDomainRestrictionMode)))
            {
                props.SharingDomainRestrictionMode = SharingDomainRestrictionMode;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(StorageQuota)))
            {
                props.StorageMaximumLevel = StorageQuota;
                updateRequired            = true;
            }
            if (ParameterSpecified(nameof(StorageQuotaWarningLevel)))
            {
                props.StorageWarningLevel = StorageQuotaWarningLevel;
                updateRequired            = true;
            }
            if (ParameterSpecified(nameof(StorageQuotaReset)))
            {
                props.StorageMaximumLevel = 0;
                updateRequired            = true;
            }
            if (ParameterSpecified(nameof(ResourceQuota)))
            {
                props.UserCodeMaximumLevel = ResourceQuota;
                updateRequired             = true;
            }
            if (ParameterSpecified(nameof(ResourceQuotaWarningLevel)))
            {
                props.UserCodeWarningLevel = ResourceQuotaWarningLevel;
                updateRequired             = true;
            }
            if (ParameterSpecified(nameof(SharingCapability)))
            {
                props.SharingCapability = SharingCapability;
                updateRequired          = true;
            }
            if (ParameterSpecified(nameof(DefaultLinkPermission)))
            {
                props.DefaultLinkPermission = DefaultLinkPermission;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(ShowPeoplePickerSuggestionsForGuestUsers)))
            {
                Tenant.EnsureProperty(t => t.ShowPeoplePickerSuggestionsForGuestUsers);
                if (!Tenant.ShowPeoplePickerSuggestionsForGuestUsers)
                {
                    WriteWarning("ShowPeoplePickerSuggestionsForGuests users has been disabled for this tenant. See Set-PnPTenant");
                }
                props.ShowPeoplePickerSuggestionsForGuestUsers = ShowPeoplePickerSuggestionsForGuestUsers;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(DefaultSharingLinkType)))
            {
                props.DefaultSharingLinkType = DefaultSharingLinkType;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(DefaultLinkToExistingAccess)))
            {
                props.DefaultLinkToExistingAccess = DefaultLinkToExistingAccess.Value;
                updateRequired = true;
            }
            if (ParameterSpecified(nameof(DefaultLinkToExistingAccessReset)))
            {
                props.DefaultLinkToExistingAccessReset = true;
                updateRequired = true;
            }
#pragma warning disable CS0618
            if (ParameterSpecified(nameof(BlockDownloadOfNonViewableFiles)) || ParameterSpecified(nameof(AllowDownloadingNonWebViewableFiles)))
            {
                var value = ParameterSpecified(nameof(BlockDownloadLinksFileTypes)) ? !BlockDownloadOfNonViewableFiles : AllowDownloadingNonWebViewableFiles;
                if (ConditionalAccessPolicy == SPOConditionalAccessPolicyType.AllowLimitedAccess)
                {
                    props.AllowDownloadingNonWebViewableFiles = value;
                    updateRequired = true;
                    if (!value)
                    {
                        WriteWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true.");
                    }
                }
                else
                {
                    if (ShouldContinue("To set AllowDownloadingNonWebViewableFiles parameter you need to set the -ConditionalAccessPolicy parameter to AllowLimitedAccess. We can set the Conditional Access Policy of this site to AllowLimitedAccess. Would you like to continue?", string.Empty))
                    {
                        ConditionalAccessPolicy                   = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                        props.ConditionalAccessPolicy             = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                        props.AllowDownloadingNonWebViewableFiles = value;
                        if (!value)
                        {
                            WriteWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true.");
                        }
                    }
                }
            }
#pragma warning restore CS0618

            if (ParameterSpecified(nameof(CommentsOnSitePagesDisabled)))
            {
                props.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DisableAppViews)))
            {
                props.DisableAppViews = DisableAppViews;
                updateRequired        = true;
            }

            if (ParameterSpecified(nameof(DisableCompanyWideSharingLinks)))
            {
                props.DisableCompanyWideSharingLinks = DisableCompanyWideSharingLinks;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DisableFlows)))
            {
                props.DisableFlows = DisableFlows;
                updateRequired     = true;
            }

            if (ParameterSpecified(nameof(EnablePWA)))
            {
                props.PWAEnabled = EnablePWA ? PWAEnabledStatus.Enabled : PWAEnabledStatus.Disabled;
                updateRequired   = true;
            }

            if (ParameterSpecified(nameof(OverrideTenantAnonymousLinkExpirationPolicy)))
            {
                props.OverrideTenantAnonymousLinkExpirationPolicy = OverrideTenantAnonymousLinkExpirationPolicy.ToBool();
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(AnonymousLinkExpirationInDays)) && AnonymousLinkExpirationInDays.HasValue)
            {
                props.AnonymousLinkExpirationInDays = AnonymousLinkExpirationInDays.Value;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(DisableSharingForNonOwners)))
            {
                var office365Tenant = new Office365Tenant(ClientContext);
                ClientContext.Load(office365Tenant);
                ClientContext.ExecuteQueryRetry();
                office365Tenant.DisableSharingForNonOwnersOfSite(Identity.Url);
            }

            if (ParameterSpecified(nameof(ConditionalAccessPolicy)) && ConditionalAccessPolicy == SPOConditionalAccessPolicyType.ProtectionLevel)
            {
                if (IsRootSite(Identity.Url))
                {
                    throw new PSInvalidOperationException("You cannot set the conditional access policy 'ProtectionLevel' on the root site.");
                }
                if (string.IsNullOrEmpty(ProtectionLevelName))
                {
                    props.AuthContextStrength = null;
                }
                else
                {
                    props.AuthContextStrength = ProtectionLevelName;
                }
                updateRequired = true;
            }
            else
            {
                if (ParameterSpecified(nameof(ProtectionLevelName)))
                {
                    throw new PSArgumentException("ConditionalAccessPolicy has to be set too when using this parameter.");
                }
                if (ParameterSpecified(nameof(ConditionalAccessPolicy)))
                {
                    props.AuthContextStrength = null;
                    updateRequired            = true;
                }
            }

            if (ClientContext.ServerVersion >= new Version(16, 0, 8715, 1200)) // ServerSupportsIpLabelId2
            {
                if (ParameterSpecified(nameof(SensitivityLabel)))
                {
                    props.SensitivityLabel2 = SensitivityLabel;
                    updateRequired          = true;
                }
                if (ParameterSpecified(nameof(RemoveLabel)))
                {
                    props.SensitivityLabel2 = null;
                    updateRequired          = true;
                }
            }
            else
            {
                WriteWarning("Server does not support setting sensitity label");
            }

            if (ParameterSpecified(nameof(LimitedAccessFileType)))
            {
                if (ConditionalAccessPolicy == SPOConditionalAccessPolicyType.AllowLimitedAccess)
                {
                    props.LimitedAccessFileType = LimitedAccessFileType;
                    updateRequired = true;
                }
                else if (ShouldContinue("To set LimitedAccessFileType you need to set the -ConditionalAccessPolicy parameter to AllowLimitedAccess. We can set the Conditional Access Policy of this site to AllowLimitedAccess. Would you like to continue?", string.Empty))
                {
                    ConditionalAccessPolicy       = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                    props.ConditionalAccessPolicy = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                    props.LimitedAccessFileType   = LimitedAccessFileType;
                    updateRequired = true;
                }
            }

            if (ParameterSpecified(nameof(AllowEditing)))
            {
                if (ConditionalAccessPolicy == SPOConditionalAccessPolicyType.AllowLimitedAccess)
                {
                    props.AllowEditing = AllowEditing;
                }
                else if (ShouldContinue("To set AllowEditing you need to set the -ConditionalAccessPolicy parameter to AllowLimitedAccess. We can set the Conditional Access Policy of this site to AllowLimitedAccess. Would you like to continue?", string.Empty))
                {
                    ConditionalAccessPolicy       = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                    props.ConditionalAccessPolicy = SPOConditionalAccessPolicyType.AllowLimitedAccess;
                    props.AllowEditing            = AllowEditing;
                }
            }

            if (ParameterSpecified(nameof(RestrictedToGeo)))
            {
                props.RestrictedToRegion = RestrictedToGeo;
                updateRequired           = true;
            }

            if (ParameterSpecified(nameof(ExternalUserExpirationInDays)))
            {
                props.ExternalUserExpirationInDays = ExternalUserExpirationInDays;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(OverrideTenantExternalUserExpirationPolicy)))
            {
                props.OverrideTenantExternalUserExpirationPolicy = OverrideTenantExternalUserExpirationPolicy;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(AddInformationSegment)) && AddInformationSegment.Length > 0)
            {
                props.IBSegmentsToAdd = AddInformationSegment;
                updateRequired        = true;
            }

            if (ParameterSpecified(nameof(RemoveInformationSegment)) && RemoveInformationSegment.Length > 0)
            {
                props.IBSegmentsToRemove = RemoveInformationSegment;
                updateRequired           = true;
            }

            if (ParameterSpecified(nameof(BlockDownloadLinksFileType)))
            {
                props.BlockDownloadLinksFileType = BlockDownloadLinksFileType;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(OverrideBlockUserInfoVisibility)))
            {
                props.OverrideBlockUserInfoVisibility = OverrideBlockUserInfoVisibility;
                updateRequired = true;
            }

            if (ParameterSpecified(nameof(HubSiteId)))
            {
                var hubsiteProperties = Tenant.GetHubSitePropertiesById(HubSiteId);
                ClientContext.Load(hubsiteProperties);
                ClientContext.ExecuteQueryRetry();
                if (hubsiteProperties == null || string.IsNullOrEmpty(hubsiteProperties.SiteUrl))
                {
                    throw new PSArgumentException("Hubsite not found with the ID specified");
                }
                if (hubsiteProperties.ID != Guid.Empty)
                {
                    Tenant.ConnectSiteToHubSiteById(Identity.Url, hubsiteProperties.ID);
                }
                else
                {
                    Tenant.ConnectSiteToHubSite(Identity.Url, hubsiteProperties.SiteUrl);
                }
                ClientContext.ExecuteQueryRetry();
            }

            if (updateRequired)
            {
                var op = props.Update();
                ClientContext.Load(op, i => i.IsComplete, i => i.PollingInterval);
                ClientContext.ExecuteQueryRetry();

                if (Wait)
                {
                    WaitForIsComplete(ClientContext, op, timeoutFunction, TenantOperationMessage.SettingSiteProperties);
                }
            }

            if (Owners != null && Owners.Count > 0)
            {
                var admins = new List <UserEntity>();
                foreach (var owner in Owners)
                {
                    var userEntity = new UserEntity {
                        LoginName = owner
                    };
                    admins.Add(userEntity);
                }
                Tenant.AddAdministrators(admins, new Uri(Identity.Url));
            }
        }
Esempio n. 13
0
        public override bool Execute()
        {
            bool processed = false;

            string generalSiteDirectoryUrl = GetConfiguration("General.SiteDirectoryUrl");
            string generalSiteDirectoryListName = GetConfiguration("General.SiteDirectoryListName");
            string generalSiteCollectionUrl = GetConfiguration("General.SiteCollectionUrl");
            string generalMailSMTPServer = GetConfiguration("General.MailSMTPServer");
            string generalMailUser = GetConfiguration("General.MailUser");
            string generalMailUserPassword = GetConfiguration("General.MailUserPassword");
            string generalMailSiteAvailable = GetConfiguration("General.MailSiteAvailable");
            string generalEncryptionThumbPrint = GetConfiguration("General.EncryptionThumbPrint");
            //Decrypt mail password
            generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint);
            string contosoCollaborationPromotedSiteName = GetConfiguration("ContosoCollaboration.PromotedSiteName");
            string contosoCollaborationPromotedSiteUrl = GetConfiguration("ContosoCollaboration.PromotedSiteUrl");    
            string contosoCollaborationThemeName = GetConfiguration("ContosoCollaboration.ThemeName");                
            //On-Prem settings
            string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication");

            try
            {
                SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager();
                //FeatureManager featureManager = new FeatureManager();
                //ListManager listManager = new ListManager();
                //PageManager pageManager = new PageManager();
                //SecurityManager securityManager = new SecurityManager();
                //NavigationManager navigationManager = new NavigationManager();
                //BrandingManager brandingManager = new BrandingManager();


                string tempSharePointUrl = this.SharePointProvisioningData.Url;
                string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl;

                // issue the final SharePoint url
                SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl);
                
                //update site directory status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning");

                //complete the site data
                this.SharePointProvisioningData.Template = "STS#0";
                this.SharePointProvisioningData.SiteOwner = this.SharePointProvisioningData.Owners[0];
                this.SharePointProvisioningData.Lcid = 1033;
                this.SharePointProvisioningData.TimeZoneId = 3;
                this.SharePointProvisioningData.StorageMaximumLevel = 100;
                this.SharePointProvisioningData.StorageWarningLevel = 80;

                //create the site collection
                this.AddSiteCollection(this.SharePointProvisioningData);

                //enable features
                // Document ID Service (DocID) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("b50e3104-6812-424f-a011-cc90e6327318"));
                // Search Server Web Parts and Templates (SearchMaster) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("9c0834e1-ba47-4d49-812b-7d4fb6fea211"));
                // Workflows (Workflows) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("0af5989a-3aea-4519-8ab0-85d91abe39ff"));
                // Metadata Navigation and Filtering (MetaDataNav) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("7201d6a4-a5d3-49a1-8c19-19c4bac6e668"));
                // Community Site Feature (CommunitySite) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("961d6a9c-4388-4cf2-9733-38ee8c89afd4"));
                // Project Functionality (ProjectFunctionality) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("e2f2bb18-891d-4812-97df-c265afdba297"));

                // Picture library called Media
                this.CreatedSiteContext.Web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.PictureLibrary, "Media", false);
                // Promoted Links library called Links
                this.CreatedSiteContext.Web.CreateList(new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), 170, "Links", false);

                // Update existing list settings for the documents library and the blog post library
                this.CreatedSiteContext.Web.UpdateListVersioning("Documents", true);

                //Remove the "Project Summary" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Project Summary", "home.aspx");
                //Remove the "Get started with your site" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Get started with your site", "home.aspx");
                //Remove the "Documents" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Documents", "home.aspx");

                //Add links web part to the home page
                Guid linksID = this.CreatedSiteContext.Web.GetListID("Links");
                WebPartEntity promotedLinksWP = new WebPartEntity();
                promotedLinksWP.WebPartXml = WpPromotedLinks(linksID, string.Format("{0}{1}/Lists/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "Links"), string.Format("{0}{1}/SitePages/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "home.aspx"), "$Resources:core,linksList");
                promotedLinksWP.WebPartIndex = 2;
                promotedLinksWP.WebPartTitle = "Links";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", promotedLinksWP, "home.aspx", 2, 2, false);

                //Add html to the home page wiki
                this.CreatedSiteContext.Web.AddHtmlToWikiPage("SitePages", "Hello <strong>SharePoint Conference</strong> from spc403<br/><br/><br/>", "home.aspx", 1, 1);

                //add additional pages
                string siteMembersPage = "site members.aspx";
                string siteMembersUrl = this.CreatedSiteContext.Web.AddWikiPage("Site Pages", siteMembersPage);
                this.CreatedSiteContext.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumns, siteMembersPage);
                //Add site members web parts
                WebPartEntity wpSiteUsers = new WebPartEntity();
                wpSiteUsers.WebPartXml = WpSiteUsers("Site owners", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Owners")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site owners";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, false);

                wpSiteUsers.WebPartXml = WpSiteUsers("Site visitors", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Visitors")));
                wpSiteUsers.WebPartIndex = 1;
                wpSiteUsers.WebPartTitle = "Site visitors";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, true);

                wpSiteUsers.WebPartXml = WpSiteUsers("Site members", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Members")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site members";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 2, false);

                //Update the quick launch navigation
                //First delete all quicklaunch entries
                this.CreatedSiteContext.Web.DeleteAllQuickLaunchNodes();

                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,nav_Home", null, "", NavigationType.QuickLaunch);
                //csomService.AddNavigationNode(this.SiteToProvision, "$Resources:core,BlogQuickLaunchTitle", new Uri(this.BlogSite.Url), "News & Trending", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,DiscussionsTab", new Uri(string.Format("{0}/Lists/Community%20Discussion/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                string notebookPath = string.Format("{0}/SiteAssets/{1} Notebook", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Title);
                notebookPath = HttpUtility.UrlPathEncode(notebookPath, false).Replace("/", "%2F");
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,SiteNotebookLink", new Uri(string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=editnew", this.SharePointProvisioningData.Url, notebookPath)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,taskList", new Uri(string.Format("{0}/Lists/Tasks/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,calendarList", new Uri(string.Format("{0}/Lists/Calendar/calendar.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,shareddocuments_Title_15", new Uri(string.Format("{0}/Shared Documents/Forms/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,linksList", new Uri(string.Format("{0}/Lists/Links/Tiles.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,GrpMedia", new Uri(string.Format("{0}/Media/Forms/Thumbnails.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,Members_QuickLaunch", new Uri(string.Format("{0}/{1}", this.SharePointProvisioningData.Url, siteMembersUrl)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,category_SiteContents", new Uri(string.Format("{0}/_layouts/15/viewlsts.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);

                // Insert demo promoted links list item
                if (contosoCollaborationPromotedSiteName.Length > 0 || contosoCollaborationPromotedSiteUrl.Length > 0)
                {
                    AddPromotedSiteLink(this.CreatedSiteContext, this.CreatedSiteContext.Web, "Links", contosoCollaborationPromotedSiteName, contosoCollaborationPromotedSiteUrl);
                }

                if (!this.CreateOnPremises)
                {
                    // add owners to site collection administrators
                    List<UserEntity> adminLogins = new List<UserEntity>();

                    int i = 0;
                    foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                    {
                        adminLogins.Add(new UserEntity()
                            {
                                 Email = owner.Email,
                                 LoginName = owner.Login,
                                 Title = owner.Name,
                            });
                        i++;
                    }

                    Tenant tenant = new Tenant(this.AppOnlyClientContext);
                    tenant.AddAdministrators(adminLogins, new Uri(this.SharePointProvisioningData.Url), true);

                    // Everyone reader
                    this.CreatedSiteContext.Web.AddReaderAccess();
                }

                // Apply themes
                string themeRoot = Path.Combine(this.AppRootPath, String.Format(@"Themes\{0}", contosoCollaborationThemeName));
                string spColorFile = Path.Combine(themeRoot, string.Format("{0}.spcolor", contosoCollaborationThemeName));
                string spFontFile = Path.Combine(themeRoot, string.Format("{0}.spfont", contosoCollaborationThemeName));
                string backgroundFile = Path.Combine(themeRoot, string.Format("{0}bg.jpg", contosoCollaborationThemeName));
                string logoFile = Path.Combine(themeRoot, string.Format("{0}logo.png", contosoCollaborationThemeName));

                // Deploy theme files to root web, if they are not there and set it as active theme for the site
                string themeColorFileString = "";
                string themeFontFileString = "";
                string themeBackgroundImageString = "";

                if (!String.IsNullOrEmpty(themeRoot))
                {
                    themeColorFileString = this.CreatedSiteContext.Web.UploadThemeFile(themeRoot).ServerRelativeUrl;

                }
                if (!String.IsNullOrEmpty(spColorFile))
                {
                    themeFontFileString = this.CreatedSiteContext.Web.UploadThemeFile(spColorFile).ServerRelativeUrl;
                }

                if (!String.IsNullOrWhiteSpace(backgroundFile))
                {
                    themeBackgroundImageString = this.CreatedSiteContext.Web.UploadThemeFile(backgroundFile).ServerRelativeUrl;
                }

                this.CreatedSiteContext.Web.CreateComposedLookByUrl(contosoCollaborationThemeName, themeColorFileString, themeFontFileString, themeBackgroundImageString, String.Empty);
                this.CreatedSiteContext.Web.SetComposedLookByUrl(contosoCollaborationThemeName);

                //Seems to be broken at the moment...to be investigated
                //brandingManager.SetSiteLogo(this.CreatedSiteContext, this.CreatedSiteContext.Web, logoFile);

                // Update status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available");

                // Send mail to owners
                List<String> mailTo = new List<string>();
                string ownerNames = "";
                string ownerAccounts = "";

                foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                {
                    mailTo.Add(owner.Email);

                    if (ownerNames.Length > 0)
                    {
                        ownerNames = ownerNames + ", ";
                        ownerAccounts = ownerAccounts + ", ";
                    }
                    ownerNames = ownerNames + owner.Name;
                    ownerAccounts = ownerAccounts + owner.Login;
                }

                // send email to notify the use of successful provisioning
                string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts);
                MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody);

            }
            catch (Exception ex)
            {
                //log error
                new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex);
            }

            return processed;
        }
Esempio n. 14
0
        protected override void ExecuteCmdlet()
        {
            Func <TenantOperationMessage, bool> timeoutFunction = TimeoutFunction;

            if (LockState.HasValue)
            {
                Tenant.SetSiteLockState(Url, LockState.Value, Wait, Wait ? timeoutFunction : null);
                WriteWarning("You changed the lockstate of a site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect.");
            }

            if (!LockState.HasValue)
            {
                var props          = GetSiteProperties(Url);
                var updateRequired = false;
                if (ParameterSpecified(nameof(SharingAllowedDomainList)))
                {
                    props.SharingAllowedDomainList = SharingAllowedDomainList;
                    updateRequired = true;
                }
                if (ParameterSpecified(nameof(SharingBlockedDomainList)))
                {
                    props.SharingBlockedDomainList = SharingBlockedDomainList;
                    updateRequired = true;
                }
                if (ParameterSpecified(nameof(SharingDomainRestrictionMode)))
                {
                    props.SharingDomainRestrictionMode = SharingDomainRestrictionMode;
                    updateRequired = true;
                }
                if (ParameterSpecified(nameof(LocaleId)))
                {
                    props.Lcid     = LocaleId;
                    updateRequired = true;
                }
                if (ParameterSpecified(nameof(DenyAddAndCustomizePages)))
                {
                    props.DenyAddAndCustomizePages = DenyAddAndCustomizePages ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled;
                    updateRequired = true;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                if (ParameterSpecified(nameof(UserCodeMaximumLevel)))
                {
                    props.UserCodeMaximumLevel = UserCodeMaximumLevel;
                    updateRequired             = true;
                }
                if (ParameterSpecified(nameof(UserCodeWarningLevel)))
                {
                    props.UserCodeWarningLevel = UserCodeWarningLevel;
                    updateRequired             = true;
                }
#pragma warning restore CS0618 // Type or member is obsolete
                if (ParameterSpecified(nameof(StorageMaximumLevel)))
                {
                    props.StorageMaximumLevel = StorageMaximumLevel;
                    updateRequired            = true;
                }
                if (ParameterSpecified(nameof(StorageWarningLevel)))
                {
                    props.StorageWarningLevel = StorageWarningLevel;
                    updateRequired            = true;
                }
                if (ParameterSpecified(nameof(SharingCapability)))
                {
                    props.SharingCapability = SharingCapability;
                    updateRequired          = true;
                }
                if (ParameterSpecified(nameof(DefaultLinkPermission)))
                {
                    props.DefaultLinkPermission = DefaultLinkPermission;
                    updateRequired = true;
                }
                if (ParameterSpecified(nameof(DefaultSharingLinkType)))
                {
                    props.DefaultSharingLinkType = DefaultSharingLinkType;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(BlockDownloadOfNonViewableFiles)))
                {
                    props.AllowDownloadingNonWebViewableFiles = !BlockDownloadOfNonViewableFiles;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(Title)))
                {
                    props.Title    = Title;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(CommentsOnSitePagesDisabled)))
                {
                    props.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(DisableAppViews)))
                {
                    props.DisableAppViews = DisableAppViews;
                    updateRequired        = true;
                }

                if (ParameterSpecified(nameof(DisableCompanyWideSharingLinks)))
                {
                    props.DisableCompanyWideSharingLinks = DisableCompanyWideSharingLinks;
                    updateRequired = true;
                }

                if (ParameterSpecified(nameof(DisableFlows)))
                {
                    props.DisableFlows = DisableFlows;
                    updateRequired     = true;
                }

                if (updateRequired)
                {
                    var op = props.Update();
                    ClientContext.Load(op, i => i.IsComplete, i => i.PollingInterval);
                    ClientContext.ExecuteQueryRetry();

                    if (Wait)
                    {
                        WaitForIsComplete(ClientContext, op, timeoutFunction, TenantOperationMessage.SettingSiteProperties);
                    }
                }

                if (Owners != null && Owners.Count > 0)
                {
                    var admins = new List <UserEntity>();
                    foreach (var owner in Owners)
                    {
                        var userEntity = new UserEntity {
                            LoginName = owner
                        };
                        admins.Add(userEntity);
                    }
                    Tenant.AddAdministrators(admins, new Uri(Url));
                }
            }
        }