/// <summary>
 /// Update, check-in, publish and approve a page with a check-in message.
 /// </summary>
 /// <param name="page">The page.</param>
 /// <param name="message">The message.</param>
 public void UpdateCheckInPublishApprove(PublishingPage page, string message)
 {
     page.Update();
     page.CheckIn(message);
     page.ListItem.File.Publish(message);
     page.ListItem.File.Approve(message);
 }
示例#2
0
        private void CreatePartnerTabbedPage(SPWeb web, SPList sitesList)
        {
            // Create a new page for listing Partner Site Collections
            if (PublishingWeb.IsPublishingWeb(web))
            {
                PublishingWeb            pubWeb           = PublishingWeb.GetPublishingWeb(web);
                PublishingPageCollection availablePages   = pubWeb.GetPublishingPages();
                PublishingPage           partnerSitesPage = availablePages[Constants.PartnerSitesPageUrl];

                if (partnerSitesPage == null)
                {
                    // The Partner Sites page should be based on the same layout as the top sites page.
                    PublishingPage topSitesPage = availablePages[Constants.TopSitesPageUrl];
                    partnerSitesPage = availablePages.Add(Constants.PartnerSitesFileName, topSitesPage.Layout);
                    partnerSitesPage.ListItem[titleFieldId] = Constants.PartnerSitesTile;
                    // We can not use the Field Id of the the Description field, because it is not static.
                    partnerSitesPage.ListItem[Constants.DescriptionField] = Resources.PartnerSitePageDescription;
                    partnerSitesPage.Update();
                    SPFile partnerSitesPageFile = web.GetFile(partnerSitesPage.Url);

                    AddListViewWebPartToPage(sitesList, partnerSitesPage, partnerSitesPageFile);

                    // Add a tab to the Tabs control.
                    SPListItem newTab = web.Lists[Constants.TabsList].Items.Add();
                    newTab[Constants.TabNameField] = Constants.PartnersTabName;
                    newTab[Constants.PageField]    = Constants.PartnerSitesFileName;
                    newTab[Constants.TooltipField] = Constants.PartnerSitesTooltip;
                    newTab.Update();
                }
            }
        }
        // method for creating publising page
        private string CreatePublishingPage(string pageName, string pageLayoutName, bool isLandingPage)
        {
            string createdPageURL = string.Empty;

            // elevated privilages as not all user will have permission to create a new page
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // get current web
                SPWeb oWeb                  = SPContext.Current.Web;
                string fullPageUrl          = string.Empty;
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(oWeb);
                /* Get the publishing web page collection list. */
                PublishingPageCollection publishingPageCollection = publishingWeb.GetPublishingPages();
                //GetPageLayoutName(application);
                if (!string.IsNullOrEmpty(pageLayoutName))
                {
                    /* Search for the page layout for creating the new page */
                    List <PageLayout> layouts = new List <PageLayout>(publishingWeb.GetAvailablePageLayouts());
                    PageLayout pageLayout     = layouts.Find(
                        delegate(PageLayout l)
                    {
                        return(l.Name.Equals(pageLayoutName, StringComparison.CurrentCultureIgnoreCase));
                    });
                    /*page layout exists*/
                    if (pageLayout != null)
                    {
                        PublishingPage newPage = null;
                        newPage       = publishingPageCollection.Add(pageName + ".aspx", pageLayout);
                        newPage.Title = pageName;
                        newPage.Update();

                        SPList li = newPage.ListItem.ParentList;

                        if (li.EnableModeration == false)
                        {
                            li.EnableModeration = true;
                            li.Update();
                        }
                        newPage.CheckIn("page checked in");
                        newPage.ListItem.File.Publish("page published");
                        newPage.ListItem.File.Approve("page approved");
                        /* Set newly created page as a welcome page */
                        if (isLandingPage == true)
                        {
                            fullPageUrl               = oWeb.Url + "/Pages/" + pageName + ".aspx";
                            SPFile fileNew            = publishingWeb.Web.GetFile(fullPageUrl);
                            publishingWeb.DefaultPage = fileNew;
                        }
                        publishingWeb.Update();

                        createdPageURL = newPage.Uri.AbsoluteUri.ToString();
                    }
                }
            });

            // return new page url
            return(createdPageURL);
        }
示例#4
0
        /// <summary>
        /// Creates a publishing page under the specified site with the content type ID and specified title.
        /// Filename of the created page is automatically chosen to avoid collision to existing pages.
        /// </summary>
        /// <param name="currentWeb">Publishing web.</param>
        /// <param name="contentTypeId">Content type ID of the new page.</param>
        /// <param name="title">Title of the new page.</param>
        /// <exception cref="InvalidOperationException">Throws if there is no page layouts associated with the specified content type ID.</exception>
        /// <returns>A publishing page object.</returns>
        public static PublishingPage CreatePublishingPage(this PublishingWeb currentWeb, SPContentTypeId contentTypeId, string title)
        {
            CommonHelper.ConfirmNotNull(currentWeb, "currentWeb");
            CommonHelper.ConfirmNotNull(title, "title");

            PageLayout pageLayout = null;

            currentWeb.Web.Site.WithElevatedPrivileges(elevatedSite => {
                PublishingSite publishingSite = new PublishingSite(elevatedSite);

                IEnumerable <PageLayout> pageLayouts = publishingSite.GetPageLayouts(true).Where(p => p.AssociatedContentType != null);
                pageLayout = pageLayouts.FirstOrDefault(p => p.AssociatedContentType.Id == contentTypeId);
                if (pageLayout == null)
                {
                    pageLayout = pageLayouts.FirstOrDefault(p => p.AssociatedContentType.Id.IsChildOf(contentTypeId));
                }
                //pageLayout = publishingWeb.GetAvailablePageLayouts().FirstOrDefault(p => p.AssociatedContentType.Id == contentTypeId);
                //pageLayout = publishingWeb.GetAvailablePageLayouts(contentTypeId).FirstOrDefault();
            });
            if (pageLayout == null)
            {
                throw new InvalidOperationException(String.Format("Could not find available page layout for content type {0} at {1}", contentTypeId, currentWeb.Url));
            }

            MethodInfo getUniquePageName =
                typeof(PublishingPage).GetMethod("GetUniquePageName", true, typeof(string), typeof(bool), typeof(PublishingWeb), typeof(bool)) ??
                typeof(PublishingPage).GetMethod("GetUniquePageName", true, typeof(string), typeof(bool), typeof(PublishingWeb));

            if (getUniquePageName == null)
            {
                throw new MissingMethodException("PublishingPage", "GetUniquePageName");
            }
            object[] param = getUniquePageName.GetParameters().Length == 4 ?
                             new object[] { title, true, currentWeb, true } :
            new object[] { title, true, currentWeb };
            string         uniquePageName = getUniquePageName.Invoke <string>(null, param);
            PublishingPage publishingPage = currentWeb.AddPublishingPage(uniquePageName, pageLayout);

            publishingPage.Title = title;
            publishingPage.Update();
            return(publishingPage);
        }
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;

            if (web != null)
            {
                if (PublishingWeb.IsPublishingWeb(web))
                {
                    PublishingWeb  pubWeb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPage page   = pubWeb.GetPublishingPages()[PartnerLandingPageUrl];

                    if (page == null)
                    {
                        SPContentTypeId contentTypeId     = new SPContentTypeId(welcomePageLayoutContentTypeId);
                        PageLayout[]    layouts           = pubWeb.GetAvailablePageLayouts(contentTypeId);
                        PageLayout      welcomePageLayout = layouts[0];

                        page = pubWeb.GetPublishingPages().Add(PartnerLandingPageFileName, welcomePageLayout);
                    }
                    else
                    {
                        page.CheckOut();
                    }

                    page.ListItem[titleFieldId]                  = PartnerLandingPageTile;
                    page.ListItem[DescriptionField]              = Resources.PageDescription;
                    page.ListItem[pageContentFieldId]            = Resources.PageContent;
                    page.ListItem[partnerSpecificContentFieldId] = Resources.PartnerSpecificContent;
                    page.Update();

                    SPFile welcomeFile = web.GetFile(page.Url);
                    pubWeb.DefaultPage = welcomeFile;
                    pubWeb.Update();

                    page.CheckIn(Resources.CheckInValue);
                }
            }
        }
示例#6
0
        private void MigrateOnePage(SPSite site, SPWeb web, SPList list, SPListItem item, String username, String password)
        {
            string remotePageURL      = item.WBxGetColumnAsString(REMOTE_PAGE_URL);
            string newLogicalLocation = item.WBxGetColumnAsString(NEW_LOGICAL_LOCATION);
            string siteOrPage         = item.WBxGetColumnAsString(SITE_OR_PAGE);
            string localPageURL       = item.WBxGetColumnAsString(LOCAL_PAGE_URL);
            string resultMessage      = "";

            if (newLogicalLocation == "")
            {
                MigrationError(item, "There was no new logical location set!");
                return;
            }

            WBLogging.Migration.HighLevel("Starting MigrateOnePage() for newLogicalLocation : " + newLogicalLocation);

            if (siteOrPage == "")
            {
                MigrationError(item, "The 'Site or Page' value wasn't set!");
                return;
            }

            if (localPageURL == "")
            {
                localPageURL = MakeLocalPageURL(newLogicalLocation, siteOrPage);
                item.WBxSetColumnAsString(LOCAL_PAGE_URL, localPageURL);
            }

            string remotePageURLToUse = remotePageURL.Replace("/alfresco/web/izzi/", "/alfresco/service/mizzi/");

            string localSPWebRelativeURL = newLogicalLocation;

            if (siteOrPage == PAGE)
            {
                localSPWebRelativeURL = WBUtils.GetParentPath(newLogicalLocation, false);
            }

            if (remotePageURL != "")
            {
                WBLogging.Migration.Verbose("Migrating remote -> local: " + remotePageURL + " -> " + localPageURL);
            }
            else
            {
                WBLogging.Migration.Verbose("Creating new local unmapped site: " + localPageURL);
            }

            SPWeb localWeb = null;

            try
            {
                string pageTitle    = item.WBxGetColumnAsString("Title");
                string pageTemplate = "";

                if (remotePageURL != "")
                {
                    pageTitle     = WBUtils.GetURLContents(remotePageURLToUse + "?JUST_PAGE_TITLE=true", username, password);
                    item["Title"] = pageTitle;

                    pageTemplate        = WBUtils.GetURLContents(remotePageURLToUse + "?JUST_PAGE_TEMPLATE=true", username, password);
                    item[PAGE_TEMPLATE] = pageTemplate;
                }


                if (remotePageURL != "" && pageTemplate != "izziThreeColumn.ftl")
                {
                    resultMessage = "Not migrated yet (due to unhandled template)";
                }
                else
                {
                    bool newSiteCreated = false;

                    localWeb = site.OpenWeb(localSPWebRelativeURL);

                    if (!localWeb.Exists)
                    {
                        // OK let's try to get the parent web:
                        string parentURL = WBUtils.GetParentPath(localSPWebRelativeURL, false);
                        string childName = WBUtils.GetLastNameInPath(localSPWebRelativeURL);

                        WBLogging.Migration.Verbose("Trying to find parent URL: " + parentURL);

                        using (SPWeb parentWeb = site.OpenWeb(parentURL))
                        {
                            if (parentWeb.Exists)
                            {
                                if (pageTitle == "")
                                {
                                    pageTitle     = childName.WBxToUpperFirstLetter();
                                    item["Title"] = pageTitle;
                                }
                                localWeb       = parentWeb.Webs.Add(childName, pageTitle, pageTitle, 1033, "CMSPUBLISHING#0", true, false);
                                newSiteCreated = true;
                            }
                            else
                            {
                                WBLogging.Migration.Verbose("Couldn't find parente web site - Don't know how to handle this situation.");
                                resultMessage = "Couldn't find the parent web site";
                            }
                        }
                    }

                    if (localWeb.Exists)
                    {
                        if (localWeb.HasUniqueRoleAssignments)
                        {
                            localWeb.ResetRoleInheritance();
                            localWeb.Update();
                        }

                        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(localWeb);

                        PageLayout layout = WBUtils.GetPageLayout(publishingWeb, "LBI Standard page layout");

                        if (layout == null)
                        {
                            MigrationError(item, "Didn't find the page layout!!");
                            return;
                        }

                        SPFile         pageFile = null;
                        PublishingPage page     = null;

                        // If this location is for a site then we get the default page:
                        if (siteOrPage == SITE)
                        {
                            pageFile = publishingWeb.DefaultPage;
                            page     = PublishingPage.GetPublishingPage(pageFile.Item);
                        }
                        else
                        {
                            // Otherwise we have to get or create a named page:
                            string pageName = WBUtils.GetLastNameInPath(newLogicalLocation) + ".aspx";

                            SPListItem pageItem = WBUtils.FindItemByColumn(site, publishingWeb.PagesList, WBColumn.Name, pageName);
                            if (pageItem != null)
                            {
                                page = PublishingPage.GetPublishingPage(pageItem);
                            }
                            else
                            {
                                // We couldn't find the page so we'll add it as a new page:
                                page = publishingWeb.AddPublishingPage(pageName, layout);
                            }

                            pageFile = page.ListItem.File;

                            string urlFromItem = "http://sp.izzi" + page.ListItem.File.ServerRelativeUrl;
                            if (localPageURL != urlFromItem)
                            {
                                MigrationError(item, "The generated names don't match: localPageURL | urlFromItem : " + localPageURL + " | " + urlFromItem);
                                return;
                            }
                        }

                        // So we'll update the content if we're migrating an izzi page or it's the first time
                        // creation of a new local page:
                        if (remotePageURL != "" || newSiteCreated)
                        {
                            string pageText = "This page is not being migrated so needs to be edited locally.";
                            if (remotePageURL != "")
                            {
                                pageText = WBUtils.GetURLContents(remotePageURLToUse + "?JUST_PAGE_TEXT=true", username, password);
                                pageText = ProcessPageText(site, list, pageText);
                            }

                            if (pageFile.CheckOutType == SPFile.SPCheckOutType.None)
                            {
                                WBLogging.Migration.Verbose("Checking out the pageFile");
                                pageFile.CheckOut();
                            }
                            else
                            {
                                WBLogging.Migration.Verbose("No need to check out the pageFile");
                            }

                            if (newSiteCreated)
                            {
                                page.Layout = layout;
                                page.Update();
                            }

                            pageFile.Item["Page Content"] = pageText;
                            pageFile.Item["Title"]        = pageTitle;


                            pageFile.Item.Update();
                            pageFile.Update();


                            pageFile.CheckIn("Checked in programmatically");
                            pageFile.Publish("Published programmatically");

                            WBLogging.Migration.Verbose("Publisehd migrated page: " + localPageURL);
                        }
                    }
                    else
                    {
                        WBLogging.Migration.Unexpected("Wasn't able to find or create the local web: " + localSPWebRelativeURL);
                        resultMessage += " Wasn't able to find or create the local web: " + localSPWebRelativeURL;
                    }
                }
            }
            catch (Exception error)
            {
                WBLogging.Migration.Unexpected("There was an error: " + error.Message + " Tried with remote | local : " + remotePageURL + " | " + localPageURL);
                resultMessage = "There was an error: " + error.Message + " Tried with remote | local : " + remotePageURL + " | " + localPageURL;
            }
            finally
            {
                if (localWeb != null)
                {
                    localWeb.Dispose();
                }
            }

            if (resultMessage == "")
            {
                resultMessage        = "Processed OK";
                item[LAST_MIGRATION] = DateTime.Now;
            }


            WBLogging.Migration.Verbose("Result message : " + resultMessage);

            item.WBxSetColumnAsString(RESULT_MESSAGE, resultMessage);
            item.Update();

            WBLogging.Migration.HighLevel("Finished MigrateOnePage() for newLogicalLocation : " + newLogicalLocation);
        }
示例#7
0
        public static PublishingPage CreatePage(SPWeb web, string pageName, string title, string layoutName, Dictionary <string, string> fieldDataCollection, bool test)
        {
            if (!PublishingWeb.IsPublishingWeb(web))
            {
                throw new ArgumentException("The specified web is not a publishing web.");
            }

            PublishingWeb pubweb           = PublishingWeb.GetPublishingWeb(web);
            PageLayout    layout           = null;
            string        availableLayouts = string.Empty;

            foreach (PageLayout lo in pubweb.GetAvailablePageLayouts())
            {
                availableLayouts += "\t" + lo.Name + "\r\n";
                if (lo.Name.ToLowerInvariant() == layoutName.ToLowerInvariant())
                {
                    layout = lo;
                    break;
                }
            }
            if (layout == null)
            {
                if (PublishingSite.IsPublishingSite(web.Site))
                {
                    Logger.WriteWarning("The specified page layout could not be found among the list of available page layouts for the web. Available layouts are:\r\n" + availableLayouts);
                    availableLayouts = string.Empty;
                    foreach (PageLayout lo in (new PublishingSite(web.Site).PageLayouts))
                    {
                        availableLayouts += "\t" + lo.Name + "\r\n";
                        if (lo.Name.ToLowerInvariant() == layoutName.ToLowerInvariant())
                        {
                            layout = lo;
                            break;
                        }
                    }
                }
                if (layout == null)
                {
                    throw new ArgumentException("The layout specified could not be found. Available layouts are:\r\n" + availableLayouts);
                }
            }

            if (!pageName.ToLowerInvariant().EndsWith(".aspx"))
            {
                pageName += ".aspx";
            }

            PublishingPage page = null;
            SPListItem     item = null;

            if (test)
            {
                Logger.Write("Page to be created at {0}", pubweb.Url);
            }
            else
            {
                page       = pubweb.GetPublishingPages().Add(pageName, layout);
                page.Title = title;
                item       = page.ListItem;
            }

            foreach (string fieldName in fieldDataCollection.Keys)
            {
                string fieldData = fieldDataCollection[fieldName];

                try
                {
                    SPField field = item.Fields.GetFieldByInternalName(fieldName);

                    if (field.ReadOnlyField)
                    {
                        Logger.Write("Field '{0}' is read only and will not be updated.", field.InternalName);
                        continue;
                    }

                    if (field.Type == SPFieldType.Computed)
                    {
                        Logger.Write("Field '{0}' is a computed column and will not be updated.", field.InternalName);
                        continue;
                    }

                    if (!test)
                    {
                        if (field.Type == SPFieldType.URL)
                        {
                            item[field.Id] = new SPFieldUrlValue(fieldData);
                        }
                        else if (field.Type == SPFieldType.User)
                        {
                            Common.Pages.CreatePublishingPage.SetUserField(web, item, field, fieldData);
                        }
                        else
                        {
                            item[field.Id] = fieldData;
                        }
                    }
                    else
                    {
                        Logger.Write("Field '{0}' would be set to '{1}'.", field.InternalName, fieldData);
                    }
                }
                catch (ArgumentException ex)
                {
                    Logger.WriteException(new ErrorRecord(new Exception(string.Format("Could not set field {0} for item {1}.", fieldName, item.ID), ex), null, ErrorCategory.InvalidArgument, item));
                }
            }
            if (page != null)
            {
                page.Update();
            }
            return(page);
        }
        protected new void CreateButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation.Begin(delegate(SPLongOperation longOperation)
                {
                    SPWeb web = SPContext.Current.Web;
                    PublishingWeb currentPublishingWeb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPage publishingPage      = null;
                    SPFolder sPFolder = null;
                    if (!string.IsNullOrEmpty(folderUrl))
                    {
                        sPFolder = currentPublishingWeb.Web.GetFolder(folderUrl);
                        if (!sPFolder.Exists)
                        {
                            string url = Helper.ConcatUrls(folderUrl, nameInput.Text);
                            SPUtility.CreateParentFoldersForFile(currentPublishingWeb.PagesList, url, false);
                            sPFolder = currentPublishingWeb.Web.GetFolder(folderUrl);
                        }
                    }
                    PageLayout pageLayout = null;
                    string text           = base.Request.QueryString.Get("PLUrl");
                    if (string.IsNullOrEmpty(text))
                    {
                        pageLayout = currentPublishingWeb.DefaultPageLayout;
                    }
                    else
                    {
                        try
                        {
                            pageLayout = new PageLayout(base.Web.GetListItem(text));
                        }
                        catch (Exception)
                        {
                            Logger.ToLog(new Exception(string.Format("Unable to create PageLayout from listitem of path : {0}", text)));
                            pageLayout = currentPublishingWeb.DefaultPageLayout;
                        }
                    }
                    publishingPage = SPHelper.CreatePublishingPage(currentPublishingWeb, nameInput.Text, pageLayout, sPFolder, false);
                    if (publishingPage != null && originalRequestedName != null)
                    {
                        publishingPage.Title = originalRequestedName;
                        publishingPage.ListItem["NewsType"] = ddlNewsType.SelectedValue;
                        publishingPage.Update();
                    }

                    string text2     = SPHttpUtility.UrlPathEncode(publishingPage.ListItem.File.ServerRelativeUrl, false);
                    string FinishUrl = SPHelper.DesignModeUrl(text2);

                    if (!string.IsNullOrEmpty(base.Request.QueryString.Get("IsDlg")))
                    {
                        if (base.Request.QueryString["shouldRedirectPage"] == "0")
                        {
                            string scriptLiteralToEncode = SPHelper.ConvertToAbsoluteUrl(FinishUrl, currentPublishingWeb.Web.Site, true);
                            longOperation.EndScript("window.frameElement.commitPopup('" + SPHttpUtility.EcmaScriptStringLiteralEncode(scriptLiteralToEncode) + "');");
                        }
                        else
                        {
                            longOperation.EndScript("window.frameElement.navigateParent('" + SPHttpUtility.EcmaScriptStringLiteralEncode(FinishUrl) + "');");
                        }
                    }
                    else
                    {
                        longOperation.End(FinishUrl);
                    }
                });
            }
        }