Exemple #1
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            PublishingWeb pWeb           = PublishingWeb.GetPublishingWeb(site.RootWeb);
            bool          pageNotCreated = !pWeb.GetPublishingPages().Cast <PublishingPage>().Any(p => p.Name == pageName);

            if (pageNotCreated)
            {
                //если такой страницы еще нет - создаем ее
                PublishingPage pPage = pWeb.GetPublishingPages().Add(pageName, null);

                pPage.CheckOut();

                using (Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager wpManager = site.RootWeb.GetLimitedWebPartManager(pPage.Url, PersonalizationScope.Shared))
                {
                    ResultScriptWebPart searchResults = GetImportedWebPart(site, wpName) as ResultScriptWebPart;
                    searchResults.Title      = wpTitle;
                    searchResults.ChromeType = PartChromeType.None;

                    wpManager.AddWebPart(searchResults, "Top", 0);
                }

                pPage.CheckIn(string.Empty);
            }
        }
Exemple #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);
        }
        private void AddResultsForSPWeb(SPSite site, SPWeb web)
        {
            WBLogging.RecordsTypes.Verbose("In AddResultsForSPWeb(): looking at SPWeb: " + web.Url);


            try
            {
                PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

                foreach (PublishingPage page in pubWeb.GetPublishingPages())
                {
                    WBLogging.RecordsTypes.Verbose("In AddResultsForSPWeb(): page = " + page.WBxToString());

                    if (page != null)
                    {
                        AddResultsForPublishingPage(page);

                        WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() just finished for AddResultsForPublishingPage(): page = " + page.Name);
                    }
                }
            }
            catch (Exception e)
            {
                WBLogging.RecordsTypes.Verbose("In FindWhereRecordIsBeingUsed.AddResultsForSPWeb(): This SPWeb is probably not a publishing site: " + web.Url);

                StringBuilder command = new StringBuilder();
                command.Append("<script type=\"text/javascript\">errorProcessingPage(\"").Append(web.Url).Append("\", \"An exception occured at an SPWeb level: ").Append(e.Message).Append("\");</script>\n");
                command.Append("<!-- Full exception stack using ToString(): ");
                command.Append(e.ToString()).Append("-->\n\n");

                command.Append("<!-- Full exception stack using FlattenException(): ");
                command.Append(FlattenException(e)).Append("-->\n\n");

                Response.Write(command.ToString());
                Response.Flush();
            }

            WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() about to look at sub webs for SPWeb: " + web.Url);

            foreach (SPWeb subWeb in web.Webs)
            {
                if (subWeb != null)
                {
                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() for a sub SPWeb: " + subWeb.Url);

                    AddResultsForSPWeb(site, subWeb);

                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() returned from AddResultsForSPWeb for:" + subWeb.Url);

                    subWeb.Dispose();
                }
                else
                {
                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() subweb was null:");
                }
            }
        }
Exemple #5
0
        private static SPFile CreateNewWelcomePage(SPWeb currentWeb, PublishingWeb publishingWeb, SPFile defaultPage)
        {
            PageLayout     welcomeLayout = publishingWeb.GetAvailablePageLayouts(ContentTypeId.WelcomePage)[0];
            PublishingPage welcomePage   = publishingWeb.GetPublishingPages().Add(DefaultFileName, welcomeLayout);

            defaultPage = currentWeb.GetFile(welcomePage.Url);
            publishingWeb.DefaultPage = defaultPage;
            publishingWeb.Update();
            //defaultPage.MoveTo("default.aspx", true);
            return(defaultPage);
        }
        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);
                }
            }
        }
        // this method gets all publishing pages for the web
        private List <string> GetAllPublishingPage()
        {
            List <string> pgList = new List <string>();

            SPWeb                    web                      = SPContext.Current.Web;
            string                   fullPageUrl              = string.Empty;
            PublishingWeb            publishingWeb            = PublishingWeb.GetPublishingWeb(web);
            PublishingPageCollection publishingPageCollection = publishingWeb.GetPublishingPages();
            List <PageLayout>        layouts                  = new List <PageLayout>(publishingWeb.GetAvailablePageLayouts());

            foreach (PageLayout pl in layouts)
            {
                pgList.Add(pl.Name);
            }

            return(pgList);
        }
Exemple #8
0
        private static List <PublishingPageInfo> GetPublishingPages(ISharePointCommandContext context)
        {
            List <PublishingPageInfo> pages = new List <PublishingPageInfo>();

            PublishingWeb            publishingWeb   = PublishingWeb.GetPublishingWeb(context.Web);
            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();

            pages = (from PublishingPage page
                     in publishingPages
                     select new PublishingPageInfo
            {
                Name = page.Name,
                ServerRelativeUrl = page.Uri.AbsolutePath,
                Title = page.Title,
            }).ToList();

            return(pages);
        }
        public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout defaultPageLayout, SPContentType ctype)
        {
            string checkInComment = "CLF3 Automatic Event Handler Page Layout Fix";

            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == defaultPageLayout)
            {
                throw new System.ArgumentNullException("defaultPageLayout");
            }

            SPList list = publishingWeb.PagesList;

            if (list.ContentTypes[defaultPageLayout.AssociatedContentType.Name] == null)
            {
                list.ContentTypes.Add(ctype);
            }
            SPContentType ct = list.ContentTypes[defaultPageLayout.AssociatedContentType.Name];

            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();

            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    publishingPage.CheckOut();
                }
                publishingPage.ListItem["ContentTypeId"] = ct.Id;

                switch (publishingPage.Url)
                {
                default:
                    publishingPage.Layout = defaultPageLayout;
                    publishingPage.Title  = publishingWeb.Title;
                    break;
                }
                publishingPage.Update();
                publishingPage.CheckIn(checkInComment);
            }
        }
        public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout defaultPageLayout, SPContentType ctype)
        {
            string checkInComment = "WET4 Automatic Event Handler Page Layout Fix";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == defaultPageLayout)
            {
                throw new System.ArgumentNullException("defaultPageLayout");
            }

            SPList list = publishingWeb.PagesList;
            if (list.ContentTypes[defaultPageLayout.AssociatedContentType.Name] == null)
            {
                list.ContentTypes.Add(ctype);
            }
            SPContentType ct = list.ContentTypes[defaultPageLayout.AssociatedContentType.Name];

            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    publishingPage.CheckOut();
                }
                publishingPage.ListItem["ContentTypeId"] = ct.Id;

                switch (publishingPage.Url)
                {
                    default:
                        publishingPage.Layout = defaultPageLayout;
                        publishingPage.Title = publishingWeb.Title;
                        break;
                }
                publishingPage.Update();
                publishingPage.CheckIn(checkInComment);
            }
        }
        /// <summary>
        /// Enumerates the specified web.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="web">The web.</param>
        /// <param name="enumerateSubWebs">if set to <c>true</c> [enumerate sub webs].</param>
        private void Enumerate(SPSite site, SPWeb web, bool enumerateSubWebs)
        {
            OnSPWebEnumerated(site, web);

            if (SPListEnumerated != null)
            {
                for (int i = 0; i < web.Lists.Count; i++)
                {
                    OnSPListEnumerated(site, web, web.Lists[i]);
                }
            }

#if MOSS
            if (PublishingPageEnumerated != null)
            {
                if (PublishingWeb.IsPublishingWeb(web))
                {
                    PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
                    foreach (PublishingPage page in pubWeb.GetPublishingPages())
                    {
                        OnPublishingPageEnumerated(site, web, page);
                    }
                }
            }
#endif
            if (enumerateSubWebs)
            {
                foreach (SPWeb subWeb in web.Webs)
                {
                    try
                    {
                        Enumerate(site, subWeb, enumerateSubWebs);
                    }
                    finally
                    {
                        subWeb.Dispose();
                    }
                }
            }
        }
Exemple #12
0
        private List <string> GetAllPublishingPages(PublishingWeb web)
        {
            if (web == null)
            {
                return(new List <string>());
            }
            List <string> allPages = new List <string>();

            // Get all pages from the pages library
            try
            {
                foreach (PublishingPage pubPage in web.GetPublishingPages())
                {
                    if (Path.GetExtension(pubPage.Url) == ".aspx")
                    {
                        allPages.Add(pubPage.Url);
                    }
                }
            }
            catch (Exception) { throw; }

            return(allPages);
        }
        /// <summary>
        /// Adds the nodes.
        /// </summary>
        /// <param name="pubWeb">The publishing web.</param>
        /// <param name="isGlobal">if set to <c>true</c> [is global].</param>
        /// <param name="existingNodes">The existing nodes.</param>
        /// <param name="newNodes">The new nodes.</param>
        private static void AddNodes(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection existingNodes, XmlNodeList newNodes)
        {
            if (newNodes.Count == 0)
                return;

            for (int i = 0; i < newNodes.Count; i++)
            {
                XmlElement newNodeXml = (XmlElement)newNodes[i];
                string url = newNodeXml.SelectSingleNode("Url").InnerText;
                string title = newNodeXml.GetAttribute("Title");
                NodeTypes type = NodeTypes.None;
                if (newNodeXml.SelectSingleNode("NodeType") != null && !string.IsNullOrEmpty(newNodeXml.SelectSingleNode("NodeType").InnerText))
                    type = (NodeTypes)Enum.Parse(typeof(NodeTypes), newNodeXml.SelectSingleNode("NodeType").InnerText);

                bool isVisible = true;
                if (!string.IsNullOrEmpty(newNodeXml.GetAttribute("IsVisible")))
                    isVisible = bool.Parse(newNodeXml.GetAttribute("IsVisible"));

                if (type == NodeTypes.Area)
                {
                    // You can't just add an "Area" node (which represents a sub-site) to the current web if the
                    // url does not correspond with an actual sub-site (the code will appear to work but you won't
                    // see anything when you load the page).  So we need to check and see if the node actually
                    // points to a sub-site - if it does not then change it to "AuthoredLinkToWeb".
                    SPWeb web = null;
                    try
                    {
                        string name = url.Trim('/');
                        if (name.Length != 0 && name.IndexOf("/") > 0)
                        {
                            name = name.Substring(name.LastIndexOf('/') + 1);
                        }
                        try
                        {
                            // pubWeb.Web.Webs[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                            web = pubWeb.Web.Webs[name];
                        }
                        catch (ArgumentException)
                        {
                        }
                        if (web == null || !web.Exists || web.ServerRelativeUrl.ToLower() != url.ToLower())
                        {
                            // The url doesn't correspond with a sub-site for the current web so change the node type.
                            // This is most likely due to copying navigation elements from another site
                            type = NodeTypes.AuthoredLinkToWeb;
                        }
                        else if (web.Exists && web.ServerRelativeUrl.ToLower() == url.ToLower())
                        {
                            // We did find a matching sub-site so now we need to set the visibility
                            if (isVisible)
                                pubWeb.Navigation.IncludeInNavigation(isGlobal, web.ID);
                            else
                                pubWeb.Navigation.ExcludeFromNavigation(isGlobal, web.ID);
                        }
                    }
                    finally
                    {
                        if (web != null)
                            web.Dispose();
                    }

                }
                else if (type == NodeTypes.Page)
                {
                    // Adding links to pages has the same limitation as sub-sites (Area nodes) so we need to make
                    // sure it actually exists and if it doesn't then change the node type.
                    PublishingPage page = null;
                    try
                    {
                        // Note that GetPublishingPages()[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                        page = pubWeb.GetPublishingPages()[url];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (page == null)
                    {
                        // The url doesn't correspond with a page for the current web so change the node type.
                        // This is most likely due to copying navigation elements from another site
                        type = NodeTypes.AuthoredLinkToPage;
                        url = pubWeb.Web.Site.MakeFullUrl(url);
                    }
                    else
                    {
                        // We did find a matching page so now we need to set the visibility
                        if (isVisible)
                            pubWeb.Navigation.IncludeInNavigation(isGlobal, page.ListItem.UniqueId);
                        else
                            pubWeb.Navigation.ExcludeFromNavigation(isGlobal, page.ListItem.UniqueId);
                    }
                }

                // If it's not a sub-site or a page that's part of the current web and it's set to
                // not be visible then just move on to the next (there is no visibility setting for
                // nodes that are not of type Area or Page).
                if (!isVisible && type != NodeTypes.Area && type != NodeTypes.Page)
                    continue;

                // Finally, can add the node to the collection.
                SPNavigationNode node = SPNavigationSiteMapNode.CreateSPNavigationNode(
                    title, url, type, existingNodes);

                // Now we need to set all the other properties
                foreach (XmlElement property in newNodeXml.ChildNodes)
                {
                    // We've already set these so don't set them again.
                    if (property.Name == "Url" || property.Name == "Node" || property.Name == "NodeType")
                        continue;

                    // CreatedDate and LastModifiedDate need to be the correct type - all other properties are strings
                    if (property.Name == "CreatedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["CreatedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }
                    if (property.Name == "LastModifiedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["LastModifiedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }

                    node.Properties[property.Name] = property.InnerText;
                }
                // If we didn't have a CreatedDate or LastModifiedDate then set them to now.
                if (node.Properties["CreatedDate"] == null)
                    node.Properties["CreatedDate"] = DateTime.Now;
                if (node.Properties["LastModifiedDate"] == null)
                    node.Properties["LastModifiedDate"] = DateTime.Now;

                // Save our changes to the node.
                node.Update();
                node.MoveToLast(existingNodes); // Should already be at the end but I prefer to make sure :)

                XmlNodeList childNodes = newNodeXml.SelectNodes("Node");

                // If we have child nodes then make a recursive call passing in the current nodes Children property as the collection to add to.
                if (childNodes.Count > 0)
                    AddNodes(pubWeb, isGlobal, node.Children, childNodes);
            }
        }
        /// <summary>
        /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery.
        /// </summary>
        /// <param name="publishingWeb">The target publishing web.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="pageLayoutUrl">The page layout URL.</param>
        /// <param name="searchRegex">The search regex.</param>
        /// <param name="replaceString">The replace string.</param>
        /// <param name="fixContact">if set to <c>true</c> [fix contact].</param>
        /// <param name="test">if set to <c>true</c> [test].</param>
        public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test)
        {
            if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web))
                return;

            PublishingPageCollection pages;
            int tryCount = 0;
            while (true)
            {
                try
                {
                    tryCount++;
                    pages = publishingWeb.GetPublishingPages();
                    break;
                }
                catch (InvalidPublishingWebException)
                {
                    // The following is meant to deal with a timing issue when using this method in conjuction with other commands.  When
                    // used independently this should be unnecessary.
                    if (tryCount > 4)
                        throw;
                    Thread.Sleep(10000);
                    SPWeb web = publishingWeb.Web;
                    SPSite site = web.Site;
                    string url = site.MakeFullUrl(web.ServerRelativeUrl);
                    site.Close();
                    site.Dispose();
                    web.Close();
                    web.Dispose();
                    publishingWeb.Close();
                    site = new SPSite(url);
                    web = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url));
                    publishingWeb = PublishingWeb.GetPublishingWeb(web);
                }
            }

            foreach (PublishingPage page in pages)
            {
                if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower()))
                    continue;

                if (page.ListItem[FieldId.PageLayout] == null)
                    continue;

                Logger.Write("Progress: Begin processing {0}.", page.Url);
                Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString());

                // Can't edit items that are checked out.
                if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem))
                {
                    Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping.");
                    continue;
                }

                SPFieldUrlValue url;
                if (string.IsNullOrEmpty(pageLayoutUrl))
                {
                    if (searchRegex == null)
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                        {
                            Logger.WriteWarning("WARNING: Current page layout is empty - skipping.  Use the 'pagelayout' parameter to set a page layout.");

                            continue;
                        }

                        // We didn't get a layout url passed in or a regular expression so try and fix the existing url
                        url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                        if (string.IsNullOrEmpty(url.Url) ||
                            url.Url.IndexOf("/_catalogs/") < 0)
                        {
                            Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping.  Use the 'pagelayout' parameter to set a page layout  Layout Url: {0}", url.ToString());
                            continue;
                        }

                        string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') +
                                      url.Url.Substring(url.Url.IndexOf("/_catalogs/"));

                        string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl);

                        if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant())
                        {
                            Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                            continue;
                        }
                        url.Url = newUrl;
                        url.Description = newDesc;
                    }
                    else
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                            Logger.Write("Progress: Current page layout is empty - skipping.  Use the pagelayout parameter to set a page layout.");

                        // A regular expression was passed in so use it to fix the page layout url if we find a match.
                        if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout]))
                        {
                            url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                            string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString);
                            if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant())
                            {
                                Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                                continue;
                            }
                            url = new SPFieldUrlValue(newUrl);
                        }
                        else
                        {
                            Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping.");
                            continue;
                        }
                    }
                }
                else
                {
                    // The user passed in an url string so use it.
                    if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout])
                    {
                        Logger.Write("Progress: Current layout matches provided layout - skipping.");
                        continue;
                    }

                    url = new SPFieldUrlValue(pageLayoutUrl);
                }

                string fileName = url.Url.Substring(url.Url.LastIndexOf('/'));
                // Make sure that the URLs are server relative instead of absolute.
                //if (url.Description.ToLowerInvariant().StartsWith("http"))
                //    url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName;
                //if (url.Url.ToLowerInvariant().StartsWith("http"))
                //    url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName;

                if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant())
                    continue; // No difference detected so move on.

                Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString());

                if (fixContact)
                {
                    SPUser contact = null;
                    try
                    {
                        contact = page.Contact;
                    }
                    catch (SPException)
                    {
                    }
                    if (contact == null)
                    {
                        Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString());
                        page.Contact = publishingWeb.Web.CurrentUser;

                        if (!test)
                            page.ListItem.SystemUpdate();
                    }
                }

                if (test)
                    continue;

                try
                {
                    bool publish = false;
                    if (!Utilities.IsCheckedOut(page.ListItem))
                    {
                        page.CheckOut();
                        publish = true;
                    }
                    page.ListItem[FieldId.PageLayout] = url;
                    page.ListItem.UpdateOverwriteVersion();

                    if (publish)
                    {
                        Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems();
                        itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page));
                }
            }
        }
        /// <summary>
        /// Enumerates the collection.
        /// </summary>
        /// <param name="pubWeb">The publishing web.</param>
        /// <param name="isGlobal">if set to <c>true</c> [is global].</param>
        /// <param name="nodes">The nodes.</param>
        /// <param name="xmlParentNode">The XML parent node.</param>
        private static void EnumerateCollection(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection nodes, XmlElement xmlParentNode)
        {
            if (nodes == null || nodes.Count == 0)
                return;

            foreach (SPNavigationNode node in nodes)
            {
                NodeTypes type = NodeTypes.None;
                if (node.Properties["NodeType"] != null && !string.IsNullOrEmpty(node.Properties["NodeType"].ToString()))
                    type = (NodeTypes)Enum.Parse(typeof(NodeTypes), node.Properties["NodeType"].ToString());

                if (isGlobal)
                {
                    if ((type == NodeTypes.Area && !pubWeb.Navigation.GlobalIncludeSubSites) ||
                        (type == NodeTypes.Page && !pubWeb.Navigation.GlobalIncludePages))
                        continue;
                }
                else
                {
                    if ((type == NodeTypes.Area && !pubWeb.Navigation.CurrentIncludeSubSites) ||
                        (type == NodeTypes.Page && !pubWeb.Navigation.CurrentIncludePages))
                        continue;
                }

                XmlElement xmlChildNode = xmlParentNode.OwnerDocument.CreateElement("Node");
                xmlParentNode.AppendChild(xmlChildNode);

                xmlChildNode.SetAttribute("Id", node.Id.ToString());
                xmlChildNode.SetAttribute("Title", node.Title);

                // Set the default visibility to true.
                xmlChildNode.SetAttribute("IsVisible", node.IsVisible.ToString());

                #region Determine Visibility

                if (type == NodeTypes.Area)
                {
                    SPWeb web = null;
                    try
                    {
                        string name = node.Url.Trim('/');
                        if (name.Length != 0 && name.IndexOf("/") > 0)
                        {
                            name = name.Substring(name.LastIndexOf('/') + 1);
                        }
                        try
                        {
                            web = pubWeb.Web.Webs[name];
                        }
                        catch (ArgumentException)
                        {
                        }

                        if (web != null && web.Exists && web.ServerRelativeUrl.ToLower() == node.Url.ToLower() &&
                            PublishingWeb.IsPublishingWeb(web))
                        {
                            PublishingWeb tempPubWeb = PublishingWeb.GetPublishingWeb(web);
                            if (isGlobal)
                                xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInGlobalNavigation.ToString());
                            else
                                xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInCurrentNavigation.ToString());
                        }
                    }
                    finally
                    {
                        if (web != null)
                            web.Dispose();
                    }
                }
                else if (type == NodeTypes.Page)
                {
                    PublishingPage page = null;
                    try
                    {
                        page = pubWeb.GetPublishingPages()[node.Url];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (page != null)
                    {
                        if (isGlobal)
                            xmlChildNode.SetAttribute("IsVisible", page.IncludeInGlobalNavigation.ToString());
                        else
                            xmlChildNode.SetAttribute("IsVisible", page.IncludeInCurrentNavigation.ToString());
                    }
                }
                #endregion

                XmlElement xmlProp = xmlParentNode.OwnerDocument.CreateElement("Url");
                xmlProp.InnerText = node.Url;
                xmlChildNode.AppendChild(xmlProp);

                foreach (DictionaryEntry d in node.Properties)
                {
                    xmlProp = xmlParentNode.OwnerDocument.CreateElement(d.Key.ToString());
                    xmlProp.InnerText = d.Value.ToString();
                    xmlChildNode.AppendChild(xmlProp);
                }
                EnumerateCollection(pubWeb, isGlobal, node.Children, xmlChildNode);
            }
        }
Exemple #16
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);
        }
        /// <summary>
        /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery.
        /// </summary>
        /// <param name="publishingWeb">The target publishing web.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="pageLayoutUrl">The page layout URL.</param>
        /// <param name="searchRegex">The search regex.</param>
        /// <param name="replaceString">The replace string.</param>
        /// <param name="fixContact">if set to <c>true</c> [fix contact].</param>
        /// <param name="test">if set to <c>true</c> [test].</param>
        public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test)
        {
            if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web))
            {
                return;
            }

            PublishingPageCollection pages;
            int tryCount = 0;

            while (true)
            {
                try
                {
                    tryCount++;
                    pages = publishingWeb.GetPublishingPages();
                    break;
                }
                catch (InvalidPublishingWebException)
                {
                    // The following is meant to deal with a timing issue when using this method in conjuction with other commands.  When
                    // used independently this should be unnecessary.
                    if (tryCount > 4)
                    {
                        throw;
                    }
                    Thread.Sleep(10000);
                    SPWeb  web  = publishingWeb.Web;
                    SPSite site = web.Site;
                    string url  = site.MakeFullUrl(web.ServerRelativeUrl);
                    site.Close();
                    site.Dispose();
                    web.Close();
                    web.Dispose();
                    publishingWeb.Close();
                    site          = new SPSite(url);
                    web           = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url));
                    publishingWeb = PublishingWeb.GetPublishingWeb(web);
                }
            }

            foreach (PublishingPage page in pages)
            {
                if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower()))
                {
                    continue;
                }

                if (page.ListItem[FieldId.PageLayout] == null)
                {
                    continue;
                }

                Logger.Write("Progress: Begin processing {0}.", page.Url);
                Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString());

                // Can't edit items that are checked out.
                if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem))
                {
                    Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping.");
                    continue;
                }

                SPFieldUrlValue url;
                if (string.IsNullOrEmpty(pageLayoutUrl))
                {
                    if (searchRegex == null)
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                        {
                            Logger.WriteWarning("WARNING: Current page layout is empty - skipping.  Use the 'pagelayout' parameter to set a page layout.");

                            continue;
                        }

                        // We didn't get a layout url passed in or a regular expression so try and fix the existing url
                        url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                        if (string.IsNullOrEmpty(url.Url) ||
                            url.Url.IndexOf("/_catalogs/") < 0)
                        {
                            Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping.  Use the 'pagelayout' parameter to set a page layout  Layout Url: {0}", url.ToString());
                            continue;
                        }


                        string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') +
                                        url.Url.Substring(url.Url.IndexOf("/_catalogs/"));

                        string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl);

                        if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant())
                        {
                            Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                            continue;
                        }
                        url.Url         = newUrl;
                        url.Description = newDesc;
                    }
                    else
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                        {
                            Logger.Write("Progress: Current page layout is empty - skipping.  Use the pagelayout parameter to set a page layout.");
                        }

                        // A regular expression was passed in so use it to fix the page layout url if we find a match.
                        if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout]))
                        {
                            url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                            string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString);
                            if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant())
                            {
                                Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                                continue;
                            }
                            url = new SPFieldUrlValue(newUrl);
                        }
                        else
                        {
                            Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping.");
                            continue;
                        }
                    }
                }
                else
                {
                    // The user passed in an url string so use it.
                    if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout])
                    {
                        Logger.Write("Progress: Current layout matches provided layout - skipping.");
                        continue;
                    }

                    url = new SPFieldUrlValue(pageLayoutUrl);
                }

                string fileName = url.Url.Substring(url.Url.LastIndexOf('/'));
                // Make sure that the URLs are server relative instead of absolute.
                //if (url.Description.ToLowerInvariant().StartsWith("http"))
                //    url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName;
                //if (url.Url.ToLowerInvariant().StartsWith("http"))
                //    url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName;

                if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant())
                {
                    continue; // No difference detected so move on.
                }
                Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString());


                if (fixContact)
                {
                    SPUser contact = null;
                    try
                    {
                        contact = page.Contact;
                    }
                    catch (SPException)
                    {
                    }
                    if (contact == null)
                    {
                        Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString());
                        page.Contact = publishingWeb.Web.CurrentUser;

                        if (!test)
                        {
                            page.ListItem.SystemUpdate();
                        }
                    }
                }

                if (test)
                {
                    continue;
                }

                try
                {
                    bool publish = false;
                    if (!Utilities.IsCheckedOut(page.ListItem))
                    {
                        page.CheckOut();
                        publish = true;
                    }
                    page.ListItem[FieldId.PageLayout] = url;
                    page.ListItem.UpdateOverwriteVersion();

                    if (publish)
                    {
                        Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems();
                        itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page));
                }
            }
        }
        /// <summary>
        /// Adds the nodes.
        /// </summary>
        /// <param name="pubWeb">The publishing web.</param>
        /// <param name="isGlobal">if set to <c>true</c> [is global].</param>
        /// <param name="existingNodes">The existing nodes.</param>
        /// <param name="newNodes">The new nodes.</param>
        private static void AddNodes(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection existingNodes, XmlNodeList newNodes)
        {
            if (newNodes.Count == 0)
            {
                return;
            }

            for (int i = 0; i < newNodes.Count; i++)
            {
                XmlElement newNodeXml = (XmlElement)newNodes[i];
                string     url        = newNodeXml.SelectSingleNode("Url").InnerText;
                string     title      = newNodeXml.GetAttribute("Title");
                NodeTypes  type       = NodeTypes.None;
                if (newNodeXml.SelectSingleNode("NodeType") != null && !string.IsNullOrEmpty(newNodeXml.SelectSingleNode("NodeType").InnerText))
                {
                    type = (NodeTypes)Enum.Parse(typeof(NodeTypes), newNodeXml.SelectSingleNode("NodeType").InnerText);
                }

                bool isVisible = true;
                if (!string.IsNullOrEmpty(newNodeXml.GetAttribute("IsVisible")))
                {
                    isVisible = bool.Parse(newNodeXml.GetAttribute("IsVisible"));
                }

                if (type == NodeTypes.Area)
                {
                    // You can't just add an "Area" node (which represents a sub-site) to the current web if the
                    // url does not correspond with an actual sub-site (the code will appear to work but you won't
                    // see anything when you load the page).  So we need to check and see if the node actually
                    // points to a sub-site - if it does not then change it to "AuthoredLinkToWeb".
                    SPWeb web = null;
                    try
                    {
                        string name = url.Trim('/');
                        if (name.Length != 0 && name.IndexOf("/") > 0)
                        {
                            name = name.Substring(name.LastIndexOf('/') + 1);
                        }
                        try
                        {
                            // pubWeb.Web.Webs[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                            web = pubWeb.Web.Webs[name];
                        }
                        catch (ArgumentException)
                        {
                        }
                        if (web == null || !web.Exists || web.ServerRelativeUrl.ToLower() != url.ToLower())
                        {
                            // The url doesn't correspond with a sub-site for the current web so change the node type.
                            // This is most likely due to copying navigation elements from another site
                            type = NodeTypes.AuthoredLinkToWeb;
                        }
                        else if (web.Exists && web.ServerRelativeUrl.ToLower() == url.ToLower())
                        {
                            // We did find a matching sub-site so now we need to set the visibility
                            if (isVisible)
                            {
                                pubWeb.Navigation.IncludeInNavigation(isGlobal, web.ID);
                            }
                            else
                            {
                                pubWeb.Navigation.ExcludeFromNavigation(isGlobal, web.ID);
                            }
                        }
                    }
                    finally
                    {
                        if (web != null)
                        {
                            web.Dispose();
                        }
                    }
                }
                else if (type == NodeTypes.Page)
                {
                    // Adding links to pages has the same limitation as sub-sites (Area nodes) so we need to make
                    // sure it actually exists and if it doesn't then change the node type.
                    PublishingPage page = null;
                    try
                    {
                        // Note that GetPublishingPages()[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                        page = pubWeb.GetPublishingPages()[url];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (page == null)
                    {
                        // The url doesn't correspond with a page for the current web so change the node type.
                        // This is most likely due to copying navigation elements from another site
                        type = NodeTypes.AuthoredLinkToPage;
                        url  = pubWeb.Web.Site.MakeFullUrl(url);
                    }
                    else
                    {
                        // We did find a matching page so now we need to set the visibility
                        if (isVisible)
                        {
                            pubWeb.Navigation.IncludeInNavigation(isGlobal, page.ListItem.UniqueId);
                        }
                        else
                        {
                            pubWeb.Navigation.ExcludeFromNavigation(isGlobal, page.ListItem.UniqueId);
                        }
                    }
                }

                // If it's not a sub-site or a page that's part of the current web and it's set to
                // not be visible then just move on to the next (there is no visibility setting for
                // nodes that are not of type Area or Page).
                if (!isVisible && type != NodeTypes.Area && type != NodeTypes.Page)
                {
                    continue;
                }

                // Finally, can add the node to the collection.
                SPNavigationNode node = SPNavigationSiteMapNode.CreateSPNavigationNode(
                    title, url, type, existingNodes);


                // Now we need to set all the other properties
                foreach (XmlElement property in newNodeXml.ChildNodes)
                {
                    // We've already set these so don't set them again.
                    if (property.Name == "Url" || property.Name == "Node" || property.Name == "NodeType")
                    {
                        continue;
                    }

                    // CreatedDate and LastModifiedDate need to be the correct type - all other properties are strings
                    if (property.Name == "CreatedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["CreatedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }
                    if (property.Name == "LastModifiedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["LastModifiedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }

                    node.Properties[property.Name] = property.InnerText;
                }
                // If we didn't have a CreatedDate or LastModifiedDate then set them to now.
                if (node.Properties["CreatedDate"] == null)
                {
                    node.Properties["CreatedDate"] = DateTime.Now;
                }
                if (node.Properties["LastModifiedDate"] == null)
                {
                    node.Properties["LastModifiedDate"] = DateTime.Now;
                }

                // Save our changes to the node.
                node.Update();
                node.MoveToLast(existingNodes); // Should already be at the end but I prefer to make sure :)

                XmlNodeList childNodes = newNodeXml.SelectNodes("Node");

                // If we have child nodes then make a recursive call passing in the current nodes Children property as the collection to add to.
                if (childNodes.Count > 0)
                {
                    AddNodes(pubWeb, isGlobal, node.Children, childNodes);
                }
            }
        }
        /// <summary>
        /// Enumerates the collection.
        /// </summary>
        /// <param name="pubWeb">The publishing web.</param>
        /// <param name="isGlobal">if set to <c>true</c> [is global].</param>
        /// <param name="nodes">The nodes.</param>
        /// <param name="xmlParentNode">The XML parent node.</param>
        private static void EnumerateCollection(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection nodes, XmlElement xmlParentNode)
        {
            if (nodes == null || nodes.Count == 0)
            {
                return;
            }

            foreach (SPNavigationNode node in nodes)
            {
                NodeTypes type = NodeTypes.None;
                if (node.Properties["NodeType"] != null && !string.IsNullOrEmpty(node.Properties["NodeType"].ToString()))
                {
                    type = (NodeTypes)Enum.Parse(typeof(NodeTypes), node.Properties["NodeType"].ToString());
                }

                if (isGlobal)
                {
                    if ((type == NodeTypes.Area && !pubWeb.Navigation.GlobalIncludeSubSites) ||
                        (type == NodeTypes.Page && !pubWeb.Navigation.GlobalIncludePages))
                    {
                        continue;
                    }
                }
                else
                {
                    if ((type == NodeTypes.Area && !pubWeb.Navigation.CurrentIncludeSubSites) ||
                        (type == NodeTypes.Page && !pubWeb.Navigation.CurrentIncludePages))
                    {
                        continue;
                    }
                }

                XmlElement xmlChildNode = xmlParentNode.OwnerDocument.CreateElement("Node");
                xmlParentNode.AppendChild(xmlChildNode);

                xmlChildNode.SetAttribute("Id", node.Id.ToString());
                xmlChildNode.SetAttribute("Title", node.Title);


                // Set the default visibility to true.
                xmlChildNode.SetAttribute("IsVisible", node.IsVisible.ToString());

                #region Determine Visibility

                if (type == NodeTypes.Area)
                {
                    SPWeb web = null;
                    try
                    {
                        string name = node.Url.Trim('/');
                        if (name.Length != 0 && name.IndexOf("/") > 0)
                        {
                            name = name.Substring(name.LastIndexOf('/') + 1);
                        }
                        try
                        {
                            web = pubWeb.Web.Webs[name];
                        }
                        catch (ArgumentException)
                        {
                        }

                        if (web != null && web.Exists && web.ServerRelativeUrl.ToLower() == node.Url.ToLower() &&
                            PublishingWeb.IsPublishingWeb(web))
                        {
                            PublishingWeb tempPubWeb = PublishingWeb.GetPublishingWeb(web);
                            if (isGlobal)
                            {
                                xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInGlobalNavigation.ToString());
                            }
                            else
                            {
                                xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInCurrentNavigation.ToString());
                            }
                        }
                    }
                    finally
                    {
                        if (web != null)
                        {
                            web.Dispose();
                        }
                    }
                }
                else if (type == NodeTypes.Page)
                {
                    PublishingPage page = null;
                    try
                    {
                        page = pubWeb.GetPublishingPages()[node.Url];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (page != null)
                    {
                        if (isGlobal)
                        {
                            xmlChildNode.SetAttribute("IsVisible", page.IncludeInGlobalNavigation.ToString());
                        }
                        else
                        {
                            xmlChildNode.SetAttribute("IsVisible", page.IncludeInCurrentNavigation.ToString());
                        }
                    }
                }
                #endregion

                XmlElement xmlProp = xmlParentNode.OwnerDocument.CreateElement("Url");
                xmlProp.InnerText = node.Url;
                xmlChildNode.AppendChild(xmlProp);

                foreach (DictionaryEntry d in node.Properties)
                {
                    xmlProp           = xmlParentNode.OwnerDocument.CreateElement(d.Key.ToString());
                    xmlProp.InnerText = d.Value.ToString();
                    xmlChildNode.AppendChild(xmlProp);
                }
                EnumerateCollection(pubWeb, isGlobal, node.Children, xmlChildNode);
            }
        }
        protected override IEnumerable <PublishingPage> RetrieveDataObjects()
        {
            List <PublishingPage> publishingPages = new List <PublishingPage>();

            switch (ParameterSetName)
            {
            case "SPWeb":
                foreach (SPWebPipeBind webPipe in Web)
                {
                    SPWeb web = webPipe.Read();

                    WriteVerbose("Getting publishing page from " + web.Url);
                    if (!PublishingWeb.IsPublishingWeb(web))
                    {
                        WriteWarning(string.Format("Web \"{0}\" is not a publishing web and will be skipped.", web.Url));
                        continue;
                    }
                    PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);


                    if (PageName == null || PageName.Length == 0)
                    {
                        foreach (PublishingPage page in pubWeb.GetPublishingPages())
                        {
                            publishingPages.Add(page);
                        }
                    }
                    else
                    {
                        foreach (string pageName in PageName)
                        {
                            string pageUrl = string.Format("{0}/{1}/{2}", web.Url.TrimEnd('/'), pubWeb.PagesListName, pageName.Trim('/'));

                            try
                            {
                                PublishingPage page = pubWeb.GetPublishingPage(pageUrl);
                                if (page != null)
                                {
                                    publishingPages.Add(page);
                                }
                                else
                                {
                                    WriteWarning("Could not locate the specified page: " + pageUrl);
                                }
                            }
                            catch (ArgumentException)
                            {
                                WriteWarning("Could not locate the specified page: " + pageUrl);
                            }
                        }
                    }
                }
                break;

            case "SPFile":
                foreach (SPFilePipeBind filePipe in Identity)
                {
                    SPFile file = filePipe.Read();
                    if (!PublishingWeb.IsPublishingWeb(file.Web))
                    {
                        WriteWarning(string.Format("Web \"{0}\" is not a publishing web and will be skipped.", file.Web.Url));
                        continue;
                    }

                    WriteVerbose("Getting publishing page from " + file.Url);
                    try
                    {
                        PublishingPage page = null;
                        if (file.Exists)
                        {
                            page = PublishingPage.GetPublishingPage(file.Item);
                        }

                        if (page != null)
                        {
                            publishingPages.Add(page);
                        }
                        else
                        {
                            WriteWarning("Could not locate the specified page: " + file.Url);
                        }
                    }
                    catch (ArgumentException)
                    {
                        WriteWarning("Could not locate the specified page: " + file.Url);
                    }
                }
                break;
            }

            foreach (PublishingPage page in publishingPages)
            {
                AssignmentCollection.Add(page.PublishingWeb.Web);
                AssignmentCollection.Add(page.PublishingWeb.Web.Site);
                WriteResult(page);
            }

            return(null);
        }
Exemple #21
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPList objPagesList = null;
                Guid   ListId;

                SPSite site = properties.Feature.Parent as SPSite;
                SPWeb  web  = null;
                if (site == null)
                {
                    web = properties.Feature.Parent as SPWeb;
                    if (web == null)
                    {
                        return;
                    }

                    site = web.Site;
                }
                else
                {
                    web = site.RootWeb;
                }

                web.AllowUnsafeUpdates = true;

                #region Site navigation and welcome page

                //Assign default page of the site to home.aspx
                PublishingWeb objPublishingWeb = PublishingWeb.GetPublishingWeb(web);
                SPFile        objHomePageFile  = web.GetFile(objPublishingWeb.PagesListName + "/Home.aspx");
                objPublishingWeb.DefaultPage = objHomePageFile;
                objPublishingWeb.Update();
                web.Update();

                //Hide the thanks.aspx page from the top navigation
                PublishingPageCollection pages = objPublishingWeb.GetPublishingPages();
                foreach (PublishingPage page in pages)
                {
                    if (page.Name.ToLower() == "thanks.aspx")
                    {
                        page.IncludeInGlobalNavigation = false;
                    }
                }

                //Delete default.aspx page created when activated publishing feature
                //Get the Pages List for current Locale
                ListId       = PublishingWeb.GetPagesListId(web);
                objPagesList = web.Lists[ListId];
                string urlPagetoDelete = objPagesList.RootFolder.ServerRelativeUrl + "/default.aspx";
                if (web.GetFile(urlPagetoDelete).Exists)
                {
                    SPFile objFile = objPagesList.RootFolder.Files["default.aspx"];
                    if (objFile != null)
                    {
                        if (objFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                        {
                            objFile.CheckOut();
                        }
                        objFile.Delete();
                    }
                }

                #endregion

                #region Create Config List & Add Columns

                //Create Config List
                SPList configList;
                configList = web.Lists.TryGetList(Constants.CONFIG_LIST);
                if (configList == null)
                {
                    web.Lists.Add(Constants.CONFIG_LIST, "This list contains the HTML for the Global Contact Us Control, Footer, Admin & Self Mail contents and subjects", SPListTemplateType.GenericList);
                    configList = web.Lists.TryGetList(Constants.CONFIG_LIST);
                }

                //Add Columns in List
                if (configList != null)
                {
                    if (!configList.Fields.ContainsField("Value"))
                    {
                        string FieldXML = "<Field Type='Note' Description='The list of Tokens that can be provided in this column are: \nName of User: #FROMNAME#\nCompany: #FROMCOMPANY#\nPhone: #FROMPHONE#\nEmail: #FROMEMAIL#\nUser Query: #BODY#' DisplayName='Value' Required='TRUE' NumLines='6' StaticName='Value' Name='Value' RichText='TRUE' RichTextMode='FullHtml' IsolateStyles='FALSE' />";
                        configList.Fields.AddFieldAsXml(FieldXML, true, SPAddFieldOptions.Default);
                        //configList.Fields.Add("Value", SPFieldType.Note, false);
                        configList.Update();
                    }
                }

                #endregion

                #region Add Configuration Items to Config List

                //Add Footer configuration value
                SPListItem itemFooter = configList.Items.Add();
                itemFooter["Title"] = Constants.CONFIG_LIST_FOOTERVALUE;
                itemFooter["Value"] = Constants.FOOTER_VALUE;
                itemFooter.Update();

                //Add Contact Us Control configuration value
                SPListItem itemContactInfo = configList.Items.Add();
                itemContactInfo["Title"] = Constants.CONFIG_LIST_CONTACTVALUE;
                itemContactInfo["Value"] = Constants.CONTACT_CONTROL_VALUE;
                itemContactInfo.Update();

                //Add Administrator mail content configuration value
                SPListItem itemAdminMailContent = configList.Items.Add();
                itemAdminMailContent["Title"] = Constants.CONFIG_LIST_ADMINMAILVALUE;
                itemAdminMailContent["Value"] = Constants.ADMINMAILCONTENT_VALUE;
                itemAdminMailContent.Update();

                //Add User mail content configuration value
                SPListItem itemUserMailContent = configList.Items.Add();
                itemUserMailContent["Title"] = Constants.CONFIG_LIST_USERMAILVALUE;
                itemUserMailContent["Value"] = Constants.USERMAILCONTENT_VALUE;
                itemUserMailContent.Update();

                //Add Admin mail Subject configuration value
                SPListItem itemAdminMailSubject = configList.Items.Add();
                itemAdminMailSubject["Title"] = Constants.CONFIG_LIST_ADMINMAILSUBJECT;
                itemAdminMailSubject["Value"] = Constants.ADMINMAILSUBJECT_VALUE;
                itemAdminMailSubject.Update();

                //Add User mail Subject configuration value
                SPListItem itemUserMailSubject = configList.Items.Add();
                itemUserMailSubject["Title"] = Constants.CONFIG_LIST_USERMAILSUBJECT;
                itemUserMailSubject["Value"] = Constants.USERMAILSUBJECT_VALUE;
                itemUserMailSubject.Update();

                #endregion

                #region Set Default page layout

                //Set default page layout of site to internal page layout
                if (objPublishingWeb != null)
                {
                    PageLayout _pageLayout = (from _pl in objPublishingWeb.GetAvailablePageLayouts()
                                              where _pl.Name == "BrickRedSmallBusinessInnerPageLayout.aspx"
                                              select _pl).FirstOrDefault();
                    objPublishingWeb.SetDefaultPageLayout(_pageLayout, true);
                    objPublishingWeb.Update();
                }

                #endregion

                #region Apply Custom Theme

                //Apply brickRed Small Business theme to the site created
                using (ThmxTheme theme = ThmxTheme.Open(web.Site, "./_catalogs/theme/" + Constants.THEME_NAME + ".thmx"))
                {
                    theme.ApplyTo(web, false);
                }

                #endregion

                #region Add Column and Item to the Service List

                SPList servicesList = web.Lists.TryGetList(Constants.SERVICES_LIST_NAME);
                if (servicesList != null)
                {
                    if (!servicesList.Fields.ContainsField("DetailedDescription"))
                    {
                        //create the column if it does not exists
                        string FieldXML = "<Field Type='Note' Description='Displays the detailed description of the services offered' DisplayName='Detailed Description' Required='TRUE' NumLines='6' StaticName='DetailedDescription' Name='DetailedDescription' RichText='TRUE' RichTextMode='FullHtml' IsolateStyles='FALSE' UnlimitedLengthInDocumentLibrary='TRUE'/>";
                        servicesList.Fields.AddFieldAsXml(FieldXML, true, SPAddFieldOptions.Default);
                        servicesList.Update();

                        string[] DETAILED_DESCRIPTION_SERVICE = { "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis turpis eros, mattis et vestibulum in, suscipit et metus. Duis nec placerat felis. Nam eget pulvinar sem. Sed dictum gravida lobortis. Phasellus ut pretium diam. Vestibulum vel velit magna, congue sollicitudin orci. Donec quis mauris at ante volutpat ornare. Nulla metus enim, fringilla at eleifend a, pulvinar a turpis. Sed ut laoreet libero. Ut ipsum felis, varius eget pharetra et, mattis vitae augue. Aliquam erat volutpat. Quisque viverra turpis ut lorem gravida accumsan. Integer est risus, aliquam eget convallis id, malesuada vitae nunc. Ut eu ipsum velit, eget semper dui. </p><p>Integer commodo dui id nulla accumsan ullamcorper. Donec eu urna id lorem venenatis vestibulum. Donec nec nisl dolor. Nulla porta condimentum lacus eu adipiscing. Aliquam nec tellus eu lectus ultrices consequat et nec turpis. Suspendisse vehicula porta urna, ac lobortis nisl viverra at. Curabitur ac velit nibh. Mauris molestie, nibh quis vestibulum fringilla, arcu eros hendrerit mi, id tempor odio lacus in quam. Mauris tristique urna eget est condimentum mattis. Sed nec lacus massa, ut dignissim elit. Vivamus augue libero, varius dictum pretium quis, auctor eget urna. Donec semper luctus dolor, at dapibus nunc fermentum a. </p>",
                                                                  "<p>Suspendisse laoreet, nulla vitae volutpat commodo, nulla nunc porta risus, eget laoreet nunc augue in felis. Quisque sed felis felis, a dictum felis. Nullam vulputate rhoncus odio, vitae tincidunt nisl vehicula eget. Donec porttitor ante orci, nec luctus elit. Vivamus massa augue, consectetur in tempus sit amet, rhoncus tristique neque. Nam elit nibh, euismod auctor tristique ut, tincidunt sed nibh. Duis tempor, dui sit amet condimentum ullamcorper, eros risus interdum nulla, ut facilisis sapien neque nec urna. Suspendisse urna lorem, rutrum ac varius vel, tempor eget risus. Suspendisse potenti. Etiam tempus gravida erat, ut commodo leo vulputate non. Praesent et risus nisl. Mauris pharetra pellentesque enim, non pulvinar tortor eleifend congue.</p>Integer commodo dui id nulla accumsan ullamcorper. Donec eu urna id lorem venenatis vestibulum. Donec nec nisl dolor. Nulla porta condimentum lacus eu adipiscing. Aliquam nec tellus eu lectus ultrices consequat et nec turpis. Suspendisse vehicula porta urna, ac lobortis nisl viverra at. Curabitur ac velit nibh. Mauris molestie, nibh quis vestibulum fringilla, arcu eros hendrerit mi, id tempor odio lacus in quam. Mauris tristique urna eget est condimentum mattis. Sed nec lacus massa, ut dignissim elit. Vivamus augue libero, varius dictum pretium quis, auctor eget urna. Donec semper luctus dolor, at dapibus nunc fermentum a.</p>",
                                                                  "<p>Integer commodo dui id nulla accumsan ullamcorper. Donec eu urna id lorem venenatis vestibulum. Donec nec nisl dolor. Nulla porta condimentum lacus eu adipiscing. Aliquam nec tellus eu lectus ultrices consequat et nec turpis. Suspendisse vehicula porta urna, ac lobortis nisl viverra at. Curabitur ac velit nibh. Mauris molestie, nibh quis vestibulum fringilla, arcu eros hendrerit mi, id tempor odio lacus in quam. Mauris tristique urna eget est condimentum mattis. Sed nec lacus massa, ut dignissim elit. Vivamus augue libero, varius dictum pretium quis, auctor eget urna. Donec semper luctus dolor, at dapibus nunc fermentum a.</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis turpis eros, mattis et vestibulum in, suscipit et metus. Duis nec placerat felis. Nam eget pulvinar sem. Sed dictum gravida lobortis. Phasellus ut pretium diam. Vestibulum vel velit magna, congue sollicitudin orci. Donec quis mauris at ante volutpat ornare. Nulla metus enim, fringilla at eleifend a, pulvinar a turpis. Sed ut laoreet libero. Ut ipsum felis, varius eget pharetra et, mattis vitae augue. Aliquam erat volutpat. Quisque viverra turpis ut lorem gravida accumsan. Integer est risus, aliquam eget convallis id, malesuada vitae nunc. Ut eu ipsum velit, eget semper dui. </p>",
                                                                  "<p>Integer commodo dui id nulla accumsan ullamcorper. Donec eu urna id lorem venenatis vestibulum. Donec nec nisl dolor. Nulla porta condimentum lacus eu adipiscing. Aliquam nec tellus eu lectus ultrices consequat et nec turpis. Suspendisse vehicula porta urna, ac lobortis nisl viverra at. Curabitur ac velit nibh. Mauris molestie, nibh quis vestibulum fringilla, arcu eros hendrerit mi, id tempor odio lacus in quam. Mauris tristique urna eget est condimentum mattis. Sed nec lacus massa, ut dignissim elit. Vivamus augue libero, varius dictum pretium quis, auctor eget urna. Donec semper luctus dolor, at dapibus nunc fermentum a. </p><p>Suspendisse laoreet, nulla vitae volutpat commodo, nulla nunc porta risus, eget laoreet nunc augue in felis. Quisque sed felis felis, a dictum felis. Nullam vulputate rhoncus odio, vitae tincidunt nisl vehicula eget. Donec porttitor ante orci, nec luctus elit. Vivamus massa augue, consectetur in tempus sit amet, rhoncus tristique neque. Nam elit nibh, euismod auctor tristique ut, tincidunt sed nibh. Duis tempor, dui sit amet condimentum ullamcorper, eros risus interdum nulla, ut facilisis sapien neque nec urna. Suspendisse urna lorem, rutrum ac varius vel, tempor eget risus. Suspendisse potenti. Etiam tempus gravida erat, ut commodo leo vulputate non. Praesent et risus nisl. Mauris pharetra pellentesque enim, non pulvinar tortor eleifend congue.</p>" };

                        //Enter the dummy data
                        for (int i = 1; i <= servicesList.ItemCount; i++)
                        {
                            SPListItem item = servicesList.GetItemById(i);
                            item["DetailedDescription"] = DETAILED_DESCRIPTION_SERVICE[i - 1];
                            item.Update();
                        }

                        servicesList.Update();
                    }
                }

                #endregion

                web.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }