private static void AddPublishingPage(ClientContext context, PublishingWeb webPub, ListItemCollection allPageLayouts, OfficeDevPnP.Core.Framework.Provisioning.Model.PublishingPage page)
        {
            ListItem layout = null;

            //try to get layout by Title
            layout = allPageLayouts.Where(x => x["Title"] != null && x["Title"].ToString().Equals(page.Layout)).FirstOrDefault();

            //try to get layout by DisplayName
            if (layout == null)
            {
                layout = allPageLayouts.Where(x => x.DisplayName == page.Layout).FirstOrDefault();
            }

            //we need to have a layout for a publishing page
            if (layout == null)
            {
                throw new ArgumentNullException(string.Format("Layout '{0}' for page {1} can not be found.", page.Layout, page.Name));
            }

            context.Load(layout);

            // Create a publishing page
            PublishingPageInformation publishingPageInfo = new PublishingPageInformation();

            publishingPageInfo.Name = page.Name;
            publishingPageInfo.PageLayoutListItem = layout;

            Microsoft.SharePoint.Client.Publishing.PublishingPage publishingPage = webPub.AddPublishingPage(publishingPageInfo);

            //publishingPage.ListItem.File.Approve(string.Empty);

            context.Load(publishingPage);
            context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);
            context.ExecuteQuery();
        }
    public static void CreatePublishingPage(ClientContext ctx, string pageName, string pageLayoutName)
    {
        var pubWeb   = PublishingWeb.GetPublishingWeb(ctx, ctx.Web);
        var pageInfo = new PublishingPageInformation();

        pageInfo.Name = pageName;
        pageInfo.PageLayoutListItem = GetPageLayout(ctx, pageLayoutName);
        var publishingPage = pubWeb.AddPublishingPage(pageInfo);

        ctx.ExecuteQuery();
    }
Esempio n. 3
0
        public static void CreatePublishingPage(ClientContext clientContext, string pageName, string pagelayoutname, string url, string queryurl)
        {
            var publishingPageName = pageName + ".aspx";

            Web web = clientContext.Web;

            clientContext.Load(web);

            List pages = web.Lists.GetByTitle("Pages");

            clientContext.Load(pages.RootFolder, f => f.ServerRelativeUrl);
            clientContext.ExecuteQuery();

            Microsoft.SharePoint.Client.File file =
                web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx");
            clientContext.Load(file, f => f.Exists);
            clientContext.ExecuteQuery();
            if (file.Exists)
            {
                file.DeleteObject();
                clientContext.ExecuteQuery();
            }
            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web);

            clientContext.Load(publishingWeb);

            if (publishingWeb != null)
            {
                List publishingLayouts = clientContext.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");

                ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pagelayoutname));
                clientContext.ExecuteQuery();

                ListItem layout = allItems.Where(x => x.DisplayName == pagelayoutname).FirstOrDefault();
                clientContext.Load(layout);

                PublishingPageInformation publishingpageInfo = new PublishingPageInformation()
                {
                    Name = publishingPageName,
                    PageLayoutListItem = layout,
                };

                PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingpageInfo);
                publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                publishingPage.ListItem.File.Publish(string.Empty);
                clientContext.ExecuteQuery();
            }
            SetSupportCaseContent(clientContext, "SupportCasesPage", url, queryurl);
        }
Esempio n. 4
0
        public void AddPublishingPage()
        {
            string pageName = "CustomPage3.aspx";
            Web    webSite  = context.Web;

            context.Load(webSite);
            PublishingWeb web = PublishingWeb.GetPublishingWeb(context, webSite);

            context.Load(web);

            if (web != null)
            {
                List pages = context.Site.RootWeb.Lists.GetByTitle("Pages");
                ListItemCollection defaultPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());
                context.Load(defaultPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageName));
                context.ExecuteQuery();
                if (defaultPages != null && defaultPages.Count > 0)
                {
                }
                else
                {
                    List publishingLayouts      = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");
                    ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
                    context.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "PageLayoutTemplate"));
                    context.ExecuteQuery();
                    ListItem layout = allItems.Where(x => x.DisplayName == "PageLayoutTemplate").FirstOrDefault();
                    context.Load(layout);
                    PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                    publishingPageInfo.Name = pageName;
                    publishingPageInfo.PageLayoutListItem = layout;
                    PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo);
                    publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    publishingPage.ListItem.File.Publish(string.Empty);
                    publishingPage.ListItem.File.Approve(string.Empty);
                    context.Load(publishingPage);
                    context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);
                    context.ExecuteQuery();
                }
            }
        }
Esempio n. 5
0
        protected void btnScenario1_Click(object sender, EventArgs e)
        {
            var    spContext          = SharePointContextProvider.Current.GetSharePointContext(Context);
            string ContosoWebPageCTId = "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4002CA362904d604607B0F1E39BE59D76E0";

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Create content type for the page layouts
                if (!clientContext.Web.ContentTypeExistsByName("ContosoWebPage"))
                {
                    // Let's create a content type which is inherited from oob welcome page
                    clientContext.Web.CreateContentType("ContosoWebPage",
                                                        ContosoWebPageCTId,
                                                        "Contoso Web Content Types");
                }

                // Upload page layouts to the master page gallery
                clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksBelow.aspx")),
                                                   "Contoso Links Below", "Contoso Links Below", ContosoWebPageCTId);

                clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksRight.aspx")),
                                                   "Contoso Links Right", "Contoso Links Right", ContosoWebPageCTId);

                // Add content type to Pages library
                clientContext.Web.AddContentTypeToListById("Pages", ContosoWebPageCTId);

                // Deploy addditional JS to site
                DeployJStoContosoFoldersInStyleLibrary(clientContext);

                // Create a new page based on the page layout
                List pages = clientContext.Web.Lists.GetByTitle("Pages");
                Microsoft.SharePoint.Client.ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(pages);
                clientContext.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "demo"));
                clientContext.ExecuteQuery();

                // Check if page already exists and delete old version if existed
                if (existingPages != null && existingPages.Count > 0)
                {
                    existingPages[0].DeleteObject();
                    clientContext.ExecuteQuery();
                }

                // Solve layout and create new page
                Microsoft.SharePoint.Client.ListItem pageLayout = clientContext.Web.GetPageLayoutListItemByName("ContosoLinksRight.aspx");
                PublishingWeb             pWeb = PublishingWeb.GetPublishingWeb(clientContext, clientContext.Web);
                PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                publishingPageInfo.Name = "demo.aspx";
                publishingPageInfo.PageLayoutListItem = pageLayout;
                PublishingPage publishingPage = pWeb.AddPublishingPage(publishingPageInfo);
                if (pages.ForceCheckout || pages.EnableVersioning)
                {
                    publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    publishingPage.ListItem.File.Publish(string.Empty);
                    if (pages.EnableModeration)
                    {
                        publishingPage.ListItem.File.Approve(string.Empty);
                    }
                }
                clientContext.ExecuteQuery();

                lblStatus1.Text = string.Format("New content type created, page layouts uploaded and new page created to the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString() + "/pages/demo.aspx");
            }
        }
Esempio n. 6
0
        protected void btnScenario1_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            string ContosoWebPageCTId = "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4002CA362904d604607B0F1E39BE59D76E0";

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Create content type for the page layouts
                if (!clientContext.Web.ContentTypeExistsByName("ContosoWebPage"))
                {
                    // Let's create a content type which is inherited from oob welcome page
                    clientContext.Web.CreateContentType("ContosoWebPage",
                                                        ContosoWebPageCTId,
                                                        "Contoso Web Content Types");
                }

                // Upload page layouts to the master page gallery
                clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksBelow.aspx")),
                                                    "Contoso Links Below", "Contoso Links Below", ContosoWebPageCTId);

                clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksRight.aspx")),
                                                    "Contoso Links Right", "Contoso Links Right", ContosoWebPageCTId);

                // Add content type to Pages library
                clientContext.Web.AddContentTypeToListById("Pages", ContosoWebPageCTId);

                // Deploy addditional JS to site
                DeployJStoContosoFoldersInStyleLibrary(clientContext);

                // Create a new page based on the page layout
                List pages = clientContext.Web.Lists.GetByTitle("Pages");
                Microsoft.SharePoint.Client.ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(pages);
                clientContext.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "demo"));
                clientContext.ExecuteQuery();

                // Check if page already exists and delete old version if existed
                if (existingPages != null && existingPages.Count > 0)
                {
                    existingPages[0].DeleteObject();
                    clientContext.ExecuteQuery();
                }

                // Solve layout and create new page
                Microsoft.SharePoint.Client.ListItem pageLayout = clientContext.Web.GetPageLayoutListItemByName("ContosoLinksRight.aspx");
                PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(clientContext, clientContext.Web);
                PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                publishingPageInfo.Name = "demo.aspx";
                publishingPageInfo.PageLayoutListItem = pageLayout;
                PublishingPage publishingPage = pWeb.AddPublishingPage(publishingPageInfo);
                if (pages.ForceCheckout || pages.EnableVersioning)
                {
                    publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    publishingPage.ListItem.File.Publish(string.Empty);
                    if (pages.EnableModeration)
                    {
                        publishingPage.ListItem.File.Approve(string.Empty);
                    }
                }
                clientContext.ExecuteQuery();

                lblStatus1.Text = string.Format("New content type created, page layouts uploaded and new page created to the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString() + "/pages/demo.aspx");

            }
        }
Esempio n. 7
0
        /// <summary>
        /// Adds the publishing page.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="pageTemplateName">Name of the page template/layout excluded the .aspx file extension.</param>
        /// <param name="title">The title of the target publishing page.</param>
        /// <param name="publish">Should the page be published or not?</param>
        /// <param name="folder">The target folder for the page, within the Pages library.</param>
        /// <param name="startDate">Start date for scheduled publishing.</param>
        /// <param name="endDate">End date for scheduled publishing.</param>
        /// <param name="schedule">Defines whether to define a schedule or not.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when key or pageName is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentException">Thrown when key or pageName is null</exception>
        public static void AddPublishingPage(this Web web, string pageName, string pageTemplateName, string title = null, bool publish = false, Folder folder = null, DateTime?startDate = null, DateTime?endDate = null, Boolean schedule = false)
        {
            if (string.IsNullOrEmpty(pageName))
            {
                throw (title == null)
                  ? new ArgumentNullException(nameof(pageName))
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, nameof(pageName));
            }
            if (string.IsNullOrEmpty(pageTemplateName))
            {
                throw (title == null)
                  ? new ArgumentNullException(nameof(pageTemplateName))
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, nameof(pageTemplateName));
            }
            if (string.IsNullOrEmpty(title))
            {
                title = pageName;
            }

            // Fix page name, if needed
            pageName = pageName.ReplaceInvalidUrlChars("-");

            var context = web.Context as ClientContext;
            var site    = context.Site;

            context.Load(site, s => s.ServerRelativeUrl);
            context.ExecuteQueryRetry();

            // Load reference Page Layout
            var pageFromPageLayout = context.Site.RootWeb.GetFileByServerRelativeUrl($"{UrlUtility.EnsureTrailingSlash(site.ServerRelativeUrl)}_catalogs/masterpage/{pageTemplateName}.aspx");
            var pageLayoutItem     = pageFromPageLayout.ListItemAllFields;

            context.Load(pageLayoutItem);
            context.ExecuteQueryRetry();

            // Create the publishing page
            var publishingWeb = PublishingWeb.GetPublishingWeb(context, web);

            context.Load(publishingWeb);

            // Configure the publishing page
            var pageInformation = new PublishingPageInformation
            {
                Name = !pageName.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ?
                       $"{pageName}.aspx" : pageName,
                PageLayoutListItem = pageLayoutItem
            };

            // Handle target folder, if any
            if (folder != null)
            {
                pageInformation.Folder = folder;
            }
            var page = publishingWeb.AddPublishingPage(pageInformation);

            // Get parent list of item, this way we can handle all languages
            var pagesLibrary = page.ListItem.ParentList;

            context.Load(pagesLibrary);
            context.ExecuteQueryRetry();
            var pageItem = page.ListItem;

            pageItem["Title"] = title;
            pageItem.Update();

            // Checkin the page file, if needed
            web.Context.Load(pageItem, p => p.File.CheckOutType);
            web.Context.ExecuteQueryRetry();
            if (pageItem.File.CheckOutType != CheckOutType.None)
            {
                pageItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
            }

            // Publish the page, if required
            if (publish)
            {
                pageItem.File.Publish(string.Empty);
                if (pagesLibrary.EnableModeration)
                {
                    pageItem.File.Approve(string.Empty);

                    // Setup scheduling, if required
                    if (schedule && startDate.HasValue)
                    {
                        page.StartDate = startDate.Value;
                        page.EndDate   = endDate ?? new DateTime(2050, 01, 01);
                        page.Schedule(string.Empty);
                    }
                }
            }
            context.ExecuteQueryRetry();
        }
Esempio n. 8
0
        private static void CreatePublishingPage2013(ClientContext ctx, Web web, XElement xPage)
        {
            Web webSite = web;

            ctx.Load(webSite);

            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(ctx, webSite);

            ctx.Load(pubWeb);

            string pageName       = xPage.Attribute("Name").Value;
            string layoutPageName = xPage.Attribute("LayoutPageName").Value;
            string pageLibrary    = xPage.Attribute("PageLibrary").Value;

            if (pubWeb != null)
            {
                // Get library to hold new page

                List targetLibrary = webSite.Lists.GetByTitle(pageLibrary);

                ListItemCollection existingPages = targetLibrary.GetItems(CamlQuery.CreateAllItemsQuery());

                ctx.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageName));
                ctx.ExecuteQuery();

                if (existingPages != null && existingPages.Count > 0)
                {
                    // Page already exists
                }
                else
                {
                    // Get publishing page layouts

                    List publishingLayouts = ctx.Web.Lists.GetByTitle("Master Page Gallery");

                    ListItemCollection layoutPages = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
                    ctx.Load(layoutPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == layoutPageName));
                    ctx.ExecuteQuery();

                    ListItem layoutPage = layoutPages.Where(x => x.DisplayName == layoutPageName).FirstOrDefault();
                    ctx.Load(layoutPage);

                    // Create a publishing page

                    PublishingPageInformation newPublishingPageInfo = new PublishingPageInformation();
                    newPublishingPageInfo.Name = pageName;
                    newPublishingPageInfo.PageLayoutListItem = layoutPage;

                    PublishingPage newPublishingPage = pubWeb.AddPublishingPage(newPublishingPageInfo);

                    newPublishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    newPublishingPage.ListItem.File.Publish(string.Empty);
                    newPublishingPage.ListItem.File.Approve(string.Empty);

                    ctx.Load(newPublishingPage);
                    ctx.Load(newPublishingPage.ListItem.File, obj => obj.ServerRelativeUrl);

                    ctx.ExecuteQuery();
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Adds the publishing page.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="pageTemplateName">Name of the page template/layout excluded the .aspx file extension.</param>
        /// <param name="title">The title of the target publishing page.</param>
        /// <param name="publish">Should the page be published or not?</param>
        /// <param name="folder">The target folder for the page, within the Pages library.</param>
        /// <param name="startDate">Start date for scheduled publishing.</param>
        /// <param name="endDate">End date for scheduled publishing.</param>
        /// <param name="schedule">Defines whether to define a schedule or not.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when key or pageName is a zero-length string or contains only white space</exception>
        /// <exception cref="System.ArgumentException">Thrown when key or pageName is null</exception>
        public static void AddPublishingPage(this Web web, string pageName, string pageTemplateName, string title = null, 
            bool publish = false, Folder folder = null,
            DateTime? startDate = null, DateTime? endDate = null, Boolean schedule = false)
        {
            if (string.IsNullOrEmpty(pageName))
            {
                throw (title == null)
                  ? new ArgumentNullException("pageName")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "pageName");
            }
            if (string.IsNullOrEmpty(pageTemplateName))
            {
                throw (title == null)
                  ? new ArgumentNullException("pageTemplateName")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "pageTemplateName");
            }
            if (string.IsNullOrEmpty(title))
            {
                title = pageName;
            }

            // Fix page name, if needed
            pageName = pageName.ReplaceInvalidUrlChars("-");

            ClientContext context = web.Context as ClientContext;
            Site site = context.Site;
            context.Load(site, s => s.ServerRelativeUrl);
            context.ExecuteQueryRetry();

            // Load reference Page Layout
            File pageFromPageLayout = context.Site.RootWeb.GetFileByServerRelativeUrl(String.Format("{0}_catalogs/masterpage/{1}.aspx",
                UrlUtility.EnsureTrailingSlash(site.ServerRelativeUrl),
                pageTemplateName));
            ListItem pageLayoutItem = pageFromPageLayout.ListItemAllFields;
            context.Load(pageLayoutItem);
            context.ExecuteQueryRetry();

            // Create the publishing page
            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(context, web);
            context.Load(publishingWeb);

            // Configure the publishing page
            var pageInformation = new PublishingPageInformation
            {
                Name = !pageName.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ?
                    string.Format("{0}.aspx", pageName) : pageName,
                PageLayoutListItem = pageLayoutItem,
            };

            // Handle target folder, if any
            if (folder != null)
            {
                pageInformation.Folder = folder;
            }
            PublishingPage page = publishingWeb.AddPublishingPage(pageInformation);

            // Get parent list of item, this way we can handle all languages
            List pagesLibrary = page.ListItem.ParentList;
            context.Load(pagesLibrary);
            context.ExecuteQueryRetry();
            ListItem pageItem = page.ListItem;
            pageItem["Title"] = title;
            pageItem.Update();

            // Checkin the page file, if needed
            web.Context.Load(pageItem, p => p.File.CheckOutType);
            web.Context.ExecuteQueryRetry();
            if (pageItem.File.CheckOutType != CheckOutType.None)
            {
                pageItem.File.CheckIn(String.Empty, CheckinType.MajorCheckIn);
            }

            // Publish the page, if required
            if (publish)
            {
                pageItem.File.Publish(String.Empty);
                if (pagesLibrary.EnableModeration)
                {
                    pageItem.File.Approve(String.Empty);

                    // Setup scheduling, if required
                    if (schedule && startDate.HasValue)
                    {
                        page.StartDate = startDate.Value;
                        page.EndDate = endDate.HasValue ? endDate.Value : new DateTime(2050, 01, 01);
                        page.Schedule(String.Empty);
                    }
                }
            }
            context.ExecuteQueryRetry();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter Site Address: ");
            string siteUrl      = Console.ReadLine();
            bool   siteOnline   = false;
            string siteUser     = "";
            string sitePassword = "";
            string siteDomain   = "";

            if (siteUrl.Contains(".sharepoint.com"))
            {
                Console.WriteLine("This site is SharePoint Online Right ? (Y/N): ");
                string OnlineAnswer = Console.ReadLine();

                if (OnlineAnswer.ToUpper() == "Y")
                {
                    siteOnline = true;
                }
            }

            if (siteOnline)
            {
                Console.WriteLine("Please Enter Site Login User Email Address: ");
                siteUser = Console.ReadLine();

                Console.WriteLine("Please Enter Site Login User Password: "******"Please Enter Site Login User Domain Name: ");
                siteDomain = Console.ReadLine();

                Console.WriteLine("Please Enter Site Login User Name: ");
                siteUser = Console.ReadLine();

                Console.WriteLine("Please Enter Site Login User Password: "******"Please Enter Master Page Gallery Name: ");
            string siteMasterPageGallery = Console.ReadLine();

            Console.WriteLine("Please Enter Create Publishing Page Content Type Display Name: ");
            string pageContentType = Console.ReadLine();

            Console.WriteLine("Please Enter Create Publishing Page Name: ");
            string pageName = Console.ReadLine();

            Console.WriteLine("Do You Have Add Page Field Value (Y/N): ");
            string addPageValuAnswer  = Console.ReadLine();
            bool   addPageValue       = false;
            string addPageValueString = "";

            if (addPageValuAnswer.ToUpper() == "Y")
            {
                addPageValue = true;
                Console.WriteLine("Please Enter Page Field Data ( ':' Separator Using For Field Name And Value, ';' Separator Using For Each Field Data ): ");
                Console.WriteLine("For Example ---> Title:TestPage;Comments:TestPage Comments ");
                Console.WriteLine("");
                addPageValueString = Console.ReadLine();
            }

            Console.WriteLine("Please Wait Start Create Process....");

            ClientContext  clientContext  = null;
            PublishingPage publishingPage = null;
            Web            web            = null;

            try
            {
                clientContext = new ClientContext(siteUrl);

                if (siteOnline)
                {
                    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;

                    string password = sitePassword;
                    System.Security.SecureString passwordChar = new System.Security.SecureString();
                    foreach (char ch in password)
                    {
                        passwordChar.AppendChar(ch);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(siteUser, passwordChar);
                }
                else
                {
                    clientContext.Credentials = new NetworkCredential(siteUser, sitePassword, siteDomain);
                }

                web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("This Site Connect Error Please Check Your Information And Try Again");
                Console.WriteLine("Error Message: " + ex.Message);
                Console.ReadLine();
                Environment.Exit(0);
            }

            try
            {
                Console.WriteLine("This Site Connection Success....");
                Console.WriteLine("Please Wait Create Publishing Page.....");

                List publishingLayouts      = clientContext.Site.RootWeb.Lists.GetByTitle(siteMasterPageGallery);
                ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageContentType));
                clientContext.ExecuteQuery();
                ListItem layout = allItems.Where(x => x.DisplayName == pageContentType).FirstOrDefault();
                clientContext.Load(layout);

                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web);
                clientContext.Load(publishingWeb);

                PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                publishingPageInfo.Name = pageName.Contains(".aspx") ? pageName : pageName + ".aspx";
                publishingPageInfo.PageLayoutListItem = layout;

                publishingPage = publishingWeb.AddPublishingPage(publishingPageInfo);

                clientContext.Load(publishingPage);
                clientContext.Load(publishingPage.ListItem.File);
                clientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("This During Publishing Page Error Please Check Your Information And Try Again");
                Console.WriteLine("Error Message: " + ex.Message);
                Console.ReadLine();
                Environment.Exit(0);
            }

            Console.WriteLine("this Publishing Page Create Success....");

            if (addPageValue)
            {
                try
                {
                    Console.WriteLine("Please Wait Add Field Data Publishing Page....");

                    ListItem listItem = publishingPage.ListItem;

                    string[] dataArray = addPageValueString.Split(';');

                    foreach (string data in dataArray)
                    {
                        listItem[data.Split(':')[0]] = data.Split(':')[1];
                    }

                    listItem.Update();

                    publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    publishingPage.ListItem.File.Publish(string.Empty);

                    clientContext.Load(publishingPage);

                    clientContext.ExecuteQuery();

                    Console.WriteLine("Tihs Publishing Page Add Field Data Success....");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("This During Publishing Page Add Field Data Error Please Check Your Information And Try Again");
                    Console.WriteLine("Error Message: " + ex.Message);
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }

            Console.WriteLine("All Process Complete Success...");
            Console.ReadLine();
            Environment.Exit(0);
        }
Esempio n. 11
0
        public static void CreatePublishingPage(ClientContext clientContext, string pageName, string pagelayoutname, string url, string queryurl)
        {
            var publishingPageName = pageName + ".aspx";

            Web web = clientContext.Web;
            clientContext.Load(web);

            List pages = web.Lists.GetByTitle("Pages");
            clientContext.Load(pages.RootFolder, f => f.ServerRelativeUrl);
            clientContext.ExecuteQuery();

            Microsoft.SharePoint.Client.File file =
                web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx");
            clientContext.Load(file, f => f.Exists);
            clientContext.ExecuteQuery();
            if(file.Exists)
            {
                file.DeleteObject();
                clientContext.ExecuteQuery();
            }
            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web);
            clientContext.Load(publishingWeb);

            if (publishingWeb != null)
            {
                List publishingLayouts = clientContext.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");

                ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pagelayoutname));
                clientContext.ExecuteQuery();

                ListItem layout = allItems.Where(x => x.DisplayName == pagelayoutname).FirstOrDefault();
                clientContext.Load(layout);

                PublishingPageInformation publishingpageInfo = new PublishingPageInformation()
                {
                    Name = publishingPageName,
                    PageLayoutListItem = layout,
                };

                PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingpageInfo);
                publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                publishingPage.ListItem.File.Publish(string.Empty);
                clientContext.ExecuteQuery();
            }
            SetSupportCaseContent(clientContext, "SupportCasesPage", url, queryurl);
        }
        private void ProvisionFromStorage(ClientContext ctx, Web web, AppManifestBase manifest)
        {
            List wikiPagesLibrary       = null;
            List publishingPagesLibrary = null;

            if (Creators != null && Creators.Count > 0)
            {
                foreach (var fileCreator in Creators.Values)
                {
                    try
                    {
                        if (!FileExists(fileCreator, ctx, web, fileCreator.ForceOverwrite))
                        {
                            if ((fileCreator.ContentType != null && fileCreator.ContentType == "Wiki Page") || (fileCreator.ContentTypeId != null && fileCreator.ContentTypeId.StartsWith(WikiPageContentTypeId)))
                            {
                                OnNotify(ProvisioningNotificationLevels.Verbose, "Creating wiki page " + fileCreator.Url);
                                if (wikiPagesLibrary == null)
                                {
                                    wikiPagesLibrary = web.Lists.GetByTitle(fileCreator.List);
                                    ctx.Load(wikiPagesLibrary.RootFolder, f => f.ServerRelativeUrl);
                                    ctx.ExecuteQueryRetry();
                                }
                                var fileUrl = fileCreator.Url;
                                if (web.ServerRelativeUrl != "/")
                                {
                                    fileUrl = web.ServerRelativeUrl + fileUrl;
                                }

                                fileCreator.File = wikiPagesLibrary.RootFolder.Files.AddTemplateFile(fileUrl,
                                                                                                     TemplateFileType.WikiPage);
                                ctx.Load(fileCreator.File, f => f.ServerRelativeUrl);
                                ctx.ExecuteQueryRetry();
                                fileCreator.AddWikiOrPublishingPageWebParts(ctx, web, WikiPageContentFieldName);
                                fileCreator.Created = true;
                            }
                            else if (fileCreator.ContentTypeId != null && fileCreator.ContentTypeId.StartsWith(PublishingPageContentTypeId))
                            {
                                OnNotify(ProvisioningNotificationLevels.Verbose, "Creating publishing page " + fileCreator.Url);
                                if (publishingPagesLibrary == null)
                                {
                                    publishingPagesLibrary = web.Lists.GetByTitle(fileCreator.List);
                                    ctx.Load(publishingPagesLibrary.RootFolder, f => f.ServerRelativeUrl);
                                    ctx.ExecuteQueryRetry();
                                }
                                var fileUrl = fileCreator.Url;
                                if (web.ServerRelativeUrl != "/")
                                {
                                    fileUrl = web.ServerRelativeUrl + fileUrl;
                                }

                                var pageName   = fileCreator.ListItemFieldValues.Find(p => p.FieldName == "FileLeafRef")?.Value;
                                var pageLayout = fileCreator.ListItemFieldValues.Find(p => p.FieldName == "PublishingPageLayout")?.Value;


                                if (string.IsNullOrEmpty(pageName) || string.IsNullOrEmpty(pageLayout) || !pageLayout.Contains(", "))
                                {
                                    OnNotify(ProvisioningNotificationLevels.Verbose,
                                             $"Invalid publishing page data for {fileCreator.Url}! Skipping");
                                }
                                else
                                {
                                    try
                                    {
                                        pageLayout = pageLayout.Split(',')[0].Replace("{@WebUrl}", web.ServerRelativeUrl);
                                        var pageLayoutListItem =
                                            web.GetFileByServerRelativeUrl(pageLayout).ListItemAllFields;
                                        ctx.Load(pageLayoutListItem);
                                        PublishingPageInformation publishingPageInfo = new PublishingPageInformation()
                                        {
                                            Name               = pageName,
                                            Folder             = publishingPagesLibrary.RootFolder,
                                            PageLayoutListItem = pageLayoutListItem
                                        };
                                        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(ctx, web);
                                        fileCreator.File = publishingWeb.AddPublishingPage(publishingPageInfo).ListItem.File;
                                        ctx.Load(fileCreator.File, f => f.ServerRelativeUrl);
                                        ctx.ExecuteQueryRetry();
                                        fileCreator.AddWikiOrPublishingPageWebParts(ctx, web, PublishingPageContentFieldName);
                                        fileCreator.Created = true;
                                    }
                                    catch
                                    {
                                        OnNotify(ProvisioningNotificationLevels.Verbose,
                                                 $"Invalid publishing page data for {fileCreator.Url}! Unable to find page layout at {pageLayout}. If the page layout is in the manifest, ensure that it appears before the pages that depend on it. Skipping");
                                    }
                                }
                            }
                            else if ((fileCreator.ContentType != null && fileCreator.ContentType == "Web Part Page") || (fileCreator.ContentTypeId != null && fileCreator.ContentTypeId.StartsWith(BasicPageContentTypeId)))
                            {
                                OnNotify(ProvisioningNotificationLevels.Verbose,
                                         "Creating web part page " + fileCreator.Url);
                                var file = GetFileFromStorage(manifest, fileCreator);

                                file             = fileCreator.PrepareFile(file, ctx, web, true);
                                fileCreator.File = UploadFile(ctx, web, fileCreator.List, file, fileCreator.Url);
                                ctx.Load(fileCreator.File, f => f.ServerRelativeUrl);
                                ctx.ExecuteQueryRetry();
                                fileCreator.AddWebPartPageWebParts(ctx, web);
                                fileCreator.Created = true;
                            }
                            else
                            {
                                OnNotify(ProvisioningNotificationLevels.Verbose, "Creating file " + fileCreator.Url);
                                var file = GetFileFromStorage(manifest, fileCreator);
                                if (!fileCreator.IsBinary)
                                {
                                    file = fileCreator.PrepareFile(file, ctx, web, fileCreator.ContentType != null && fileCreator.ContentType == "Workflow");
                                }
                                fileCreator.File = UploadFile(ctx, web, fileCreator.List, file, fileCreator.Url);
                                ctx.Load(fileCreator.File, f => f.ServerRelativeUrl);
                                fileCreator.Created = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        OnNotify(ProvisioningNotificationLevels.Normal,
                                 "Error creating file " + fileCreator.RelativeFilePath + " | " + ex);
                        Trace.TraceError("Error creating file " + fileCreator.RelativeFilePath + " | " + ex);
                        throw;
                    }
                }

                if (!ctx.Web.IsPropertyAvailable("AppInstanceId"))
                {
                    ctx.Load(ctx.Web, w => w.AppInstanceId);
                    ctx.ExecuteQueryRetry();
                }
                if (ctx.Web.AppInstanceId == default(Guid))
                {
                    ApplySecurity(ctx);
                }

                foreach (var key in Creators.Keys)
                {
                    OnNotify(ProvisioningNotificationLevels.Verbose, "Setting properties for " + Creators[key].Url);
                    Creators[key].SetProperties(ctx, web);
                }
                ctx.ExecuteQueryRetry();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Adds a wiki page by Url
        /// </summary>
        /// <param name="web">The web to process</param>
        /// <param name="serverRelativePageUrl">Server relative URL of the wiki page to process</param>
        /// <param name="pageLayoutUrl">Server relative URL of the publishing page layout</param>
        /// <param name="html">HTML to add to wiki page</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 is null</exception>
        public static void AddPublishingPageByUrl(this Web web, string serverRelativePageUrl, string pageLayoutUrl, string title, string html = null)
        {
            if (string.IsNullOrEmpty(serverRelativePageUrl))
            {
                throw (serverRelativePageUrl == null)
                  ? new ArgumentNullException("serverRelativePageUrl")
                  : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, "serverRelativePageUrl");
            }

            var context = web.Context as ClientContext;

            var list = context.Site.GetCatalog((int)ListTemplateType.MasterPageCatalog);
            var qry = new CamlQuery();
            qry.ViewXml = string.Format("<View><Query><Where><Contains><FieldRef Name=\"FileRef\"/><Value Type=\"Url\">{0}</Value></Contains></Where></Query></View>", pageLayoutUrl.Substring(pageLayoutUrl.IndexOf("_catalogs")));
            var layouts = list.GetItems(qry);
            context.Load(layouts);
            context.ExecuteQueryRetry();
            var layoutEnum = layouts.GetEnumerator();
            ListItem layoutItem = null;
            while (layoutEnum.MoveNext()) {
                layoutItem = layoutEnum.Current;
                break;
            }

            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(context, web);
            context.Load(publishingWeb);

            int idx = serverRelativePageUrl.LastIndexOf('/');
            string folderUrl = serverRelativePageUrl.Substring(0, idx);
            string pageName = serverRelativePageUrl.Substring(idx + 1);

            Folder folder = web.GetFolderByServerRelativeUrl(folderUrl);

            PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
            publishingPageInfo.Folder = folder;
            publishingPageInfo.Name = pageName;
            publishingPageInfo.PageLayoutListItem = layoutItem;

            PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingPageInfo);

            publishingPage.ListItem["Title"] = title;
            publishingPage.ListItem.Update();
            context.ExecuteQueryRetry();
            if (!string.IsNullOrEmpty(html))
            {
                web.AddHtmlToWikiPage(serverRelativePageUrl, html);
            }

            publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
            publishingPage.ListItem.File.Publish(string.Empty);

            context.ExecuteQueryRetry();
        }