Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="properties"></param>
        private void DefaultNavigation(SPWebEventProperties properties)
        {
            int level;

            try
            {
                using (SPSite site = new SPSite(properties.Web.Site.ID))
                {
                    using (SPWeb web = site.AllWebs[properties.WebId])
                    {
                        PublishingSite pubsite = new PublishingSite(site);
                        PublishingWeb  pubWeb  = this.GetPublishingSiteFromWeb(web);
                        level = web.ServerRelativeUrl.Split('/').Length - 1;

                        switch (level)
                        {
                        case 0:
                            //Global Navigation Settings
                            pubWeb.Navigation.GlobalIncludeSubSites = true;
                            pubWeb.Navigation.GlobalIncludePages    = false;
                            //Current Navigation Settings
                            pubWeb.Navigation.CurrentIncludeSubSites = true;
                            pubWeb.Navigation.CurrentIncludePages    = false;
                            web.Update();
                            break;

                        case 1:
                            //Global Navigation Settings
                            pubWeb.Navigation.InheritGlobal         = true;
                            pubWeb.Navigation.GlobalIncludeSubSites = true;
                            pubWeb.Navigation.GlobalIncludePages    = false;
                            //Current Navigation Settings
                            pubWeb.Navigation.ShowSiblings           = true;
                            pubWeb.Navigation.CurrentIncludeSubSites = true;
                            pubWeb.Navigation.CurrentIncludePages    = false;
                            pubWeb.Update();
                            break;

                        default:
                            //Global Navigation Settings
                            pubWeb.Navigation.InheritGlobal         = true;
                            pubWeb.Navigation.GlobalIncludeSubSites = true;
                            pubWeb.Navigation.GlobalIncludePages    = false;
                            //Current Navigation Settings
                            pubWeb.Navigation.InheritCurrent         = true;
                            pubWeb.Navigation.CurrentIncludeSubSites = true;
                            pubWeb.Navigation.CurrentIncludePages    = false;
                            pubWeb.Update();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("WebProvisioning.cs - DefaultNavigation: " + ex.Message + " " + ex.StackTrace);
            }
        }
Пример #2
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;

            //if the web of type MLGSchool, set its MasterURL and Custom MasterURl
            if (string.Compare(web.WebTemplate, "MLGSchool", true) == 0)
            {
                try
                {
                    string masterURL = web.ServerRelativeUrl + masterPageName;
                    web.MasterUrl       = masterURL;
                    web.CustomMasterUrl = masterURL;
                    web.Update();
                }
                catch { }
            }
            else
            {
                //in case this is not a school site, check if it is a publishing web,
                //and if so set the MasterURL, and customMusterURl to inherit from the parent site.
                try
                {
                    if (PublishingWeb.IsPublishingWeb(web))
                    {
                        PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
                        pWeb.MasterUrl.SetInherit(true, true);
                        pWeb.CustomMasterUrl.SetInherit(true, true);
                        pWeb.Update();
                    }
                }
                catch { }
            }
        }
        // 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
        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);
        }
        void activation_OnPublishingWebActivated(SPWeb web, PublishingSite pubSite, PublishingWeb pubWeb)
        {
            // do stuff requiring publishing feature activation here
            pubWeb.Navigation.InheritGlobal         = true;
            pubWeb.Navigation.GlobalIncludePages    = false;
            pubWeb.Navigation.GlobalIncludeSubSites = true;

            SPFile homePageFile = web.GetFile("default.aspx");

            pubWeb.DefaultPage = homePageFile;
            pubWeb.Update();
        }
        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);
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
        {
            output = string.Empty;

            string url = Params["url"].Value.TrimEnd('/');

            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                {
                    if (Params["treeviewenabled"].UserTypedIn)
                    {
                        web.TreeViewEnabled = bool.Parse(Params["treeviewenabled"].Value);
                    }

                    if (Params["quicklaunchenabled"].UserTypedIn)
                    {
                        web.QuickLaunchEnabled = bool.Parse(Params["quicklaunchenabled"].Value);
                    }

#if MOSS
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);
                    if (Params["currentshowsubsites"].UserTypedIn)
                    {
                        pubweb.Navigation.CurrentIncludeSubSites = bool.Parse(Params["currentshowsubsites"].Value);
                    }
                    if (Params["globalshowsubsites"].UserTypedIn)
                    {
                        pubweb.Navigation.GlobalIncludeSubSites = bool.Parse(Params["globalshowsubsites"].Value);
                    }

                    if (Params["currentshowpages"].UserTypedIn)
                    {
                        pubweb.Navigation.CurrentIncludePages = bool.Parse(Params["currentshowpages"].Value);
                    }
                    if (Params["globalshowpages"].UserTypedIn)
                    {
                        pubweb.Navigation.GlobalIncludePages = bool.Parse(Params["globalshowpages"].Value);
                    }

                    OrderingMethod sortMethod = pubweb.Navigation.OrderingMethod;
                    if (Params["sortmethod"].UserTypedIn)
                    {
                        sortMethod = (OrderingMethod)Enum.Parse(typeof(OrderingMethod), Params["sortmethod"].Value, true);
                        pubweb.Navigation.OrderingMethod = sortMethod;
                    }

                    if (sortMethod != OrderingMethod.Manual)
                    {
                        if (Params["autosortmethod"].UserTypedIn)
                        {
                            pubweb.Navigation.AutomaticSortingMethod = (AutomaticSortingMethod)Enum.Parse(typeof(AutomaticSortingMethod), Params["autosortmethod"].Value, true);
                        }
                        if (Params["sortascending"].UserTypedIn)
                        {
                            pubweb.Navigation.SortAscending = bool.Parse(Params["sortascending"].Value);
                        }
                    }
                    else
                    {
                        if (Params["autosortmethod"].UserTypedIn)
                        {
                            Console.WriteLine("WARNING: parameter autosortmethod is incompatible with sortmethod {0}.  The parameter will be ignored.", sortMethod);
                        }
                        if (Params["sortascending"].UserTypedIn)
                        {
                            Console.WriteLine("WARNING: parameter sortascending is incompatible with sortmethod {0}.  The parameter will be ignored.", sortMethod);
                        }
                    }

                    if (Params["inheritglobalnav"].UserTypedIn)
                    {
                        pubweb.Navigation.InheritGlobal = bool.Parse(Params["inheritglobalnav"].Value);
                    }

                    if (Params["currentnav"].UserTypedIn)
                    {
                        CurrentNavSettingsEnum currentNav = (CurrentNavSettingsEnum)Enum.Parse(typeof(CurrentNavSettingsEnum), Params["currentnav"].Value, true);
                        if (currentNav == CurrentNavSettingsEnum.InheritParent)
                        {
                            pubweb.Navigation.InheritCurrent = true;
                            pubweb.Navigation.ShowSiblings   = false;
                        }
                        else if (currentNav == CurrentNavSettingsEnum.CurrentSiteAndSiblings)
                        {
                            pubweb.Navigation.InheritCurrent = false;
                            pubweb.Navigation.ShowSiblings   = true;
                        }
                        else if (currentNav == CurrentNavSettingsEnum.CurrentSiteOnly)
                        {
                            pubweb.Navigation.InheritCurrent = false;
                            pubweb.Navigation.ShowSiblings   = false;
                        }
                    }

                    pubweb.Update();
#else
                    web.Update();
#endif
                }

            return((int)ErrorCodes.NoError);
        }
 public void DefineDefaultHome(SPWeb web, PublishingSite pubSite, PublishingWeb pubWeb)
 {
     pubWeb.DefaultPage = web.GetFile("default.aspx");
     pubWeb.Update();
 }
Пример #9
0
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            output = string.Empty;



            SPBinaryParameterValidator.Validate("template", Params["template"].Value, "allowalltemplates",
                                                (Params["allowalltemplates"].UserTypedIn ? "true" : Params["allowalltemplates"].Value));

            string url              = Params["url"].Value.TrimEnd('/');
            string templateName     = Params["template"].Value;
            bool   resetAllSubsites = Params["resetallsubsites"].UserTypedIn;

            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                {
                    uint lcid           = web.Language;
                    bool localeProvided = Params["lcid"].UserTypedIn;
                    if (localeProvided)
                    {
                        lcid = uint.Parse(Params["lcid"].Value);
                    }
                    bool exists = false;

#if MOSS
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);

                    if (Params["allowalltemplates"].UserTypedIn)
                    {
                        pubweb.AllowAllWebTemplates(resetAllSubsites);
                        pubweb.Update();
                        return((int)ErrorCodes.NoError);
                    }
                    SPWebTemplateCollection existingLanguageNeutralTemplatesCollection  = pubweb.GetAvailableCrossLanguageWebTemplates();
                    SPWebTemplateCollection existingLanguageSpecificTemplatesCollection = pubweb.GetAvailableWebTemplates(lcid);
#else
                    if (Params["allowalltemplates"].UserTypedIn)
                    {
                        web.AllowAllWebTemplates();
                        web.Update();
                        return((int)ErrorCodes.NoError);
                    }
                    SPWebTemplateCollection existingLanguageNeutralTemplatesCollection  = web.GetAvailableCrossLanguageWebTemplates();
                    SPWebTemplateCollection existingLanguageSpecificTemplatesCollection = web.GetAvailableWebTemplates(lcid);
#endif


                    Collection <SPWebTemplate> newLanguageNeutralTemplatesCollection  = new Collection <SPWebTemplate>();
                    Collection <SPWebTemplate> newLanguageSpecificTemplatesCollection = new Collection <SPWebTemplate>();

                    foreach (SPWebTemplate existingTemplate in existingLanguageNeutralTemplatesCollection)
                    {
                        if (existingTemplate.Name == templateName && !localeProvided)
                        {
                            exists = true;
                            continue;
                        }
                        newLanguageNeutralTemplatesCollection.Add(existingTemplate);
                    }
                    foreach (SPWebTemplate existingTemplate in existingLanguageSpecificTemplatesCollection)
                    {
                        if (existingTemplate.Name == templateName && localeProvided)
                        {
                            exists = true;
                            continue;
                        }
                        newLanguageSpecificTemplatesCollection.Add(existingTemplate);
                    }


                    if (!exists)
                    {
                        output = "Template is not assigned.";
                        return((int)ErrorCodes.GeneralError);
                    }

                    if (newLanguageSpecificTemplatesCollection.Count == 0 && newLanguageNeutralTemplatesCollection.Count == 0)
                    {
                        output = "There must be at least one template available.";
                        return((int)ErrorCodes.GeneralError);
                    }
#if MOSS
                    pubweb.SetAvailableCrossLanguageWebTemplates(newLanguageNeutralTemplatesCollection, resetAllSubsites);
                    pubweb.SetAvailableWebTemplates(newLanguageSpecificTemplatesCollection, lcid, resetAllSubsites);
#else
                    web.SetAvailableCrossLanguageWebTemplates(newLanguageNeutralTemplatesCollection);
                    web.SetAvailableWebTemplates(newLanguageSpecificTemplatesCollection, lcid);
#endif
                }
            }

            return((int)ErrorCodes.NoError);
        }
Пример #10
0
        public static SPWebCollection removePageLayoutFromWeb(SPWeb oWeb, string pageLayoutToRemove)
        {
            PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(oWeb);

            Console.Write("\n Doing " + oWeb.Url);

            if (!pWeb.IsInheritingAvailablePageLayouts)
            {
                Console.Write("\n  Does not inherit. Searching...");

                List <PageLayout> myArray = new List <PageLayout>();


                var availablePageLayouts = pWeb.GetAvailablePageLayouts();
                Console.Write("\n  " + availablePageLayouts.Length.ToString() + " Page Layouts assoiciated with web.");
                if (availablePageLayouts.Length > 0)
                {
                    for (int i = 1; i < availablePageLayouts.Length; i++)
                    {
                        Console.Out.Flush();
                        string strapl = availablePageLayouts[i].Name;

                        if (strapl.Length == 0)
                        {
                            Console.Write("\nPage Layout without filename. Skipping " + availablePageLayouts[i].Title);
                        }
                        else
                        {
                            Console.Write("\n   Comparing " + strapl + " with " + pageLayoutToRemove);

                            if (strapl.CompareTo(pageLayoutToRemove) == 0)
                            {
                                var strrh = availablePageLayouts[i].Title;
                                Console.Write("\n   Removing page" + strapl + ". Press Enter to continue.");
                                Console.ReadLine();
                            }
                            else
                            {
                                Console.Write("\n   Keeping page" + strapl);
                                myArray.Add(availablePageLayouts[i]);
                            }
                        }
                    }

                    if (myArray.Count > 0)
                    {
                        Console.Write("\n  Updating Web");

                        pWeb.SetAvailablePageLayouts(myArray.ToArray(), false);
                        pWeb.Update();
                    }
                    else
                    {
                        Console.Write("\n  No pagelayouts to set. Skipping update. (At least one PageLayout must be left to do update).");
                    }
                }
            }
            else
            {
                Console.Write("\n  Inherits. Skipping.");
            }
            Console.Write("\n");
            return(oWeb.Webs);
        }
Пример #11
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());
            }
        }
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            output = string.Empty;



            SPBinaryParameterValidator.Validate("template", Params["template"].Value, "allowalltemplates",
                                                (Params["allowalltemplates"].UserTypedIn ? "true" : Params["allowalltemplates"].Value));

            string url              = Params["url"].Value.TrimEnd('/');
            string templateName     = Params["template"].Value;
            bool   resetAllSubsites = Params["resetallsubsites"].UserTypedIn;

            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                {
                    uint lcid = web.Language;
                    if (!string.IsNullOrEmpty(keyValues["lcid"]))
                    {
                        lcid = uint.Parse(keyValues["lcid"]);
                    }
                    bool localeProvided = keyValues.ContainsKey("lcid");

#if MOSS
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);

                    if (Params["allowalltemplates"].UserTypedIn)
                    {
                        pubweb.AllowAllWebTemplates(resetAllSubsites);
                        pubweb.Update();
                        return((int)ErrorCodes.NoError);
                    }
#else
                    if (Params["allowalltemplates"].UserTypedIn)
                    {
                        web.AllowAllWebTemplates();
                        web.Update();
                        return((int)ErrorCodes.NoError);
                    }
#endif
                    SPWebTemplateCollection templateColl;
                    if (localeProvided)
                    {
                        templateColl = web.GetAvailableWebTemplates(lcid);
                    }
                    else
                    {
                        templateColl = web.GetAvailableCrossLanguageWebTemplates();
                    }

                    bool exists;
                    try
                    {
                        exists = (templateColl[templateName] != null);
                    }
                    catch (ArgumentException)
                    {
                        exists = false;
                    }
                    if (exists && !web.AllWebTemplatesAllowed)
                    {
                        output = "Template is already installed.";
                        return((int)ErrorCodes.GeneralError);
                    }

                    Collection <SPWebTemplate> list = new Collection <SPWebTemplate>();
                    if (!web.AllWebTemplatesAllowed)
                    {
                        foreach (SPWebTemplate existingTemplate in templateColl)
                        {
                            list.Add(existingTemplate);
                        }
                    }
                    SPWebTemplate newTemplate = GetWebTemplate(site, lcid, templateName);
                    if (newTemplate == null)
                    {
                        output = "Template not found.";
                        return((int)ErrorCodes.GeneralError);
                    }
                    else
                    {
                        list.Add(newTemplate);
                    }

#if MOSS
                    if (!localeProvided)
                    {
                        pubweb.SetAvailableCrossLanguageWebTemplates(list, resetAllSubsites);
                    }
                    else
                    {
                        pubweb.SetAvailableWebTemplates(list, lcid, resetAllSubsites);
                    }
#else
                    if (!localeProvided)
                    {
                        web.SetAvailableCrossLanguageWebTemplates(list);
                    }
                    else
                    {
                        web.SetAvailableWebTemplates(list, lcid);
                    }
#endif
                }
            }

            return((int)ErrorCodes.NoError);
        }
Пример #13
0
        private void DefaultPageLayoutProcess(SPWebEventProperties properties)
        {
            PageLayout _pageLayout;

            try
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        PublishingSite pubSiteCollection = new PublishingSite(site);
                        PublishingWeb  publishingWeb     = PublishingWeb.GetPublishingWeb(properties.Web);

                        //check if pagelayout to be defaulted already exists in AvailablePageLayouts
                        _pageLayout = (from _pl in publishingWeb.GetAvailablePageLayouts()
                                       where _pl.Name == defaultPageLayout
                                       select _pl).FirstOrDefault();

                        //if exists
                        if (_pageLayout != null)
                        {
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);
                            publishingWeb.Update();
                        }
                        else  //if does not exist
                        {
                            //get all AvailablePageLayouts
                            PageLayout[] _allpageLayout = publishingWeb.GetAvailablePageLayouts();
                            PageLayout[] plarray        = new PageLayout[_allpageLayout.Length + 1];
                            int          ipl            = -1;
                            //transfer existing pagelayouts in AvailablePageLayouts to PageLayout[]
                            foreach (PageLayout _itempl in _allpageLayout)
                            {
                                ipl++;
                                plarray[ipl] = _itempl;
                            }

                            //PageLayout to be defaulted to
                            _pageLayout = pubSiteCollection.PageLayouts["/_catalogs/masterpage/" + defaultPageLayout];
                            ipl++;
                            //add to the PageLayout array
                            plarray[ipl] = _pageLayout;
                            //reset AvailablePageLayouts
                            publishingWeb.SetAvailablePageLayouts(plarray, true);
                            publishingWeb.Update();
                            //set DefaultPageLayout
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);

                            publishingWeb.Update();
                            web.Update();
                        }

                        //Swap the page layout of the default.aspx page
                        SwapPageLayout(publishingWeb, _pageLayout, web.Site.RootWeb.ContentTypes[_pageLayout.AssociatedContentType.Id]);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("WebProvisioning.cs - DefaultPageLayoutProcess: " + ex.Message + " " + ex.StackTrace);
            }
        }
        /// <summary>
        /// Sets the navigation.
        /// </summary>
        /// <param name="web">The web site.</param>
        /// <param name="xmlDoc">The XML doc containing the navigation nodes.</param>
        /// <param name="deleteExistingGlobal">if set to <c>true</c> [delete existing global nodes].</param>
        /// <param name="deleteExistingCurrent">if set to <c>true</c> [delete existing current nodes].</param>
        public static void SetNavigation(SPWeb web, XmlDocument xmlDoc, bool deleteExistingGlobal, bool deleteExistingCurrent, bool includeChildren)
        {
            PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);

            AutoAddSubSites(web, xmlDoc);
            AutoAddSiteCollectionUrl(web.Site, xmlDoc);
            AutoAddWebUrl(web, xmlDoc);

            XmlElement webElement = xmlDoc.SelectSingleNode("//Web[translate(@serverRelativeUrl, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='" + web.ServerRelativeUrl.ToLower() + "']") as XmlElement;

            if (webElement == null)
            {
                throw new Exception("Cannot find Web with Server Relative URL \"" + web.ServerRelativeUrl + "\".");
            }

            XmlElement globalNode  = webElement.SelectSingleNode("./Navigation/Global") as XmlElement;
            XmlElement currentNode = webElement.SelectSingleNode("./Navigation/Current") as XmlElement;


            // First need to set whether or not we show sub-sites and pages
            bool globalShowSubSites  = pubweb.Navigation.GlobalIncludeSubSites;
            bool globalShowPages     = pubweb.Navigation.GlobalIncludePages;
            bool currentShowSubSites = pubweb.Navigation.CurrentIncludeSubSites;
            bool currentShowPages    = pubweb.Navigation.CurrentIncludePages;

            if (globalNode != null)
            {
                globalShowSubSites = bool.Parse(globalNode.GetAttribute("IncludeSubSites"));
                globalShowPages    = bool.Parse(globalNode.GetAttribute("IncludePages"));;

                pubweb.Navigation.GlobalIncludeSubSites = globalShowSubSites;
                pubweb.Navigation.GlobalIncludePages    = globalShowPages;
            }
            if (currentNode != null)
            {
                currentShowSubSites = bool.Parse(currentNode.GetAttribute("IncludeSubSites"));
                currentShowPages    = bool.Parse(currentNode.GetAttribute("IncludePages"));;

                pubweb.Navigation.CurrentIncludeSubSites = currentShowSubSites;
                pubweb.Navigation.CurrentIncludePages    = currentShowPages;
            }
            pubweb.Update();

            List <SPNavigationNode> existingGlobalNodes  = new List <SPNavigationNode>();
            List <SPNavigationNode> existingCurrentNodes = new List <SPNavigationNode>();

            // We can't delete the navigation items until we've added the new ones so store the existing
            // ones for later deletion (note that we don't have to store all of them - just the top level).
            // I have no idea why this is the case - but when I tried to clear everything out first I got
            // all kinds of funky errors that just made no sense to me - this works so....
            foreach (SPNavigationNode node in pubweb.Navigation.GlobalNavigationNodes)
            {
                existingGlobalNodes.Add(node);
            }
            foreach (SPNavigationNode node in pubweb.Navigation.CurrentNavigationNodes)
            {
                existingCurrentNodes.Add(node);
            }

            XmlNodeList newGlobalNodes = null;

            if (globalNode != null)
            {
                newGlobalNodes = globalNode.SelectNodes("./Node");
            }

            XmlNodeList newCurrentNodes = null;

            if (currentNode != null)
            {
                newCurrentNodes = currentNode.SelectNodes("./Node");
            }

            if (newGlobalNodes != null && newGlobalNodes.Count > 0)
            {
                pubweb.Navigation.InheritGlobal = false;
                pubweb.Update();
            }
            if (newCurrentNodes != null && newCurrentNodes.Count > 0)
            {
                pubweb.Navigation.InheritCurrent = false;
                pubweb.Update();
            }
            pubweb = PublishingWeb.GetPublishingWeb(web);

            // If we've got global or current nodes in the xml then the intent is to reset those elements.
            // If we've also specified to delete any existing elements then we need to first hide all the
            // sub-sites and pages (you can't delete them because they don't exist as a node).  Note that
            // we are only doing this if showSubSites is true - if it's false we don't see them so no point
            // in hiding them.  Any non-sub-site or non-page will be deleted after we've added the new nodes.
            foreach (SPWeb tempWeb in pubweb.Web.Webs)
            {
                try
                {
                    if (newGlobalNodes != null && newGlobalNodes.Count > 0 && deleteExistingGlobal && globalShowSubSites)
                    {
                        // Initialize the sub-sites (forces the provided XML to specify whether any should be visible)
                        pubweb.Navigation.ExcludeFromNavigation(true, tempWeb.ID);
                    }
                    if (newCurrentNodes != null && newCurrentNodes.Count > 0 && deleteExistingCurrent && currentShowSubSites)
                    {
                        pubweb.Navigation.ExcludeFromNavigation(false, tempWeb.ID);
                    }
                }
                finally
                {
                    tempWeb.Dispose();
                }
            }
            pubweb.Update();

            // Now we need to add all the global nodes (if any - if the collection is empty the following will just return and do nothing)
            AddNodes(pubweb, true, pubweb.Navigation.GlobalNavigationNodes, newGlobalNodes);
            // Update the web as the above may have made modifications
            pubweb.Update();

            // Now delete all the previously existing global nodes.
            if (newGlobalNodes != null && newGlobalNodes.Count > 0 && deleteExistingGlobal)
            {
                foreach (SPNavigationNode node in existingGlobalNodes)
                {
                    node.Delete();
                }
            }

            // Now we need to add all the current nodes (if any)
            AddNodes(pubweb, false, pubweb.Navigation.CurrentNavigationNodes, newCurrentNodes);
            // Update the web as the above may have made modifications
            pubweb.Update();

            // Now delete all the previously existing current nodes.
            if (newCurrentNodes != null && newCurrentNodes.Count > 0 && deleteExistingCurrent)
            {
                foreach (SPNavigationNode node in existingCurrentNodes)
                {
                    node.Delete();
                }
            }

            if (includeChildren)
            {
                foreach (SPWeb childWeb in web.Webs)
                {
                    SetNavigation(childWeb, xmlDoc, deleteExistingGlobal, deleteExistingCurrent, true);
                }
            }
        }