Beispiel #1
0
        private static SPWeb AddSite(this SPWeb parentSite, string url, string name, string templateName)
        {
            if (string.IsNullOrEmpty(url))
            {
                url = name.Simplyfied();
            }
            SPWeb newSite            = null;
            bool  allowUnsafeupdates = parentSite.AllowUnsafeUpdates;

            parentSite.AllowUnsafeUpdates = true;
            try
            {
                //Create the new site from the template

                SPWebTemplate template = GetTemplate(templateName, parentSite.Site);
                if (template != null)
                {
                    newSite = parentSite.Webs.Add(url, name, string.Empty, 1033, template, false, false);
                    newSite.Update();
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message + ex.StackTrace, AIAPortalFeatures.Infrastructure);
            }
            finally
            {
                parentSite.AllowUnsafeUpdates = allowUnsafeupdates;
            }
            return(newSite);
        }
        private static Dictionary <string, string> GetWebTemplateProperties(ISharePointCommandContext context,
                                                                            WebTemplateInfo nodeInfo)
        {
            SPWebTemplate template = context.Web.GetAvailableWebTemplates((uint)context.Web.Locale.LCID, true)[nodeInfo.Name];

            return(SharePointCommandServices.GetProperties(template));
        }
        public SPWebTemplateInstance Construct(SPWebTemplate template)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            return(new SPWebTemplateInstance(this.InstancePrototype, template));
        }
        internal void ApplayTemplate(SPWebTemplate template)
        {
            if (SiteCollection == null)
            {
                return;
            }
            SPWeb _root = SiteCollection.RootWeb;

            _root.ApplyWebTemplate(template);
        }
        private SPWebTemplate LookupTemplate(SPSite site, string templateName)
        {
            SPWebTemplate template = LookupTemplateIDInGallery(site, templateName);

            if (template != null)
            {
                return(template);
            }
            else
            {
                return(LookupTemplateIDInDefinitions(site, templateName));
            }
        }
Beispiel #6
0
        protected virtual SPWebTemplate LookupCustomWebTemplate(SPWeb web, WebDefinition definition)
        {
            // lookup on the current web?
            SPWebTemplate result = LookupCustomWebTemplateFromWeb(web, definition);

            // lookup on the site?
            if (result == null)
            {
                result = LookupCustomWebTemplateFromWeb(web.Site.RootWeb, definition);
            }

            return(result);
        }
Beispiel #7
0
 private void x_OKButton_Click(object sender, RoutedEventArgs e)
 {
     if (x_TemplatesListBox.SelectedIndex != -1)
     {
         WebTemplate       = TemplatesCollection[x_TemplatesListBox.SelectedIndex];
         this.DialogResult = true;
     }
     else
     {
         WebTemplate       = null;
         this.DialogResult = false;
     }
     this.Close();
 }
Beispiel #8
0
        private static SPWebTemplate GetTemplate(string solutionName, SPSite siteCollection)
        {
            SPWebTemplate           templateName = null;
            SPWebTemplateCollection coll         = siteCollection.GetWebTemplates(1033);

            foreach (SPWebTemplate template in coll)
            {
                if (template.Name.Contains(solutionName))
                {
                    templateName = template;
                }
            }

            return(templateName);
        }
Beispiel #9
0
 private static void PopulateTemplate(Location loc, SPWeb web)
 {
     loc.Template.Name  = "?";
     loc.Template.Title = "?";
     try
     {
         SPWebTemplateCollection templateCollection = web.Site.GetWebTemplates(web.Site.RootWeb.RegionalSettings.LocaleId);
         string templateName = web.WebTemplate + "#" + web.Configuration.ToString();
         loc.Template.Name = templateName;
         SPWebTemplate template = FindWebTemplate(templateCollection, templateName);
         loc.Template.Title = template.Title;
     }
     catch
     {
     }
 }
Beispiel #10
0
        public static void CreateSiteBySiteTemplate(string url, string webName, string webDescription, string templateName)
        {
            string loginName = GetLoginAccountWithDomain;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site            = new SPSite(SPContext.Current.Site.Url);
                SPWeb web              = site.OpenWeb();
                web.AllowUnsafeUpdates = true;
                //= "subsite1";//创建后的站点是:http://moss:5001/subsite1
                if (!web.Webs[webName].Exists)
                {
                    //1.根据网站模版,创建网站
                    //= "SubSiteTemplate";//网站模版定义
                    SPWebTemplate CustomTemplate           = null;
                    SPWebTemplateCollection subWebTemplate = web.GetAvailableWebTemplates((uint)web.Locale.LCID);
                    foreach (SPWebTemplate template in subWebTemplate)
                    {
                        if (template.Title == templateName)
                        {
                            CustomTemplate = template;
                            break;
                        }
                    }
                    SPWeb NewWeb = web.Webs.Add(url, webName, webDescription, (uint)2052, CustomTemplate, true, false);
                    NewWeb.AllowUnsafeUpdates = true;
                    //2.给创建好的网站分配权限,
                    //2.1断开网站权限
                    NewWeb.BreakRoleInheritance(false);
                    //2.2添加网站的"完全控制"权限.
                    SPUser user = web.EnsureUser(loginName);
                    SPRoleAssignment MyRoleAssignment = new SPRoleAssignment(user);
                    MyRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
                    NewWeb.RoleAssignments.Add(MyRoleAssignment);
                    NewWeb.Update();
                }
                web.Update();
                web.Dispose();
            });
        }
Beispiel #11
0
        /// <summary>
        /// Returns a new SPWeb object representing the case web.  Make sure you dispose this object.
        /// </summary>
        /// <param name="rootWeb"></param>
        /// <param name="uniqueUrl"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        private SPWeb CreateCaseWeb(SPWeb rootWeb, string uniqueUrl, string title, string description)
        {
            try
            {
                SPWebTemplate spWebTemplate = rootWeb.Site.GetWebTemplates(1033)["SusDebCaseSiteDefinition#0"];
                SPWeb         caseWeb       = rootWeb.Webs.Add(uniqueUrl, title, description, 1033, spWebTemplate, true, false); // Disposed outside of this scope
                caseWeb.AssociatedOwnerGroup  = eCaseGroups.GetOwners(caseWeb);
                caseWeb.AssociatedMemberGroup = eCaseGroups.GetParticipants(caseWeb);
                caseWeb.Update(); // Push changes to the CaseWeb to the DB

                caseWeb.TryGrantPermission(caseWeb.AssociatedOwnerGroup, SPRoleType.Administrator);
                caseWeb.TryGrantPermission(caseWeb.AssociatedMemberGroup, SPRoleType.Contributor);
                caseWeb.TryGrantPermission(caseWeb.AssociatedVisitorGroup, SPRoleType.Reader);

                Logger.Instance.Info(string.Format("Created new Case Web at {0}", uniqueUrl), DiagnosticsCategories.eCaseSite);

                return(caseWeb);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// Gets the web template.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="lcid">The lcid.</param>
        /// <param name="webTemplateName">Name of the web template.</param>
        /// <returns></returns>
        internal static SPWebTemplate GetWebTemplate(SPSite site, uint lcid, string webTemplateName)
        {
            SPWebTemplateCollection webTemplates       = site.GetWebTemplates(lcid);
            SPWebTemplateCollection customWebTemplates = site.GetCustomWebTemplates(lcid);
            SPWebTemplate           template           = null;

            try
            {
                template = webTemplates[webTemplateName];
            }
            catch (ArgumentException)
            {
                try
                {
                    return(customWebTemplates[webTemplateName]);
                }
                catch (ArgumentException)
                {
                    return(template);
                }
            }
            return(template);
        }
Beispiel #13
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                using (SPSite site = new SPSite(WebURL, __Context.Web.CurrentUser.UserToken))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string[] templateIDs = TemplateIDs.Split(';');
                        Collection <SPWebTemplate> templateList = new Collection <SPWebTemplate>();
                        foreach (string templateid in templateIDs)
                        {
                            SPWebTemplate template = LookupTemplate(site, templateid);
                            if (template != null)
                            {
                                templateList.Add(template);
                            }
                            else
                            {
                                throw new Exception("Could not locate template, " + templateid + ", in site, " + WebURL + ".");
                            }
                        }
                        web.SetAvailableWebTemplates(templateList, LCID);
                        web.Update();

                        string message = "Web: " + WebURL + " templates restricted to: " + TemplateIDs;
                        WorkflowHistoryLogger.LogMessage(executionContext, SPWorkflowHistoryEventType.None, "Complete", UserID, message);
                    }
                }
            }
            catch (Exception ex)
            {
                WorkflowHistoryLogger.LogError(executionContext, UserID, ex);
                return(ActivityExecutionStatus.Faulting);
            }
            return(ActivityExecutionStatus.Closed);
        }
Beispiel #14
0
 private void InstallationMachineViewModel_OnSPWebTeplateSelection(object sender, SPWebTeplateEventArgs e)
 {
     try
     {
         ValidationListBox.AddMessage((string)e.UserState);
         SPWebTemplate _selectedTemplate = null;
         foreach (SPWebTemplate _tmplt in e.WebTemplates)
         {
             if (!m_MainWindowStateMachine.InstallationDescription.SiteTemplate.Contains(_tmplt.Name))
             {
                 continue;
             }
             _selectedTemplate = _tmplt;
             break;
         }
         if (_selectedTemplate == null)
         {
             Controls.WebTemplateDialog _dialog = new WebTemplateDialog();
             _dialog.TemplatesCollection = e.WebTemplates;
             _dialog.ShowDialog();
             if (!_dialog.DialogResult.GetValueOrDefault(false))
             {
                 Tracing.TraceEvent.TraceWarning(97, "OnSPWebTeplateSelection", "Canceled template selection");
                 return;
             }
             _selectedTemplate = _dialog.WebTemplate;
         }
         m_MainWindowStateMachine.InstallationDescription.SiteTemplate  = _selectedTemplate.Name;
         m_MainWindowStateMachine.InstallationDescription.SPWebTemplate = _selectedTemplate;
         string _msg = String.Format("New template selected: {0}", Controls.WebTemplateDialog.SPWebTemplateToString(_selectedTemplate));
         Tracing.TraceEvent.TraceInformation(97, "OnSPWebTeplateSelection", _msg);
     }
     finally
     {
         e.SPWebTeplateSelected();
     }
 }
 public TemplateHolder(SPWebTemplate template)
 {
     this.Template = template;
 }
Beispiel #16
0
        /// <summary>
        /// Create department sub site from site template
        /// </summary>
        /// <param name="currentWeb">SharePoint Current web</param>
        /// <param name="departmentItem">Department List Item</param>
        public void CreateDepartmentSite(Guid siteId, Guid webId, SPListItem departmentItem)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb currentWeb = site.OpenWeb(webId))
                    {
                        var webTemplates          = currentWeb.Site.RootWeb.GetAvailableWebTemplates(1033);
                        SPWebTemplate webTemplate = null;

                        for (var i = 0; i < webTemplates.Count; i++)
                        {
                            var webTemplateSearchName = webTemplates[i].Title;

                            if (!webTemplateSearchName.Contains(DepartmentTemplateName))
                            {
                                continue;
                            }

                            webTemplate = webTemplates[i];
                            break;
                        }

                        if (webTemplate == null)
                        {
                            return;
                        }
                        var department = ParseToEntity(departmentItem);
                        // check web existed or not
                        var webExisted = currentWeb.Webs.FirstOrDefault(w => w.Title == department.Name);
                        if (webExisted != null)
                        {
                            CreateUpdateDepartmentGroup(webExisted, currentWeb, department.Name);
                            return;
                        }

                        // Default language English
                        var newSite = currentWeb.Webs.Add(department.Code, department.Name, department.Name, Convert.ToUInt16(1033), webTemplate, false, false);

                        newSite.AllowUnsafeUpdates   = true;
                        newSite.Navigation.UseShared = false;

                        //Set default home pages
                        var rootFolder         = newSite.RootFolder;
                        rootFolder.WelcomePage = "SitePages/Home.aspx";
                        rootFolder.Update();
                        //SPHelper.ActiveInstalledLanguage(newSite);

                        // Update language resource for Site title
                        CreateUpdateDepartmentGroup(newSite, currentWeb, department.Name);
                        SPHelper.ActiveInstalledLanguage(newSite);
                        foreach (var culture in newSite.SupportedUICultures)
                        {
                            switch (culture.LCID)
                            {
                            case 1066:
                                newSite.TitleResource.SetValueForUICulture(culture, department.VietnameseName);
                                break;

                            default:
                                newSite.TitleResource.SetValueForUICulture(culture, department.Name);
                                break;
                            }
                        }
                        newSite.Update();
                    }
                }
            });
        }
 public SPWebTemplateInstance(ObjectInstance prototype, SPWebTemplate template)
     : this(prototype)
 {
     this.m_webTemplate = template;
 }
Beispiel #18
0
        internal static string SPWebTemplateToString(SPWebTemplate template)
        {
            string _patter = "Title:{0}, Name:{1}, Multilingual:{2}, Lcid:{3}, Root:{4}, Category:{5} - {6}";

            return(String.Format(_patter, template.Title, template.Name, template.SupportsMultilingualUI, template.Lcid, template.IsRootWebOnly, template.DisplayCategory, template.Description));
        }
        /// <summary>
        /// Creates an SPWeb object
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static void CreateSPWeb(SPListItem item, string managerUserName)
        {
            //Construct the Url, display name and language ID for the site
            string newWebUrl   = item.ID.ToString();
            string newWebTitle = null;

            if (item["Matter Number: Matter Name"] != null)
            {
                newWebTitle = item["Matter Number: Matter Name"].ToString();
            }
            else if (item["Matter Number: Account Name"] != null)
            {
                newWebTitle = item["Matter Number: Account Name"].ToString();
            }
            string newWebDescription = string.Empty;
            uint   newWebLcid        = item.Web.Language;

            //Get the ID of the web template for Matter sites
            SPWebTemplateCollection templateCollection = item.Web.GetAvailableWebTemplates(item.Web.Language);
            SPWebTemplate           newWebTemplate     = null;

            foreach (SPWebTemplate currentTemplate in templateCollection)
            {
                if (currentTemplate.Title == "Matter Template")
                {
                    newWebTemplate = currentTemplate;
                }
            }

            //Create the new web using the Matter Template as a web template
            using (SPWeb newWeb = item.Web.Webs.Add(newWebUrl, newWebTitle, string.Empty, newWebLcid, newWebTemplate, true, false))
            {
                //Apply the same permissions that are on the list item to the subsite
                SPRoleAssignmentCollection newWebRoles = item.RoleAssignments;
                foreach (SPRoleAssignment currentRole in newWebRoles)
                {
                    newWeb.RoleAssignments.Add(currentRole);
                }
                newWeb.Update();

                //Create a matter summary object on the subsite
                SPListItem matterSummary = newWeb.Lists["Matter summary"].AddItem();
                matterSummary["Account Name"] = item["Matter Number: Account Name"];

                //Affiliate is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Affiliate"] != null)
                {
                    string   affiliatesConcat = item["Matter Number: Affiliate"].ToString();
                    string[] affiliates       = affiliatesConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(affiliates, matterSummary, "Affiliate");
                }

                matterSummary["Case Caption"]  = item["Matter Number: Case Caption"];
                matterSummary["Docket Number"] = item["Matter Number: Docket Number"];

                //Manager is a person/group field, must update with an actual SPUser object
                if (!string.IsNullOrEmpty(managerUserName))
                {
                    if (!managerUserName.StartsWith(@"i:0#.w|TRG"))
                    {
                        managerUserName = @"i:0#.w|TRG\" + managerUserName;
                    }
                    SPUser manager = null;
                    try
                    {
                        manager = item.Web.AllUsers[managerUserName];
                    }
                    catch (Exception ex)
                    {
                        manager = item.Web.EnsureUser(@"i:0#.w|TRG\Legacy");
                    }
                    matterSummary["Litigation Manager"] = manager;
                }

                //Litigation type is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Litigation Type"] != null)
                {
                    UpdateMMField(item["Matter Number: Litigation Type"].ToString(), matterSummary, "Litigation Type");
                }

                matterSummary["Matter Name"]   = item["Matter Number: Matter Name"];
                matterSummary["Matter Status"] = item["Matter Number: Matter Status"];

                //State filed is a managed metadata value column, can't update display value directly
                if (item["Matter Number: State Filed"] != null)
                {
                    UpdateMMField(item["Matter Number: State Filed"].ToString(), matterSummary, "State Filed");
                }

                //Venue is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Venue"] != null)
                {
                    UpdateMMField(item["Matter Number: Venue"].ToString(), matterSummary, "Venue");
                }

                //Work matter type is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Work/Matter Type"] != null)
                {
                    string   workmatterTypeConcat = item["Matter Number: Work/Matter Type"].ToString();
                    string[] workmatterTypes      = workmatterTypeConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(workmatterTypes, matterSummary, "Work/Matter Type");
                }
                matterSummary.Update();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="webApplicationURL"></param>
        /// <param name="siteName"></param>
        /// <param name="siteTitle"></param>
        /// <param name="siteDesc"></param>
        /// <param name="siteLanguage"></param>
        /// <param name="templateName"></param>
        /// <param name="ownerLoginName"></param>
        /// <param name="ownerName"></param>
        /// <param name="ownerEmail"></param>
        /// <returns></returns>
        public bool CreateSiteCollection(
            String webApplicationURL,
            string siteName,
            string siteTitle,
            string siteDesc,
            int siteLanguage,
            string templateName,
            string ownerLoginName,
            string ownerName,
            string ownerEmail
            )
        {
            bool isSiteCreated = false;

            try
            {
                LoggingService.LogErrorInULS("RSG.Inside.SPSiteCol.ExternalService - CreateSiteCollection - Start");
                LoggingService.LogErrorInULS("SIte Info: " + "\nWebApplication URL: " + webApplicationURL +
                                             "\nSiteName: " + siteName +
                                             "\nSiteTitle: " + siteTitle +
                                             "\nSiteDesc: " + siteDesc +
                                             "\nSiteLanguage: " + siteLanguage +
                                             "\nTemplateName: " + templateName +
                                             "\nownerLoginName: " + ownerLoginName +
                                             "\nownerName: " + ownerName +
                                             "\nownerEmail: " + ownerEmail
                                             );

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite siteCollectionOuter = new SPSite(webApplicationURL))
                    {
                        SPWebApplication webApp = siteCollectionOuter.WebApplication;
                        LoggingService.LogErrorInULS("SiteCreationActivity :" + webApplicationURL + siteName + templateName + siteLanguage);

                        SPSiteCollection siteCollection = webApp.Sites;
                        UInt32 lang = Convert.ToUInt32(siteLanguage);
                        SPWebTemplateCollection myTemplates = siteCollectionOuter.RootWeb.GetAvailableWebTemplates(lang);
                        SPWebTemplate reqTemplate           = myTemplates[templateName];

                        if (reqTemplate != null)
                        {
                            using (SPSite site = siteCollection.Add("sites/" + siteName, siteTitle, siteDesc, lang, reqTemplate.Name, ownerLoginName, ownerName, ownerEmail))
                            {
                                isSiteCreated = true;
                                try
                                {
                                    site.Features.Add(new Guid("F6924D36-2FA8-4f0b-B16D-06B7250180FA"), true);
                                }
                                catch (Exception expub)
                                {
                                    LoggingService.LogErrorInULS("Publishing Feature Activation Issue" + expub.ToString());
                                }
                                try
                                {
                                    site.Features.Add(new Guid("c7c893fd-9cbe-4f40-ad1d-990f69978203"), true);
                                }
                                catch (Exception expub)
                                {
                                    LoggingService.LogErrorInULS("Site Provision Feature Activation Issue" + expub.ToString());
                                }
                            }
                        }
                    }
                });
                LoggingService.LogErrorInULS("RSG.Inside.SPSiteCol.ExternalService - CreateSiteCollection - End");
            }
            catch (Exception ex)
            {
                LoggingService.LogErrorInULS("RSG.Inside.SPSiteCol.ExternalService CreateSiteCollection Issue :" + ex.Message);
            }

            return(isSiteCreated);
        }
        private void bulkSiteCreation(bool onlyValidate)
        {
            //--Validate
            if (NewSiteOrList.ListOfNewSites == null || NewSiteOrList.ListOfNewSites.Count == 0)
            {
                AddToRtbLocal("The sites to create list is empty.\r\n", StyleType.bodyRed);
                return;
            }
            if (cboSiteTemplates.SelectedItem == null)
            {
                AddToRtbLocal("Please select a Site Template.\r\n", StyleType.bodyRed);
                return;
            }
            for (int i = 0; i < NewSiteOrList.ListOfNewSites.Count - 1; i++)
            {
                if (NewSiteOrList.ListOfNewSites[i].UrlName == NewSiteOrList.ListOfNewSites[i + 1].UrlName)
                {
                    AddToRtbLocal("The Site URL " + NewSiteOrList.ListOfNewSites[i].UrlName + " is listed twice.\r\n", StyleType.bodyRed);
                    return;
                }
            }

            int counter             = 0;
            int counterListToCreate = 0;

            try
            {
                FrmCancelRunning.ToggleEnabled(true);
                SPWeb parentWeb = Util.RetrieveWeb(txtTargetSite.Text, rtbSiteValidateMessage);
                if (parentWeb == null)
                {
                    return;
                }
                txtTargetSite.Text = parentWeb.Url;

                //--
                SPWebTemplate targetTemplate = ((TemplateHolder)cboSiteTemplates.SelectedItem).Template;
                AddToRtbLocal("Creating new SubSites beneath parent site " + parentWeb.Url + "\r\n", StyleType.bodySeaGreen);
                AddToRtbLocal("Using template: ", StyleType.bodySeaGreen); AddToRtbLocal(targetTemplate.Title + "\r\n", StyleType.bodyBlue);
                AddToRtbLocal("\r\n", StyleType.bodyBlack);
                Application.DoEvents();

                //--
                List <string> currentSiteUrlNames = new List <string>();
                currentSiteUrlNames.AddRange(parentWeb.Webs.Names);
                foreach (NewSiteOrList ns in NewSiteOrList.ListOfNewSites)
                {
                    if (GlobalVars.CancelRunning)
                    {
                        throw new Eh.CancelException();
                    }

                    counterListToCreate++;
                    AddToRtbLocal("#" + counterListToCreate + ") ", StyleType.bodyBlackBold);
                    SPWeb childWeb = null;
                    if (currentSiteUrlNames.Contains(ns.UrlName))
                    {
                        AddToRtbLocal("Subsite " + ns.UrlName + " already exists\r\n", StyleType.bodyBlue);
                        childWeb = parentWeb.Webs[ns.UrlName];
                    }
                    else
                    {
                        if (onlyValidate)
                        {
                            AddToRtbLocal("Subsite to be created: ", StyleType.bodyBlack);
                            AddToRtbLocal(ns.ToString() + "\r\n", StyleType.bodyBlue);
                        }
                        else
                        {
                            AddToRtbLocal("Creating subsite:" + ns.ToString(), StyleType.bodyBlack);
                            childWeb = parentWeb.Webs.Add(ns.UrlName, ns.Title, "", 1033, targetTemplate, false, false);
                            counter++;
                            AddToRtbLocal(" success\r\n", StyleType.bodySeaGreen);

                            //--
                            AddToRtbLocal("Applying same global navigation as parent\r\n", StyleType.bodyBlack);
                            childWeb.Navigation.UseShared = true;
                        }
                    }

                    SmartStepUtil.ScrollToBottom(rtbDisplay);
                    Application.DoEvents();
                }
            }
            catch (Eh.CancelException)
            {
                AddToRtbLocal("cancelled by user\r\n", StyleType.bodyRed);
            }
            catch (Exception ex)
            {
                AddToRtbLocal("error: " + ex.Message + "\r\n", StyleType.bodyRed);
            }
            finally
            {
                FrmCancelRunning.ToggleEnabled(false);
                string s = onlyValidate ? "to be " : "";
                AddToRtbLocal("DONE. Count of sites in new sites list: " + NewSiteOrList.ListOfNewSites.Count + ", sites " + s + "created: " + counter, StyleType.bodyDarkGray);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Creates the web.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="name">The name.</param>
        /// <param name="template">The template.</param>
        /// <param name="uniquePermissions"><c>true</c> to create a subsite that does not inherit permissions from another site; otherwise, false</param>
        /// <param name="alternativeIfExist">if set to <c>true</c> [alternative if exist].</param>
        /// <returns>The new</returns>
        public SPWeb CreateWeb(string url, string name, string template, bool uniquePermissions, bool alternativeIfExist)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("Web url can't be null or empty.");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Web name can't be null or empty.");
            }

            if (string.IsNullOrEmpty(template))
            {
                throw new ArgumentException("Template name can't be null or empty.");
            }

            string namedUrl = RemoveDiacritics((RemoveInvalidCharacters(name)));

            using (SPSite _site = new SPSite(url))
            {
                using (SPWeb web = _site.OpenWeb())
                {
                    SPWeb newWeb;

                    if (web == null)
                    {
                        throw new SPSException(string.Format("Can´t open parent web at '{0}'",
                                                             url));
                    }

                    Debug.WriteLine(string.Format("Trying create test web '{0}' - at '{1}/{2}'",
                                                  name,
                                                  url,
                                                  namedUrl));


                    // check if new site exist and lo
                    if (ExistUrl(web, namedUrl))
                    {
                        if (alternativeIfExist)
                        {
                            namedUrl = GetNewValidUrl(web, namedUrl);
                        }
                        else
                        {
                            throw new SPSException(string.Format("Unable to create web. Already exist at '{0}/{1}'", url, namedUrl));
                        }
                    }

                    SPWebTemplate webTemplate = GetCustomWebTemplate(template, _site, web);

                    #region Custom Template

                    if (webTemplate != null)
                    {
                        try
                        {
                            newWeb = web.Webs.Add(namedUrl,
                                                  name,
                                                  string.Empty,
                                                  (uint)web.Locale.LCID,
                                                  webTemplate,
                                                  uniquePermissions,
                                                  false);

                            Debug.WriteLine(string.Format("Created web '{0}' at '{1}'",
                                                          newWeb.Title,
                                                          newWeb.Url));


                            return(newWeb);
                        }
                        catch (SPException ex)
                        {
                            throw new SPSException(string.Format("Unable create web at '{0}' named '{1}/{2}'",
                                                                 url,
                                                                 name,
                                                                 namedUrl),
                                                   ex);
                        }
                    }

                    #endregion

                    // not a custom template, search here
                    webTemplate = GetWebTemplate(template, _site, web);

                    #region Web Template

                    if (webTemplate != null)
                    {
                        try
                        {
                            newWeb = web.Webs.Add(namedUrl,
                                                  name,
                                                  string.Empty,
                                                  (uint)web.Locale.LCID,
                                                  webTemplate,
                                                  uniquePermissions,
                                                  false);

                            Debug.WriteLine(string.Format("Created web '{0}' at '{1}'",
                                                          newWeb.Title,
                                                          newWeb.Url));
                            return(newWeb);
                        }
                        catch (Exception ex)
                        {
                            throw new SPSException(string.Format("Unable create web at '{0}' named '{1}/{2}'",
                                                                 url,
                                                                 name,
                                                                 namedUrl),
                                                   ex);
                        }
                    }

                    #endregion

                    throw new SPSException(string.Format("Template '{0}' not found.", template));
                }
            }
        }
        public override void Provision(SPWebProvisioningProperties props)
        {
            SPWeb  eCaseRootWeb  = props.Web;
            SPSite eCaseRootSite = eCaseRootWeb.Site;

            eCaseRootWeb.ApplyWebTemplate("SusDebRootWeb");

            #region Create & Configure the eCase FAST Search Site
            SPWebTemplate eCaseFastSrchCtrSiteDef = eCaseRootSite.GetWebTemplates(1033)["SusDebFastSearchSiteDef#0"];
            using (SPWeb eCaseFastSrchCtr = eCaseRootWeb.Webs.Add(ECASE_SRCH_CTR_URL, ECASE_SRCH_CTR_TITLE, ECASE_SRCH_CTR_DESC, 1033, eCaseFastSrchCtrSiteDef, false, false))
            {
                // Display Ribbon by default
                eCaseFastSrchCtr.AllProperties["__DisplayShowHideRibbonActionId"] = false.ToString();

                #region Configure Site Collection Search Center settings
                eCaseRootWeb.AllProperties["SRCH_ENH_FTR_URL"]         = eCaseFastSrchCtr.Url + "/pages";
                eCaseRootWeb.AllProperties["SRCH_SITE_DROPDOWN_MODE"]  = "ShowDD";
                eCaseRootWeb.AllProperties["SRCH_TRAGET_RESULTS_PAGE"] = eCaseFastSrchCtr.Url + "/pages/results.aspx";
                eCaseRootWeb.Update();
                #endregion

                #region Set MasterPage
                try
                {
                    // Get the masterpage
                    SPFile eCaseSrchMaster = eCaseRootWeb.GetFile(eCaseRootWeb.Url + "/_catalogs/masterpage/eCase_minimal.master");
                    // eCaseFastSrchCtr.MasterUrl = eCaseSrchMaster.ServerRelativeUrl; /* DO NOT APPLY TO SYSTEM PAGES */
                    eCaseFastSrchCtr.CustomMasterUrl = eCaseSrchMaster.ServerRelativeUrl;
                    eCaseFastSrchCtr.Update();
                }
                catch (Exception x)
                {
                    Logger.Instance.Error(string.Format("Failed to set master page in SusDeb FAST Search Center at {0}", eCaseFastSrchCtr.Url),
                                          x, DiagnosticsCategories.eCaseSearch);
                }
                #endregion

                #region Populate Search Tabs Lists
                try
                {
                    #region Create SearchResults Tabs List
                    Guid srchResultsGuid = eCaseFastSrchCtr.Lists.Add("Tabs in Search Results", "Use this list to store the tabs displayed in search results.",
                                                                      "SearchResults", "285dfda8-ae65-4ac1-8f6a-39ff7187bba9", 301, "100", SPListTemplate.QuickLaunchOptions.Off);
                    SPList     srchResultsList = eCaseFastSrchCtr.Lists[srchResultsGuid];
                    SPListItem resultsAspx     = srchResultsList.AddItem();
                    resultsAspx[eCaseConstants.FieldGuids.TABS_LIST_TAB_NAME] = "All Sites";
                    resultsAspx[eCaseConstants.FieldGuids.TABS_LIST_PAGE]     = "results.aspx";
                    resultsAspx[eCaseConstants.FieldGuids.TABS_LIST_TOOLTIP]  = "Click for results from All Sites";
                    resultsAspx.Update();
                    SPListItem peopleResultsAspx = srchResultsList.AddItem();
                    peopleResultsAspx[eCaseConstants.FieldGuids.TABS_LIST_TAB_NAME] = "People";
                    peopleResultsAspx[eCaseConstants.FieldGuids.TABS_LIST_PAGE]     = "peopleresults.aspx";
                    peopleResultsAspx[eCaseConstants.FieldGuids.TABS_LIST_TOOLTIP]  = "Click for people results";
                    peopleResultsAspx.Update();
                    #endregion

                    #region Create SearchCenter Tabs List
                    Guid srchCenterGuid = eCaseFastSrchCtr.Lists.Add("Tabs in Search Pages", "Use this list to store the tabs displayed in the default blank search pages.",
                                                                     "SearchCenter", "285dfda8-ae65-4ac1-8f6a-39ff7187bba9", 301, "100", SPListTemplate.QuickLaunchOptions.Off);
                    SPList     srchCenterList = eCaseFastSrchCtr.Lists[srchCenterGuid];
                    SPListItem defaultAspx    = srchCenterList.AddItem();
                    defaultAspx[eCaseConstants.FieldGuids.TABS_LIST_TAB_NAME] = "All Sites";
                    defaultAspx[eCaseConstants.FieldGuids.TABS_LIST_PAGE]     = "default.aspx";
                    defaultAspx[eCaseConstants.FieldGuids.TABS_LIST_TOOLTIP]  = "Click for results from All Sites";
                    defaultAspx.Update();
                    SPListItem advancedAspx = srchCenterList.AddItem();
                    advancedAspx[eCaseConstants.FieldGuids.TABS_LIST_TAB_NAME] = "All Sites";
                    advancedAspx[eCaseConstants.FieldGuids.TABS_LIST_PAGE]     = "advanced.aspx";
                    advancedAspx[eCaseConstants.FieldGuids.TABS_LIST_TOOLTIP]  = "Click for results from All Sites";
                    advancedAspx.Update();
                    SPListItem peopleAspx = srchCenterList.AddItem();
                    peopleAspx[eCaseConstants.FieldGuids.TABS_LIST_TAB_NAME] = "People";
                    peopleAspx[eCaseConstants.FieldGuids.TABS_LIST_PAGE]     = "people.aspx";
                    peopleAspx[eCaseConstants.FieldGuids.TABS_LIST_TOOLTIP]  = "Click for people results";
                    peopleAspx.Update();
                    #endregion
                }
                catch (Exception x)
                {
                    Logger.Instance.Error(string.Format("Failed to create Tabs lists in eCase FAST Search Center at {0}", eCaseFastSrchCtr.Url), x, DiagnosticsCategories.eCaseSearch);
                }
                #endregion
            }
            #endregion

            #region Create a Daily Schedule for the UpdateNextDueDate Timer Job
            string jobName = string.Format(UPDATE_NEXT_DUE_DATE_TIMER_JOB_NAME, eCaseRootSite.ServerRelativeUrl);
            foreach (SPJobDefinition job in eCaseRootSite.WebApplication.JobDefinitions)
            {
                if (job.Name == jobName)
                {
                    job.Delete();
                }
            }

            // Install the job.
            UpdateNextDueDateTimerJob unddTimerJob = new UpdateNextDueDateTimerJob(jobName, eCaseRootSite.WebApplication, null, SPJobLockType.Job, eCaseRootSite.ID.ToString());

            SPDailySchedule schedule = new SPDailySchedule();
            schedule.BeginHour    = 1;
            schedule.EndHour      = 2;
            unddTimerJob.Schedule = schedule;
            unddTimerJob.Update();

            #endregion
        }
        private SPWeb CreateWeb(string title, string parentUrl, string template)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("Web title can't be null or empty.");
            }

            if (string.IsNullOrEmpty(parentUrl))
            {
                throw new ArgumentException("Web parentUrl can't be null or empty.");
            }

            Trace.WriteLine(string.Format("Creating test web {0} at {1}", title, parentUrl));

            _site = new SPSite(UrlTestSite + parentUrl);
            SPWeb web = _site.OpenWeb();
            SPWeb newWeb;

            if (web == null)
            {
                throw new Exception(string.Format("Can´t open SharePoint Site at: {0}", _site.Url));
            }

            // If exist delete
            if (web.Webs[title].Exists)
            {
                throw new Exception(string.Format("There is already a web in this url.{0}", web.Webs[title].Url));
                //RecursiveDeleteWebs(web.Webs[title]);
                //web.Webs[title].Delete();
            }

            // Simple STS site
            if (template.Equals(string.Empty))
            {
                newWeb = web.Webs.Add(title);
            }
            else
            {
                // Create a web with custom based template
                try
                {
                    SPWebTemplateCollection webTemplateCollection;
                    webTemplateCollection = _site.GetCustomWebTemplates((uint)web.Locale.LCID);

                    SPWebTemplate webTemplate = webTemplateCollection[template];

                    newWeb = web.Webs.Add(title,
                                          title,
                                          string.Empty,
                                          (uint)web.Locale.LCID,
                                          webTemplate,
                                          true,
                                          false);
                }
                catch (ArgumentException) // Not a custom template
                {
                    newWeb = web.Webs.Add(title,
                                          title,
                                          string.Empty,
                                          (uint)web.Locale.LCID,
                                          template,
                                          true,
                                          false);
                }
            }

            Trace.WriteLine(string.Format("Created web {0} at {1}", newWeb.Title, newWeb.Url));

            return(newWeb);
        }
        /// <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);
        }
 public TemplateHolder(SPWebTemplate template)
 {
     this.Template = template;
 }
        private string createSite(string url, SPSiteSubscription subscription, string title, string description, string user, string fullName, string email, string template, out Guid siteid, bool useHostHeader)
        {
            siteid = Guid.Empty;
            string errors = "";

            try
            {
                SPSite site;
                if (subscription != null)
                {
                    site = app.Sites.Add(subscription, url, title, description, 1033, "", user, fullName, email, null, null, null, useHostHeader);
                }
                else
                {
                    site = app.Sites.Add(url, title, description, 1033, "", user, fullName, email, null, null, null, useHostHeader);
                }
                try
                {                                 //SPSite site = spApp.Sites.Add(bUrl + url, user, email);
                    site.AllowUnsafeUpdates = true;
                    using (SPWeb web = site.OpenWeb())

                    {
                        web.Title = title;
                        web.AllowUnsafeUpdates              = true;
                        web.Site.AllowUnsafeUpdates         = true;
                        web.Site.RootWeb.AllowUnsafeUpdates = true;
                        //SPDocumentLibrary solGallery1 = (SPDocumentLibrary)web.Site.RootWeb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);


                        string[] files   = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + "\\workengine\\templates\\" + template);
                        int      counter = 1;
                        foreach (string file in files)
                        {
                            addfile(Path.GetFileNameWithoutExtension(file), web, file, counter);
                            counter++;
                        }

                        SPWebTemplate webtemplate = null;
                        foreach (SPWebTemplate t in web.GetAvailableWebTemplates((uint)web.Locale.LCID))
                        {
                            if (t.Title == template)
                            {
                                webtemplate = t;
                                break;
                            }
                        }

                        if (webtemplate != null)
                        {
                            web.ApplyWebTemplate(webtemplate);
                        }

                        //web.Update();

                        //web.AllUsers.Add(user, email, fullName, "");
                        ////web.AllUsers.Add(System.Configuration.ConfigurationManager.AppSettings["owner"].ToString(), "", System.Configuration.ConfigurationManager.AppSettings["owner"].ToString(), "");
                        //web.Users[user].Name = fullName;
                        //web.Users[user].Update();

                        //web.Update();
                        SPUser owner = web.AllUsers[user];


                        web.SiteGroups.Add("Administrators", owner, owner, "");

                        //web.Update();
                        web.AssociatedOwnerGroup = GetSiteGroup(web, "Administrators");
                        SPRole roll = web.Roles["Full Control"];
                        roll.AddGroup(web.SiteGroups["Administrators"]);
                        SPMember newOwner = web.SiteGroups["Administrators"];

                        web.SiteGroups.Add("Team Members", newOwner, owner, "");
                        web.SiteGroups.Add("Visitors", newOwner, owner, "");
                        web.SiteGroups.Add("Project Managers", newOwner, owner, "");
                        //web.Update();

                        web.AssociatedVisitorGroup = GetSiteGroup(web, "Visitors");
                        web.AssociatedOwnerGroup   = GetSiteGroup(web, "Administrators");
                        web.AssociatedMemberGroup  = GetSiteGroup(web, "Team Members");
                        // web.Update();

                        //web.SiteGroups["Administrators"].Users[user].Name = fullName;
                        //web.SiteGroups["Project Managers"].Users[user].Name = fullName;
                        //web.SiteGroups["Team Members"].Users[user].Name = fullName;
                        //web.SiteGroups["Visitors"].Users[user].Name = fullName;

                        web.Roles.Add("Contribute2", "Can view, add, update, delete and manage subwebs", web.Roles["Contribute"].PermissionMask | SPRights.ManageSubwebs);

                        roll = web.Roles["Full Control"];
                        roll.AddGroup(web.SiteGroups["Administrators"]);

                        roll = web.Roles["Contribute"];
                        roll.AddGroup(web.SiteGroups["Team Members"]);

                        roll = web.Roles["Read"];
                        roll.AddGroup(web.SiteGroups["Visitors"]);

                        roll = web.Roles["Contribute2"];
                        roll.AddGroup(web.SiteGroups["Project Managers"]);

                        siteid = site.ID;

                        if (txtDatabaseServer.Text != "")
                        {
                            errors = mapReports(site);
                        }
                    }
                }
                catch (Exception ex) { errors = ex.ToString(); }
                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                errors = ex.Message;
            }

            return(errors);
        }