Ejemplo n.º 1
0
        protected override void ExecuteCmdlet()
        {
            WebPartEntity wp = null;

            if (ParameterSetName == "FILE")
            {
                if (System.IO.File.Exists(Path))
                {
                    System.IO.StreamReader fileStream = new System.IO.StreamReader(Path);
                    string webPartString = fileStream.ReadToEnd();
                    fileStream.Close();

                    wp = new WebPartEntity();
                    wp.WebPartZone = ZoneId;
                    wp.WebPartIndex = ZoneIndex;
                    wp.WebPartXml = webPartString;
                }
            }
            else if (ParameterSetName == "XML")
            {
                wp = new WebPartEntity();
                wp.WebPartZone = ZoneId;
                wp.WebPartIndex = ZoneIndex;
                wp.WebPartXml = Xml;
            }
            if (wp != null)
            {
                this.SelectedWeb.AddWebPartToWebPartPage(PageUrl, wp);
            }
        }
Ejemplo n.º 2
0
        //sourceWebPartId - Used to update the content of the wikipage with new web part id
        public static bool AddWebPartt(Web web, string serverRelativePageUrl, WebPartEntity webPartEntity, string sourceWebPartId = "")
        {
            bool isWebPartAdded = false;
            try
            {
                Microsoft.SharePoint.Client.File webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

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

                LimitedWebPartManager webPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);

                WebPartDefinition importedWebPart = webPartManager.ImportWebPart(webPartEntity.WebPartXml);
                WebPartDefinition webPart = webPartManager.AddWebPart(importedWebPart.WebPart, webPartEntity.WebPartZone, webPartEntity.WebPartIndex);
                web.Context.Load(webPart);
                web.Context.ExecuteQuery();

                CheckForWikiFieldOrPublishingPageContentAndUpdate(webPart, web, webPartPage, sourceWebPartId);

                isWebPartAdded = true;

            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[AddWebPartt] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartt()", ex.GetType().ToString());
            }

            return isWebPartAdded;
        }
Ejemplo n.º 3
0
        protected override void ExecuteCmdlet()
        {
           

            WebPartEntity wp = null;

            switch (ParameterSetName)
            {
                case "FILE":
                    if (!System.IO.Path.IsPathRooted(Path))
                    {
                        Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                    }

                    if (File.Exists(Path))
                    {
                        var fileStream = new StreamReader(Path);
                        var webPartString = fileStream.ReadToEnd();
                        fileStream.Close();

                        wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = webPartString};
                    }
                    break;
                case "XML":
                    wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = Xml};
                    break;
            }
            if (wp != null)
            {
                SelectedWeb.AddWebPartToWebPartPage(PageUrl, wp);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <param name="page">Page to add the web part on</param>
        public static void AddWebPartToWebPartPage(this Web web, WebPartEntity webPart, string page)
        {
            if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                web.Context.ExecuteQuery();
            }
            var serverRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, page);

            AddWebPartToWebPartPage(web, serverRelativeUrl, webPart);
        }
        protected override void ExecuteCmdlet()
        {
            var serverRelativeWebUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant()))
            {
                ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl);
            }


            WebPartEntity wp = null;

            switch (ParameterSetName)
            {
                case "FILE":
                    if (!System.IO.Path.IsPathRooted(Path))
                    {
                        Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                    }

                    if (File.Exists(Path))
                    {
                        var fileStream = new StreamReader(Path);
                        var webPartString = fileStream.ReadToEnd();
                        fileStream.Close();

                        wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = webPartString};
                    }
                    break;
                case "XML":
                    wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = Xml};
                    break;
            }
            if (wp != null)
            {
                SelectedWeb.AddWebPartToWebPartPage(ServerRelativePageUrl, wp);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="serverRelativePageUrl">Page to add the web part on</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <exception cref="System.ArgumentException">Thrown when serverRelativePageUrl is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when serverRelativePageUrl or webPart is null</exception>
        public static void AddWebPartToWebPartPage(this Web web, string serverRelativePageUrl, WebPartEntity webPart)
        {
            if (string.IsNullOrEmpty(serverRelativePageUrl))
            {
                throw (serverRelativePageUrl == null)
                  ? new ArgumentNullException("serverRelativePageUrl")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "serverRelativePageUrl");
            }

            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            var webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

            if (webPartPage == null)
            {
                return;
            }

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

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml);

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.WebPartZone, webPart.WebPartIndex);
            web.Context.ExecuteQuery();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <param name="page">Page to add the web part on</param>
        /// <exception cref="System.ArgumentException">Thrown when page is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when webPart or page is null</exception>
        public static void AddWebPartToWebPartPage(this Web web, WebPartEntity webPart, string page)
        {
            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            if (string.IsNullOrEmpty(page))
            {
                throw (page == null)
                  ? new ArgumentNullException("page")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "page");
            }

            if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                web.Context.ExecuteQuery();
            }
            var serverRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, page);

            AddWebPartToWebPartPage(web, serverRelativeUrl, webPart);
        }
Ejemplo n.º 8
0
        private static void CreateSampleData(Web web) {
            var context = web.Context;
            var host = "https://" + HttpContext.Current.Request.Url.Authority;

            var event1 = new Event() {
                Title = "Corporate Event 1",
                Category = "Featured",
                ContactEmail = "*****@*****.**",
                Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sit amet augue in dolor dapibus feugiat in eu odio. Proin vel egestas purus. Integer sit amet orci rhoncus, elementum nibh sit amet, maximus dui. Vivamus rutrum neque et massa hendrerit, varius consequat quam efficitur. Quisque aliquam pellentesque quam, a bibendum nibh dignissim sit amet. Curabitur accumsan tincidunt lectus et tincidunt.",
                ImageUrl = host + "/Images/company-events1.jpg",
                Location = "Pittsburgh, PA",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT001",
                EventDate = DateTime.Today.AddDays(25)
            };

            var event2 = new Event() {
                Title = "Corporate Event 2",
                Category = "Featured",
                ContactEmail = "*****@*****.**",
                Description = "Vestibulum ex mauris, feugiat in vehicula id, congue eleifend elit. Morbi orci quam, mattis sit amet nisl sed, dictum fermentum velit. Quisque rhoncus, arcu vitae dignissim tempus, nisl felis volutpat ipsum, non lobortis tellus lectus at mauris. Fusce porta, lectus feugiat egestas fringilla, dui velit tincidunt est, nec congue ligula urna a felis. Nam vitae ullamcorper lectus. Sed vitae justo felis.",
                ImageUrl = host + "/Images/company-events2.jpg",
                Location = "Helsinki, Finland",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT002",
                EventDate = DateTime.Today.AddDays(45)
            };

            var event3 = new Event() {
                Title = "Corporate Event 3",
                Category = "Featured",
                ContactEmail = "*****@*****.**",
                Description = "Vivamus scelerisque lectus et sapien mollis, ut vestibulum nunc vulputate. Nullam sed quam felis. Praesent sit amet egestas nunc, nec aliquam eros. Maecenas et nisl dapibus, varius metus ac, luctus quam. Donec vitae justo vitae nisi placerat ultrices nec sed ante.",
                ImageUrl = host + "/Images/company-events3.jpg",
                Location = "Chicago, IL",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT003",
                EventDate = DateTime.Today.AddDays(60)
            };

            var event4 = new Event() {
                Title = "Corporate Event 4",
                Category = "General",
                ContactEmail = "*****@*****.**",
                Description = "Vivamus scelerisque lectus et sapien mollis, ut vestibulum nunc vulputate. Nullam sed quam felis. Praesent sit amet egestas nunc, nec aliquam eros. Maecenas et nisl dapibus, varius metus ac, luctus quam. Donec vitae justo vitae nisi placerat ultrices nec sed ante.",
                ImageUrl = host + "/Images/company-events1.jpg",
                Location = "Chicago, IL",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT004",
                EventDate = DateTime.Today.AddDays(20)
            };

            var event5 = new Event() {
                Title = "Corporate Event 5",
                Category = "General",
                ContactEmail = "*****@*****.**",
                Description = "Vestibulum ex mauris, feugiat in vehicula id, congue eleifend elit. Morbi orci quam, mattis sit amet nisl sed, dictum fermentum velit. Quisque rhoncus, arcu vitae dignissim tempus, nisl felis volutpat ipsum, non lobortis tellus lectus at mauris. Fusce porta, lectus feugiat egestas fringilla, dui velit tincidunt est, nec congue ligula urna a felis. Nam vitae ullamcorper lectus. Sed vitae justo felis.",
                ImageUrl = host + "/Images/company-events2.jpg",
                Location = "Helsinki, Finland",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT005",
                EventDate = DateTime.Today.AddDays(45)
            };

            var event6 = new Event() {
                Title = "Corporate Event 6",
                Category = "General",
                ContactEmail = "*****@*****.**",
                Description = "Vivamus scelerisque lectus et sapien mollis, ut vestibulum nunc vulputate. Nullam sed quam felis. Praesent sit amet egestas nunc, nec aliquam eros. Maecenas et nisl dapibus, varius metus ac, luctus quam. Donec vitae justo vitae nisi placerat ultrices nec sed ante.",
                ImageUrl = host + "/Images/company-events3.jpg",
                Location = "Chicago, IL",
                Status = EventStatus.Active,
                RegisteredEventId = "EVT006",
                EventDate = DateTime.Today.AddDays(60)
            };

            event1.Save(web);
            event2.Save(web);
            event3.Save(web);
            event4.Save(web);
            event5.Save(web);
            event6.Save(web);

            // create default wiki page
            web.AddWikiPage("Site Pages", "EventsHome.aspx");

            # region web parts
            var webPart1 = new WebPartEntity(){
                WebPartXml = @"<webParts>
  <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
    <metaData>
      <type name='Microsoft.SharePoint.WebPartPages.ClientWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name='Description' type='string'>Displays featured events</property>
        <property name='FeatureId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>3a6d7f41-2de8-4e69-b4b4-0325bd56b32c</property>
        <property name='Title' type='string'>Featured Events</property>
        <property name='ProductWebId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>12ae648f-27db-4a97-9c63-37155d3ace1e</property>
        <property name='WebPartName' type='string'>FeaturedEvents</property>
        <property name='ProductId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>3a6d7f41-2de8-4e69-b4b4-0325bd56b32b</property>
        <property name='ChromeState' type='chromestate'>Normal</property>
      </properties>
    </data>
  </webPart>
</webParts>",
                WebPartIndex = 0,
                WebPartTitle = "Featured Events",
                WebPartZone = "Rich Content"
            };

            var webPart2 = new WebPartEntity() {
                WebPartXml = @"<webParts>
  <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
    <metaData>
      <type name='Microsoft.SharePoint.WebPartPages.ClientWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name='Description' type='string'>Events displayed by specific category</property>
        <property name='FeatureId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>3a6d7f41-2de8-4e69-b4b4-0325bd56b32c</property>
        <property name='Title' type='string'>Events</property>
        <property name='ProductWebId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>12ae648f-27db-4a97-9c63-37155d3ace1e</property>
        <property name='WebPartName' type='string'>Events</property>
        <property name='ProductId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>3a6d7f41-2de8-4e69-b4b4-0325bd56b32b</property>
        <property name='ChromeState' type='chromestate'>Normal</property>
      </properties>
    </data>
  </webPart>
</webParts>",
                WebPartIndex = 1,
                WebPartTitle = "Events",
                WebPartZone = "Rich Content"
            };
            #endregion

            var welcomePage = "SitePages/EventsHome.aspx";
            var serverRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, welcomePage);

            File webPartPage = web.GetFileByServerRelativeUrl(serverRelativeUrl);

            if (webPartPage == null) {
                return;
            }

            web.Context.Load(webPartPage);
            web.Context.Load(webPartPage.ListItemAllFields);
            web.Context.Load(web.RootFolder);
            web.Context.ExecuteQuery();

            web.RootFolder.WelcomePage = welcomePage;
            web.RootFolder.Update();
            web.Context.ExecuteQuery();

            var limitedWebPartManager = webPartPage.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);
            web.Context.Load(limitedWebPartManager.WebParts);
            web.Context.ExecuteQuery();

            for (var i = 0; i < limitedWebPartManager.WebParts.Count; i++) {
                limitedWebPartManager.WebParts[i].DeleteWebPart();
            }
            web.Context.ExecuteQuery();

            var oWebPartDefinition1 = limitedWebPartManager.ImportWebPart(webPart1.WebPartXml);
            var oWebPartDefinition2 = limitedWebPartManager.ImportWebPart(webPart2.WebPartXml);
            var wpdNew1 = limitedWebPartManager.AddWebPart(oWebPartDefinition1.WebPart, webPart1.WebPartZone, webPart1.WebPartIndex);
            var wpdNew2 = limitedWebPartManager.AddWebPart(oWebPartDefinition2.WebPart, webPart2.WebPartZone, webPart2.WebPartIndex);
            web.Context.Load(wpdNew1);
            web.Context.Load(wpdNew2);
            web.Context.ExecuteQuery();
        }
Ejemplo n.º 9
0
        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 (var file in template.Files)
                {
                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    var folder = web.EnsureFolderPath(folderName);

                    File targetFile = null;

                    var checkedOut = false;

                    targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, file.Src);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            using (var stream = GetFileStream(template, file))
                            {
                                targetFile = UploadFile(template, file, folder, stream);
                            }
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = GetFileStream(template, file))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
                            targetFile = UploadFile(template, file, folder, stream);
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            SetFileProperties(targetFile, transformedProperties, false);
                        }

                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            targetFile.EnsureProperties(f => f.ServerRelativeUrl);

                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl);
                            foreach (var webpart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webpart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = webpart.Title;
                                    wpEntity.WebPartXml = parser.ParseString(webpart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone = webpart.Zone;
                                    wpEntity.WebPartIndex = (int)webpart.Order;
                                    web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                                }
                            }
                        }

                        if (checkedOut)
                        {
                            targetFile.CheckIn("", CheckinType.MajorCheckIn);
                            web.Context.ExecuteQueryRetry();
                        }

                        // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list
                        if (file.Security != null &&
                            (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0))
                        {
                            targetFile.ListItemAllFields.SetSecurity(parser, file.Security);
                        }
                    }

                }
            }
            return parser;
        }
Ejemplo n.º 10
0
        public static bool AddWebPartToPage(string webUrl, string configuredWebPartFileName, string configuredWebPartXmlFilePath, string webPartZoneIndex, string webPartZoneID, string serverRelativePageUrl, string outPutDirectory, string sourceWebPartId = "")
        {
            bool isWebPartAdded = false;
            Web web = null;
            WebPartEntity webPart = new WebPartEntity();
            ClientContext clientContext = null;
            string webPartXml = string.Empty;

            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();
                    clientContext = userContext;

                    webPart.WebPartIndex = Convert.ToInt32(webPartZoneIndex);

                    Logger.LogInfoMessage("[AddWebPartToPage] Successful authentication", false);

                    Logger.LogInfoMessage("[AddWebPartToPage] Checking Out File ...", false);

                    //Prepare Exception Comments
                    exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Configured Web Part File Name: " + configuredWebPartFileName + " , Page Url: " + serverRelativePageUrl;

                    Logger.LogInfoMessage("[AddWebPartToPage] Successful authentication", Constants.Logging);

                    Logger.LogInfoMessage("[AddWebPartToPage] Checking for web part in the Web Part Gallery", Constants.Logging);

                    //check for the target web part in the gallery
                    bool isWebPartInGallery = CheckWebPartOrAppPartPresenceInSite(clientContext, configuredWebPartFileName, configuredWebPartXmlFilePath);

                    if (isWebPartInGallery)
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(configuredWebPartXmlFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            StreamReader reader = new StreamReader(fs);
                            webPart.WebPartXml = reader.ReadToEnd();
                        }

                        webPart.WebPartZone = webPartZoneID;

                        List list = GetPageList(ref clientContext);

                        //Boolean to check if a call to Update method is required
                        bool needsUpdate = false;
                        bool forceCheckOut = false;
                        bool enableVersioning = false;
                        bool enableMinorVersions = false;
                        bool enableModeration = false;
                        DraftVisibilityType dVisibility = DraftVisibilityType.Author;

                        if (list != null)
                        {
                            try
                            {
                                #region Remove Versioning in List

                                Logger.LogInfoMessage(
                                   "[AddWebPart] List Details " + serverRelativePageUrl + ". " +
                                   "Force Check Out: " + forceCheckOut +
                                   "Enable Versioning: " + enableVersioning +
                                   "Enable Minor Versions: " + enableMinorVersions +
                                   "Enable Moderation: " + enableModeration +
                                   "Draft Version Visibility: " + dVisibility);

                                Logger.LogInfoMessage(
                                   "[AddWebPart] Removing Versioning");

                                if (enableVersioning)
                                {
                                    list.EnableVersioning = false;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = false;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = false;
                                    needsUpdate = true;
                                }

                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                            catch (Exception ex)
                            {
                                System.Console.ForegroundColor = System.ConsoleColor.Red;
                                Logger.LogErrorMessage("[AddWebPartToPage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                                System.Console.ResetColor();
                                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartToPage()", ex.GetType().ToString(), exceptionCommentsInfo1);
                            }
                        }

                        try
                        {
                            Logger.LogInfoMessage("[AddWebPartToPage] Adding web part to the page at " + serverRelativePageUrl);
                            isWebPartAdded = AddWebPartt(clientContext.Web, serverRelativePageUrl, webPart, sourceWebPartId);
                        }
                        catch
                        {
                            throw;
                        }
                        finally
                        {
                            if (list != null)
                            {
                                #region Enable Versioning in List
                                //Reset the boolean so that it can used to test if we need to call Update method
                                needsUpdate = false;
                                if (enableVersioning)
                                {
                                    list.EnableVersioning = true;
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    list.DraftVersionVisibility = dVisibility;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = enableModeration;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = true;
                                    needsUpdate = true;
                                }
                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                        }

                    }

                    else
                    {
                        Logger.LogInfoMessage("[AddWebPartToPage]. Target Webpart should be present in the site for the webpart to be added", Constants.Logging);
                        throw new Exception("Target Webpart should be present in the site for the webpart to be added");
                    }

                }

            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[AddWebPartToPage] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartToPage()", ex.GetType().ToString());
                return isWebPartAdded;
            }
            return isWebPartAdded;
        }
Ejemplo n.º 11
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one
                bool isNoScriptSite = web.IsNoScriptSite();

                var context = web.Context as ClientContext;

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

                // Build on the fly the list of additional files coming from the Directories
                var directoryFiles = new List<Model.File>();
                foreach (var directory in template.Directories)
                {
                    var metadataProperties = directory.GetMetadataProperties();
                    directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
                }

                foreach (var file in template.Files.Union(directoryFiles))
                {
                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    if (SkipFile(isNoScriptSite, file.Src, folderName))
                    {
                        // add log message
                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Files_SkipFileUpload, file.Src, folderName);
                        continue;
                    }

                    var folder = web.EnsureFolderPath(folderName);

                    var checkedOut = false;

                    var targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, file.Src);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            using (var stream = GetFileStream(template, file))
                            {
                                targetFile = UploadFile(template, file, folder, stream);
                            }
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = GetFileStream(template, file))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
                            targetFile = UploadFile(template, file, folder, stream);
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            SetFileProperties(targetFile, transformedProperties, false);
                        }

            #if !SP2013
                        bool webPartsNeedLocalization = false;
            #endif
                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            targetFile.EnsureProperties(f => f.ServerRelativeUrl);

                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl).ToList();
                            foreach (var webPart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webPart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = parser.ParseString(webPart.Title);
                                    wpEntity.WebPartXml = parser.ParseString(webPart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone = webPart.Zone;
                                    wpEntity.WebPartIndex = (int)webPart.Order;
                                    var wpd = web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
            #if !SP2013
                                    if (webPart.Title.ContainsResourceToken())
                                    {
                                        // update data based on where it was added - needed in order to localize wp title
            #if !SP2016
                                        wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties);
                                        webPart.Zone = wpd.ZoneId;
            #else
                                        wpd.EnsureProperties(w => w.WebPart, w => w.WebPart.Properties);
            #endif
                                        webPart.Order = (uint)wpd.WebPart.ZoneIndex;
                                        webPartsNeedLocalization = true;
                                    }
            #endif
                                    }
                            }
                        }

            #if !SP2013
                        if (webPartsNeedLocalization)
                        {
                            file.LocalizeWebParts(web, parser, targetFile, scope);
                        }
            #endif

                        switch (file.Level)
                        {
                            case Model.FileLevel.Published:
                                {
                                    targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Published);
                                    break;
                                }
                            case Model.FileLevel.Draft:
                                {
                                    targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Draft);
                                    break;
                                }
                            default:
                                {
                                    if (checkedOut)
                                    {
                                        targetFile.CheckIn("", CheckinType.MajorCheckIn);
                                        web.Context.ExecuteQueryRetry();
                                    }
                                    break;
                                }
                        }

                        // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list
                        if (file.Security != null &&
                            (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0))
                        {
                            targetFile.ListItemAllFields.SetSecurity(parser, file.Security);
                        }
                    }

                }
            }
            return parser;
        }
Ejemplo n.º 12
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.AddList(Microsoft.SharePoint.Client.ListTemplateType.PictureLibrary, "Media", false);
                // Promoted Links library called Links
                this.CreatedSiteContext.Web.AddList(170, new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), "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(new Uri(this.SharePointProvisioningData.Url), 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(new Uri(this.SharePointProvisioningData.Url), 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(new Uri(this.SharePointProvisioningData.Url), 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, "", true);
                //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)), "", true);
                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)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,taskList", new Uri(string.Format("{0}/Lists/Tasks/AllItems.aspx", this.SharePointProvisioningData.Url)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,calendarList", new Uri(string.Format("{0}/Lists/Calendar/calendar.aspx", this.SharePointProvisioningData.Url)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,shareddocuments_Title_15", new Uri(string.Format("{0}/Shared Documents/Forms/AllItems.aspx", this.SharePointProvisioningData.Url)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,linksList", new Uri(string.Format("{0}/Lists/Links/Tiles.aspx", this.SharePointProvisioningData.Url)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,GrpMedia", new Uri(string.Format("{0}/Media/Forms/Thumbnails.aspx", this.SharePointProvisioningData.Url)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,Members_QuickLaunch", new Uri(string.Format("{0}/{1}", this.SharePointProvisioningData.Url, siteMembersUrl)), "", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,category_SiteContents", new Uri(string.Format("{0}/_layouts/15/viewlsts.aspx", this.SharePointProvisioningData.Url)), "", true);

                // 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
                    string[] ownerLogins = new string[this.SharePointProvisioningData.Owners.Length];
                    int i = 0;
                    foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                    {
                        ownerLogins[i] = owner.Login;
                        i++;
                    }
                    this.AppOnlyClientContext.Web.AddAdministratorsTenant(ownerLogins, new Uri(this.SharePointProvisioningData.Url));

                    // 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));
                this.CreatedSiteContext.Web.DeployThemeToWeb(contosoCollaborationThemeName, spColorFile, spFontFile, backgroundFile, "");
                this.CreatedSiteContext.Web.SetThemeToWeb(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;
        }
Ejemplo n.º 13
0
        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.RootFolder.WelcomePage);

                // Check if this is not a noscript site as we're not allowed to update some properties
                bool isNoScriptSite = web.IsNoScriptSite();

                foreach (var page in template.Pages)
                {
                    var url = parser.ParseString(page.Url);

                    if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                    {
                        url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                    }

                    var exists = true;
                    Microsoft.SharePoint.Client.File file = null;
                    try
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }
                    if (exists)
                    {
                        if (page.Overwrite)
                        {
                            try
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);

                                if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
                                    web.SetHomePage(string.Empty);

                                file.DeleteObject();
                                web.Context.ExecuteQueryRetry();
                                web.AddWikiPageByUrl(url);
                                if (page.Layout == WikiPageLayout.Custom)
                                {
                                    web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                                }
                                else
                                {
                                    web.AddLayoutToWikiPage(page.Layout, url);
                                }
                            }
                            catch (Exception ex)
                            {
                                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);

                            web.AddWikiPageByUrl(url);
                            if (page.Layout == WikiPageLayout.Custom)
                            {
                                web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                            }
                            else
                            {
                                web.AddLayoutToWikiPage(page.Layout, url);
                            }
                        }
                        catch (Exception ex)
                        {
                            scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                        }
                    }

                    if (page.WelcomePage)
                    {
                        web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
                        var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                        web.SetHomePage(rootFolderRelativeUrl);
                    }

            #if !SP2013
                    bool webPartsNeedLocalization = false;
            #endif
                    if (page.WebParts != null & page.WebParts.Any())
                    {
                        if (!isNoScriptSite)
                        {
                            var existingWebParts = web.GetWebParts(url);

                            foreach (var webPart in page.WebParts)
                            {
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null)
                                {
                                    WebPartEntity wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = parser.ParseString(webPart.Title);
                                    wpEntity.WebPartXml = parser.ParseString(webPart.Contents.Trim(new[] { '\n', ' ' }));
                                    var wpd = web.AddWebPartToWikiPage(url, wpEntity, (int)webPart.Row, (int)webPart.Column, false);
            #if !SP2013
                                    if (webPart.Title.ContainsResourceToken())
                                    {
                                        // update data based on where it was added - needed in order to localize wp title
            #if !SP2016
                                        wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties);
                                        webPart.Zone = wpd.ZoneId;
            #else
                                        wpd.EnsureProperties(w => w.WebPart, w => w.WebPart.Properties);
            #endif
                                        webPart.Order = (uint)wpd.WebPart.ZoneIndex;
                                        webPartsNeedLocalization = true;
                                   }
            #endif
                                    }
                                }
                            var allWebParts = web.GetWebParts(url);
                            foreach (var webpart in allWebParts)
                            {
                                parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id));
                            }
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Pages_SkipAddingWebParts, page.Url);
                        }
                    }

            #if !SP2013
                    if (webPartsNeedLocalization)
                    {
                        page.LocalizeWebParts(web, parser, scope);
                    }
            #endif

                    file = web.GetFileByServerRelativeUrl(url);
                    file.EnsureProperty(f => f.ListItemAllFields);

                    if (page.Fields.Any())
                    {
                        var item = file.ListItemAllFields;
                        foreach (var fieldValue in page.Fields)
                        {
                            item[fieldValue.Key] = parser.ParseString(fieldValue.Value);
                        }
                        item.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    if (page.Security != null && page.Security.RoleAssignments.Count != 0)
                    {
                        web.Context.Load(file.ListItemAllFields);
                        web.Context.ExecuteQueryRetry();
                        file.ListItemAllFields.SetSecurity(parser, page.Security);
                    }
                }
            }
            return parser;
        }
Ejemplo n.º 14
0
 protected void btnAddDialogLinkOnPage_Click(object sender, EventArgs e)
 {
     string scenario1Page = String.Format("scenario1-{0}.aspx", DateTime.Now.Ticks);
     string scenario1PageUrl = cc.Web.AddWikiPage("Site Pages", scenario1Page);
     cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.OneColumn, scenario1Page);
     WebPartEntity scriptEditorWp = new WebPartEntity();
     scriptEditorWp.WebPartXml = ScriptEditorWebPart();
     scriptEditorWp.WebPartIndex = 1;
     scriptEditorWp.WebPartTitle = "Script editor test";            
     cc.Web.AddWebPartToWikiPage("SitePages", scriptEditorWp, scenario1Page, 1, 1, false);
     this.hplScenario1.NavigateUrl = string.Format("{0}/{1}", Request.QueryString["SPHostUrl"], scenario1PageUrl);
 }
        //sourceWebPartId - Used to update the content of the wikipage with new web part id [Fix for BugId - 95007]
        public bool AddWebPart(string webUrl, string configuredWebPartFileName, string configuredWebPartXmlFilePath, string webPartZoneIndex, string webPartZoneID, string serverRelativePageUrl, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A", string ActionType = "web", string sourceWebPartId = "")
        {
            bool isWebPartAdded = false;

            WebPartEntity webPart = new WebPartEntity();
            webPart.WebPartIndex = Convert.ToInt32(webPartZoneIndex);
            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            string webPartXml = string.Empty;

            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;
            try
            {
                if (ActionType.ToLower() == Constants.ActionType_Web.ToLower())
                {
                    //Initialized Exception and Logger.
                    WebPart_Initialization(outPutDirectory);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Started - AddWebPart ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Started - AddWebPart ##############");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[DATE TIME] " + Logger.CurrentDateTime());
                    Console.WriteLine("[DATE TIME] " + Logger.CurrentDateTime());

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                    Console.WriteLine("[AddWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                }

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Configured Web Part File Name: " + configuredWebPartFileName + " , Page Url: " + serverRelativePageUrl;

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.OnPremise.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][AddWebPart] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(webUrl, UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][AddWebPart] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.Online.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][AddWebPart] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(webUrl, UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][AddWebPart] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                }

                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Successful authentication");
                    Console.WriteLine("[AddWebPart] Successful authentication");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Checking for web part in the Web Part Gallery");
                    Console.WriteLine("[AddWebPart] Checking for web part in the Web Part Gallery");

                    //check for the target web part in the gallery
                    bool isWebPartInGallery = CheckWebPartOrAppPartPresenceInSite(clientContext, configuredWebPartFileName, configuredWebPartXmlFilePath);

                    if (isWebPartInGallery)
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(configuredWebPartXmlFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            StreamReader reader = new StreamReader(fs);
                            webPart.WebPartXml = reader.ReadToEnd();
                        }

                        webPart.WebPartZone = webPartZoneID;

                        List list = GetPageList(ref clientContext);

                        //Boolean to check if a call to Update method is required
                        bool needsUpdate = false;
                        bool forceCheckOut = false;
                        bool enableVersioning = false;
                        bool enableMinorVersions = false;
                        bool enableModeration = false;
                        DraftVisibilityType dVisibility = DraftVisibilityType.Author;

                        if (list != null)
                        {
                            try
                            {
                                #region Remove Versioning in List

                                Logger.AddMessageToTraceLogFile(Constants.Logging,
                                    "[AddWebPart] List Details " + serverRelativePageUrl + ". " +
                                    "Force Check Out: " + forceCheckOut +
                                    "Enable Versioning: " + enableVersioning +
                                    "Enable Minor Versions: " + enableMinorVersions +
                                    "Enable Moderation: " + enableModeration +
                                    "Draft Version Visibility: " + dVisibility);

                                Logger.AddMessageToTraceLogFile(Constants.Logging,
                                    "[AddWebPart] Removing Versioning");

                                if (enableVersioning)
                                {
                                    list.EnableVersioning = false;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = false;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = false;
                                    needsUpdate = true;
                                }

                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                            catch (Exception ex)
                            {
                                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "AddWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][AddWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("[EXCEPTION][AddWebPart] Exception Message: " + ex.Message);
                                Console.ForegroundColor = ConsoleColor.Gray;

                            }
                        }

                        try
                        {

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Adding web part to the page at " + serverRelativePageUrl);
                            Console.WriteLine("[AddWebPart] Adding web part to the page at " + serverRelativePageUrl);
                            isWebPartAdded = AddWebPart(clientContext.Web, serverRelativePageUrl, webPart, sourceWebPartId);
                        }
                        catch
                        {
                            throw;
                        }
                        finally
                        {
                            if (list != null)
                            {
                                #region Enable Versioning in List
                                //Reset the boolean so that it can used to test if we need to call Update method
                                needsUpdate = false;
                                if (enableVersioning)
                                {
                                    list.EnableVersioning = true;
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    list.DraftVersionVisibility = dVisibility;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = enableModeration;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = true;
                                    needsUpdate = true;
                                }
                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                        }
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Successfully Added the newly configured WebPart");

                        Console.WriteLine("[AddWebPart] Successfully Added the newly configured WebPart");
                    }
                    else
                    {
                        throw new Exception("Target Webpart should be present in the site for the webpart to be added");
                    }
                }

                if (ActionType.ToLower() == Constants.ActionType_Web.ToLower())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - AddWebPart ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - AddWebPart ##############");
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "AddWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][AddWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][AddWebPart] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                return isWebPartAdded;
            }
            return isWebPartAdded;
        }
        //sourceWebPartId - Used to update the content of the wikipage with new web part id [Fix for BugId - 95007]
        private bool AddWebPart(Web web, string serverRelativePageUrl, WebPartEntity webPartEntity,string sourceWebPartId="")
        {
            bool isWebPartAdded = false;
            Microsoft.SharePoint.Client.File webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

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

            LimitedWebPartManager webPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);

            WebPartDefinition importedWebPart = webPartManager.ImportWebPart(webPartEntity.WebPartXml);
            WebPartDefinition webPart = webPartManager.AddWebPart(importedWebPart.WebPart, webPartEntity.WebPartZone, webPartEntity.WebPartIndex);
            web.Context.Load(webPart);
            web.Context.ExecuteQuery();

            CheckForWikiFieldOrPublishingPageContentAndUpdate(webPart, web, webPartPage, sourceWebPartId);

            isWebPartAdded = true;

            return isWebPartAdded;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <param name="page">Page to add the web part on</param>
        public static void AddWebPartToWebPartPage(this Web web, WebPartEntity webPart, string page)
        {
            //Note: getfilebyserverrelativeurl did not work...not sure why not
            Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl("");
            web.Context.Load(pagesLib.Files);
            web.Context.ExecuteQuery();

            Microsoft.SharePoint.Client.File webPartPage = null;

            foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
            {
                if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                {
                    webPartPage = aspxFile;
                    break;
                }
            }

            if (webPartPage == null)
            {
                return;
            }

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

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml);

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.WebPartZone, webPart.WebPartIndex);
            web.Context.ExecuteQuery();
        }
Ejemplo n.º 18
0
        protected void btnScenario2_Click(object sender, EventArgs e)
        {
            if (!cc.Web.ListExists("Links"))
            {
                cc.Web.CreateList(new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), 170, "Links", false);

                AddPromotedSiteLink(cc, cc.Web, "Links", "Office 365 Dev PnP", "http://aka.ms/officedevpnp");
                AddPromotedSiteLink(cc, cc.Web, "Links", "Bing", "http://www.bing.com");
            }            
            
            string scenario2Page = String.Format("scenario2-{0}.aspx", DateTime.Now.Ticks);
            string scenario2PageUrl = cc.Web.AddWikiPage("Site Pages", scenario2Page);

            bool twoColumnsOrMore = false;
            bool header = false;
            switch (drpLayouts.SelectedValue)
            {
                case "OneColumn":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.OneColumn, scenario2Page);
                    break;
                case "OneColumnSideBar":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.OneColumnSideBar, scenario2Page);
                    break;
                case "TwoColumns":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumns, scenario2Page);
                    twoColumnsOrMore = true;
                    break;
                case "TwoColumnsHeader":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumnsHeader, scenario2Page);
                    twoColumnsOrMore = true;
                    header = true;
                    break;
                case "TwoColumnsHeaderFooter":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumnsHeaderFooter, scenario2Page);
                    twoColumnsOrMore = true;
                    header = true;
                    break;
                case "ThreeColumns":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.ThreeColumns, scenario2Page);
                    twoColumnsOrMore = true;
                    break;
                case "ThreeColumnsHeader":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.ThreeColumnsHeader, scenario2Page);
                    twoColumnsOrMore = true;
                    header = true;
                    break;
                case "ThreeColumnsHeaderFooter":
                    cc.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.ThreeColumnsHeaderFooter, scenario2Page);
                    twoColumnsOrMore = true;
                    header = true;
                    break;
                default:
                    break;
            }

            Guid linksID = cc.Web.GetListID("Links");
            WebPartEntity wp2 = new WebPartEntity();
            wp2.WebPartXml = WpPromotedLinks(linksID, string.Format("{0}/Lists/{1}", Request.QueryString["SPHostUrl"], "Links"), string.Format("{0}/{1}", Request.QueryString["SPHostUrl"], scenario2PageUrl), "$Resources:core,linksList");
            wp2.WebPartIndex = 1;
            wp2.WebPartTitle = "Links";

            int webpartRow = 1;
            if (header)
            {
                webpartRow = 2;
            }

            cc.Web.AddWebPartToWikiPage("SitePages", wp2, scenario2Page, webpartRow, 1, false);
            Session.Add("LastPageName", scenario2Page);

            if (twoColumnsOrMore)
            {
                cc.Web.AddHtmlToWikiPage("SitePages", txtHtml.Text, scenario2Page, webpartRow, 2);
            }

            this.hplScenario2.NavigateUrl = string.Format("{0}/{1}", Request.QueryString["SPHostUrl"], scenario2PageUrl);
            this.btnScenario2Remove.Enabled = true;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Add web part to a wiki style page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="folder">System name of the wiki page library - typically sitepages</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <param name="page">Page to add the web part on</param>
        /// <param name="row">Row of the wiki table that should hold the inserted web part</param>
        /// <param name="col">Column of the wiki table that should hold the inserted web part</param>
        /// <param name="addSpace">Does a blank line need to be added after the web part (to space web parts)</param>
        /// <exception cref="System.ArgumentException">Thrown when folder or page is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when folder, webPart or page is null</exception>
        public static void AddWebPartToWikiPage(this Web web, string folder, WebPartEntity webPart, string page, int row, int col, bool addSpace)
        {
            if (string.IsNullOrEmpty(folder))
            {
                throw (folder == null)
                  ? new ArgumentNullException("folder")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "folder");
            }

            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            if (string.IsNullOrEmpty(page))
            {
                throw (page == null)
                  ? new ArgumentNullException("page")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "page");
            }

            if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                web.Context.ExecuteQuery();
            }

            var webServerRelativeUrl = UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl);
            var serverRelativeUrl = UrlUtility.Combine(folder, page);
            AddWebPartToWikiPage(web, webServerRelativeUrl + serverRelativeUrl, webPart, row, col, addSpace);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Creates web part entity with the Yammer OpenGraph structure on it for specific URL
 /// </summary>
 /// <param name="yammerNetworkName"></param>
 /// <param name="url"></param>
 /// <param name="showHeader"></param>
 /// <param name="showFooter"></param>
 /// <param name="postTitle"></param>
 /// <param name="postImageUrl"></param>
 /// <param name="defaultGroupId"></param>
 /// <returns></returns>
 public static WebPartEntity GetYammerOpenGraphDiscussionPart(string yammerNetworkName, string url, bool showHeader, bool showFooter, string postTitle = "", string postImageUrl = "", string defaultGroupId = "")
 {
     WebPartEntity wpYammer = new WebPartEntity();
     wpYammer.WebPartXml = CreateYammerOpenGraphDiscussionPartXml(yammerNetworkName, url, showHeader, showFooter, postTitle, postImageUrl, true, defaultGroupId);
     wpYammer.WebPartIndex = 0;
     wpYammer.WebPartTitle = "Yammer";
     return wpYammer;
 }
Ejemplo n.º 21
0
        public static void AddWebPartToWikiPage(this Web web, string serverRelativePageUrl, WebPartEntity webPart, int row, int col, bool addSpace)
        {
            if (string.IsNullOrEmpty(serverRelativePageUrl))
            {
                throw (serverRelativePageUrl == null)
                  ? new ArgumentNullException("serverRelativePageUrl")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "serverRelativePageUrl");
            }

            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            File webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

            if (webPartPage == null)
            {
                return;
            }

            web.Context.Load(webPartPage);
            web.Context.Load(webPartPage.ListItemAllFields);
            web.Context.ExecuteQuery();

            string wikiField = (string)webPartPage.ListItemAllFields["WikiField"];

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml);
            WebPartDefinition wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "wpz", 0);
            web.Context.Load(wpdNew);
            web.Context.ExecuteQuery();

            //HTML structure in default team site home page (W16)
            //<div class="ExternalClass284FC748CB4242F6808DE69314A7C981">
            //  <div class="ExternalClass5B1565E02FCA4F22A89640AC10DB16F3">
            //    <table id="layoutsTable" style="width&#58;100%;">
            //      <tbody>
            //        <tr style="vertical-align&#58;top;">
            //          <td colspan="2">
            //            <div class="ms-rte-layoutszone-outer" style="width&#58;100%;">
            //              <div class="ms-rte-layoutszone-inner" style="word-wrap&#58;break-word;margin&#58;0px;border&#58;0px;">
            //                <div><span><span><div class="ms-rtestate-read ms-rte-wpbox"><div class="ms-rtestate-read 9ed0c0ac-54d0-4460-9f1c-7e98655b0847" id="div_9ed0c0ac-54d0-4460-9f1c-7e98655b0847"></div><div class="ms-rtestate-read" id="vid_9ed0c0ac-54d0-4460-9f1c-7e98655b0847" style="display&#58;none;"></div></div></span></span><p> </p></div>
            //                <div class="ms-rtestate-read ms-rte-wpbox">
            //                  <div class="ms-rtestate-read c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" id="div_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0"></div>
            //                  <div class="ms-rtestate-read" id="vid_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" style="display&#58;none;"></div>
            //                </div>
            //              </div>
            //            </div>
            //          </td>
            //        </tr>
            //        <tr style="vertical-align&#58;top;">
            //          <td style="width&#58;49.95%;">
            //            <div class="ms-rte-layoutszone-outer" style="width&#58;100%;">
            //              <div class="ms-rte-layoutszone-inner" style="word-wrap&#58;break-word;margin&#58;0px;border&#58;0px;">
            //                <div class="ms-rtestate-read ms-rte-wpbox">
            //                  <div class="ms-rtestate-read b55b18a3-8a3b-453f-a714-7e8d803f4d30" id="div_b55b18a3-8a3b-453f-a714-7e8d803f4d30"></div>
            //                  <div class="ms-rtestate-read" id="vid_b55b18a3-8a3b-453f-a714-7e8d803f4d30" style="display&#58;none;"></div>
            //                </div>
            //              </div>
            //            </div>
            //          </td>
            //          <td class="ms-wiki-columnSpacing" style="width&#58;49.95%;">
            //            <div class="ms-rte-layoutszone-outer" style="width&#58;100%;">
            //              <div class="ms-rte-layoutszone-inner" style="word-wrap&#58;break-word;margin&#58;0px;border&#58;0px;">
            //                <div class="ms-rtestate-read ms-rte-wpbox">
            //                  <div class="ms-rtestate-read 0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" id="div_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95"></div>
            //                  <div class="ms-rtestate-read" id="vid_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" style="display&#58;none;"></div>
            //                </div>
            //              </div>
            //            </div>
            //          </td>
            //        </tr>
            //      </tbody>
            //    </table>
            //    <span id="layoutsData" style="display&#58;none;">true,false,2</span>
            //  </div>
            //</div>

            XmlDocument xd = new XmlDocument();
            xd.PreserveWhitespace = true;
            xd.LoadXml(wikiField);

            // Sometimes the wikifield content seems to be surrounded by an additional div?
            XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement;
            if (layoutsTable == null)
            {
                layoutsTable = xd.SelectSingleNode("div/table") as XmlElement;
            }

            XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement;
            // - space element
            XmlElement space = xd.CreateElement("p");
            XmlText text = xd.CreateTextNode(" ");
            space.AppendChild(text);

            // - wpBoxDiv
            XmlElement wpBoxDiv = xd.CreateElement("div");
            layoutsZoneInner.AppendChild(wpBoxDiv);

            if (addSpace)
            {
                layoutsZoneInner.AppendChild(space);
            }

            XmlAttribute attribute = xd.CreateAttribute("class");
            wpBoxDiv.Attributes.Append(attribute);
            attribute.Value = "ms-rtestate-read ms-rte-wpbox";
            attribute = xd.CreateAttribute("contentEditable");
            wpBoxDiv.Attributes.Append(attribute);
            attribute.Value = "false";
            // - div1
            XmlElement div1 = xd.CreateElement("div");
            wpBoxDiv.AppendChild(div1);
            div1.IsEmpty = false;
            attribute = xd.CreateAttribute("class");
            div1.Attributes.Append(attribute);
            attribute.Value = "ms-rtestate-read " + wpdNew.Id.ToString("D");
            attribute = xd.CreateAttribute("id");
            div1.Attributes.Append(attribute);
            attribute.Value = "div_" + wpdNew.Id.ToString("D");
            // - div2
            XmlElement div2 = xd.CreateElement("div");
            wpBoxDiv.AppendChild(div2);
            div2.IsEmpty = false;
            attribute = xd.CreateAttribute("style");
            div2.Attributes.Append(attribute);
            attribute.Value = "display:none";
            attribute = xd.CreateAttribute("id");
            div2.Attributes.Append(attribute);
            attribute.Value = "vid_" + wpdNew.Id.ToString("D");

            ListItem listItem = webPartPage.ListItemAllFields;
            listItem["WikiField"] = xd.OuterXml;
            listItem.Update();
            web.Context.ExecuteQuery();
        }
Ejemplo n.º 22
0
        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.RootFolder.WelcomePage);

                foreach (var page in template.Pages)
                {
                    var url = parser.ParseString(page.Url);

                    if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                    {
                        url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                    }

                    var exists = true;
                    Microsoft.SharePoint.Client.File file = null;
                    try
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQuery();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }
                    if (exists)
                    {
                        if (page.Overwrite)
                        {
                            try
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);

                                if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
                                    web.SetHomePage(string.Empty);

                                file.DeleteObject();
                                web.Context.ExecuteQueryRetry();
                                web.AddWikiPageByUrl(url);
                                if (page.Layout == WikiPageLayout.Custom)
                                {
                                    web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                                }
                                else {
                                    web.AddLayoutToWikiPage(page.Layout, url);
                                }
                            }
                            catch (Exception ex)
                            {
                                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);

                            web.AddWikiPageByUrl(url);
                            web.AddLayoutToWikiPage(page.Layout, url);
                        }
                        catch (Exception ex)
                        {
                            scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                        }
                    }

                    if (page.WelcomePage)
                    {
                        web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
                        var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                        web.SetHomePage(rootFolderRelativeUrl);
                    }

                    if (page.WebParts != null & page.WebParts.Any())
                    {
                        var existingWebParts = web.GetWebParts(url);

                        foreach (var webpart in page.WebParts)
                        {
                            if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                            {
                                WebPartEntity wpEntity = new WebPartEntity();
                                wpEntity.WebPartTitle = webpart.Title;
                                wpEntity.WebPartXml = parser.ParseString(webpart.Contents.Trim(new[] { '\n', ' ' }));
                                web.AddWebPartToWikiPage(url, wpEntity, (int)webpart.Row, (int)webpart.Column, false);
                            }
                        }
                        var allWebParts = web.GetWebParts(url);
                        foreach (var webpart in allWebParts)
                        {
                            parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id));
                        }
                    }

                    file = web.GetFileByServerRelativeUrl(url);
                    file.EnsureProperty(f => f.ListItemAllFields);

                    if (page.Fields.Any())
                    {
                        var item = file.ListItemAllFields;
                        foreach (var fieldValue in page.Fields)
                        {
                            item[fieldValue.Key] = parser.ParseString(fieldValue.Value);
                        }
                        item.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    if (page.Security != null && page.Security.RoleAssignments.Count != 0)
                    {
                        web.Context.Load(file.ListItemAllFields);
                        web.Context.ExecuteQuery();
                        file.ListItemAllFields.SetSecurity(parser, page.Security);
                    }
                }
            }
            return parser;
        }
Ejemplo n.º 23
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Pages);

            var context = web.Context as ClientContext;

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

            foreach (var page in template.Pages)
            {
                var url = page.Url.ToParsedString();


                if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                {
                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                }


                var exists = true;
                Microsoft.SharePoint.Client.File file = null;
                try
                {
                    file = web.GetFileByServerRelativeUrl(url);
                    web.Context.Load(file);
                    web.Context.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                    {
                        exists = false;
                    }
                }
                if (exists)
                {
                    if (page.Overwrite)
                    {
                        file.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                        web.AddWikiPageByUrl(url);
                        web.AddLayoutToWikiPage(page.Layout, url);
                    }
                }
                else
                {
                    web.AddWikiPageByUrl(url);
                    web.AddLayoutToWikiPage(page.Layout, url);
                }

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

                    var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                    web.SetHomePage(rootFolderRelativeUrl);
                }

                if (page.WebParts != null & page.WebParts.Any())
                {
                    var existingWebParts = web.GetWebParts(url);

                    foreach (var webpart in page.WebParts)
                    {
                        if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                        {
                            WebPartEntity wpEntity = new WebPartEntity();
                            wpEntity.WebPartTitle = webpart.Title;
                            wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] {'\n', ' '});
                            web.AddWebPartToWikiPage(url, wpEntity, (int)webpart.Row, (int)webpart.Column, false);
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Files))
            {
                var context = web.Context as ClientContext;

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

                foreach (var file in template.Files)
                {

                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    var folder = web.EnsureFolderPath(folderName);

                    File targetFile = null;

                    var checkedOut = false;

                    targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_,file.Src);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            using (var stream = template.Connector.GetFileStream(file.Src))
                            {
                                targetFile = folder.UploadFile(template.Connector.GetFilenamePart(file.Src), stream, file.Overwrite);
                            }
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = template.Connector.GetFileStream(file.Src))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
                            targetFile = folder.UploadFile(template.Connector.GetFilenamePart(file.Src), stream, file.Overwrite);
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            targetFile.SetFileProperties(transformedProperties, false); // if needed, the file is already checked out
                        }

                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            if (!targetFile.IsPropertyAvailable("ServerRelativeUrl"))
                            {
                                web.Context.Load(targetFile, f => f.ServerRelativeUrl);
                                web.Context.ExecuteQuery();
                            }
                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl);
                            foreach (var webpart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page,webpart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = webpart.Title;
                                    wpEntity.WebPartXml = parser.ParseString(webpart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone = webpart.Zone;
                                    wpEntity.WebPartIndex = (int)webpart.Order;

                                    web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                                }
                            }
                        }

                        if (checkedOut)
                        {
                            targetFile.CheckIn("", CheckinType.MajorCheckIn);
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                }
            }
            return parser;
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates web part entity with the Yammer group structure on it
 /// </summary>
 /// <param name="yammerNetworkName"></param>
 /// <param name="yammerGroupId"></param>
 /// <param name="showHeader"></param>
 /// <param name="showFooter"></param>
 /// <returns></returns>
 public static WebPartEntity GetYammerGroupDiscussionPart(string yammerNetworkName, int yammerGroupId, bool showHeader, bool showFooter)
 {
     WebPartEntity wpYammer = new WebPartEntity();
     wpYammer.WebPartXml = CreateYammerGroupDiscussionPartXml(yammerNetworkName, yammerGroupId, showHeader, showFooter);
     wpYammer.WebPartIndex = 0;
     wpYammer.WebPartTitle = "Yammer";
     return wpYammer;
 }
Ejemplo n.º 26
0
        private static WebPartDefinition AddWebPart(File webPartPage, WebPartEntity webPart, string zoneId, int zoneIndex)
        {
            var limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            var oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml);

            var wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, zoneId, zoneIndex);
            webPartPage.Context.Load(wpdNew);
            webPartPage.Context.ExecuteQueryRetry();

            WebPartPostProcessorFactory.Resolve(webPart.WebPartXml).Process(wpdNew, webPartPage);

            return wpdNew;
        }
Ejemplo n.º 27
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Files);

            var context = web.Context as ClientContext;

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

            foreach (var file in template.Files)
            {

                var folderName = file.Folder.ToParsedString();

                if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                {
                    folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                }


                var folder = web.EnsureFolderPath(folderName);

                Microsoft.SharePoint.Client.File targetFile = null;
                var checkedOut = false;

                targetFile = folder.GetFile(file.Src);

                if (targetFile != null)
                {
                    if (file.Overwrite)
                    {
                        checkedOut = CheckOutIfNeeded(web, targetFile);

                        using (var stream = template.Connector.GetFileStream(file.Src))
                        {
                            targetFile = folder.UploadFile(file.Src, stream, file.Overwrite);
                        }
                    }
                    else
                    {
                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }
                }
                else
                {
                    using (var stream = template.Connector.GetFileStream(file.Src))
                    {
                        targetFile = folder.UploadFile(file.Src, stream, file.Overwrite);
                    }

                    checkedOut = CheckOutIfNeeded(web, targetFile);
                }

                if (targetFile != null)
                {
                    if (file.Properties != null && file.Properties.Any())
                    {
                        Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => property.Value.ToParsedString());
                        targetFile.SetFileProperties(transformedProperties, false); // if needed, the file is already checked out
                    }

                    if (file.WebParts != null && file.WebParts.Any())
                    {
                        if (!targetFile.IsPropertyAvailable("ServerRelativeUrl"))
                        {
                            web.Context.Load(targetFile, f => f.ServerRelativeUrl);
                            web.Context.ExecuteQuery();
                        }
                        var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl);
                        foreach (var webpart in file.WebParts)
                        {
                            // check if the webpart is already set on the page
                            if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                            {
                                var wpEntity = new WebPartEntity();
                                wpEntity.WebPartTitle = webpart.Title;
                                wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] { '\n', ' ' });
                                wpEntity.WebPartZone = webpart.Zone;
                                wpEntity.WebPartIndex = (int) webpart.Order;

                                web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                            }
                        }
                    }
                  
                    if (checkedOut)
                    {
                        targetFile.CheckIn("", CheckinType.MajorCheckIn);
                        web.Context.ExecuteQueryRetry();
                    }
                }

            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="serverRelativePageUrl">Page to add the web part on</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <exception cref="System.ArgumentException">Thrown when serverRelativePageUrl is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when serverRelativePageUrl or webPart is null</exception>
        public static void AddWebPartToWebPartPage(this Web web, string serverRelativePageUrl, WebPartEntity webPart)
        {
            if (string.IsNullOrEmpty(serverRelativePageUrl))
            {
                throw (serverRelativePageUrl == null)
                  ? new ArgumentNullException("serverRelativePageUrl")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "serverRelativePageUrl");
            }

            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            var webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

            if (webPartPage == null)
            {
                return;
            }

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

            AddWebPart(webPartPage, webPart, webPart.WebPartZone, webPart.WebPartIndex);
        }
Ejemplo n.º 29
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Pages))
            {

                var context = web.Context as ClientContext;

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

                foreach (var page in template.Pages)
                {
                    var url = parser.ParseString(page.Url);

                    if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                    {
                        url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                    }

                    var exists = true;
                    Microsoft.SharePoint.Client.File file = null;
                    try
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQuery();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }
                    if (exists)
                    {
                        if (page.Overwrite)
                        {
                            try
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);
                                file.DeleteObject();
                                web.Context.ExecuteQueryRetry();
                                web.AddWikiPageByUrl(url);
                                web.AddLayoutToWikiPage(page.Layout, url);
                            }
                            catch (Exception ex)
                            {
                                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_,url,ex.Message,ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        try
                        {

                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);

                            web.AddWikiPageByUrl(url);
                            web.AddLayoutToWikiPage(page.Layout, url);
                        }
                        catch (Exception ex)
                        {
                            scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_,url, ex.Message,ex.StackTrace);
                        }
                    }

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

                        var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                        web.SetHomePage(rootFolderRelativeUrl);
                    }

                    if (page.WebParts != null & page.WebParts.Any())
                    {
                        var existingWebParts = web.GetWebParts(url);

                        foreach (var webpart in page.WebParts)
                        {
                            if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                            {
                                WebPartEntity wpEntity = new WebPartEntity();
                                wpEntity.WebPartTitle = webpart.Title;
                                wpEntity.WebPartXml = parser.ParseString(webpart.Contents).Trim(new[] {'\n', ' '});
                                web.AddWebPartToWikiPage(url, wpEntity, (int) webpart.Row, (int) webpart.Column, false);
                            }
                        }
                    }
                }
            }
            return parser;
        }
Ejemplo n.º 30
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Pages);

            var context = web.Context as ClientContext;

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

            foreach (var page in template.PublishingPages)
            {
                var url = String.Format("{0}/Pages/{1}.aspx", web.ServerRelativeUrl, page.PageName);


                if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                {
                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                }


                var exists = true;
                Microsoft.SharePoint.Client.File file = null;
                try
                {
                    file = web.GetFileByServerRelativeUrl(url);
                    web.Context.Load(file);
                    web.Context.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                    {
                        exists = false;
                    }
                }

                if (exists)
                {
                    if (page.Overwrite)
                    {
                        file.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                        web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish);
                    }

                    //if (file.CheckOutType == CheckOutType.None)
                    //{
                    //    file.CheckOut();
                    //}
                }
                else
                {
                    web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish);

                    
                }

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

                    var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                    web.SetHomePage(rootFolderRelativeUrl);
                }

                // Check out the file if needed
                
                
                

                if (page.WebParts != null & page.WebParts.Any())
                {
                    if (!exists)
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQuery();
                    }
                    file.CheckOut();    
                                    

                    var existingWebParts = web.GetWebParts(url);

                    foreach (var webpart in page.WebParts)
                    {
                        if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                        {
                            WebPartEntity wpEntity = new WebPartEntity();
                            wpEntity.WebPartTitle = webpart.Title;
                            wpEntity.WebPartIndex = (int)webpart.Order;
                            wpEntity.WebPartZone = webpart.Zone;

                            if (!string.IsNullOrWhiteSpace(webpart.ListUrl))
                            {
                                var list = web.GetListByUrl(webpart.ListUrl);

                                var contents = String.Format(webpart.Contents, list.Id, list.Title);
                                wpEntity.WebPartXml = contents.Trim(new[] { '\n', ' ' });
                            }
                            else
                            {
                                wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] { '\n', ' ' });
                            }

                            //wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] {'\n', ' '});
                            web.AddWebPartToWebPartPage(url, wpEntity);
                        }
                    }

                    file.CheckIn("", CheckinType.MajorCheckIn);
                    file.Publish("");
                }
            }
        }