private void loadTemplateListBox()
 {
     try
     {
         using (SPSite site = SPContext.Current.Site)
         {
             using (SPWeb rootWeb = site.RootWeb)
             {
                 int iCnt = 0;
                 SPWebTemplateCollection oWebTmpltCol = currWeb.GetAvailableWebTemplates((uint)currWeb.Locale.LCID);
                 foreach (SPWebTemplate otmplt in oWebTmpltCol)
                 {
                     //SPWeb web = site.AllWebs[otmplt.Title];
                     //if (!web.Properties.ContainsKey("EPMLiveTemplateID"))
                     {
                         lstTemplates.Items.Add(otmplt.Title);
                         iCnt++;
                     }
                 }
                 lstTemplates.Height = 16 * iCnt;
             }
         }
     }
     catch (Exception exc)
     {
     }
 }
        private static string[] GetWebTemplateCategories(ISharePointCommandContext context)
        {
            context.Logger.WriteLine(Resources.WebTemplateSharePointCommands_TryingToRetrieveAvailableCategories, LogCategory.Status);

            List <string> categories = new List <string>();

            try
            {
                SPWebTemplateCollection webTemplates = context.Web.GetAvailableWebTemplates((uint)context.Web.Locale.LCID, true);

                foreach (SPWebTemplate item in webTemplates)
                {
                    if (!categories.Contains(item.DisplayCategory))
                    {
                        categories.Add(item.DisplayCategory);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Logger.WriteLine(String.Format(Resources.WebTemplateSharePointCommands_CategoriesRetrievingException,
                                                       ex.Message,
                                                       Environment.NewLine,
                                                       ex.StackTrace), LogCategory.Error);
            }

            return(categories.ToArray());
        }
        private static WebTemplateInfo[] GetWebTemplates(ISharePointCommandContext context)
        {
            context.Logger.WriteLine(Resources.WebTemplateSharePointCommands_TryingToRetrieveAvailableWebTemplates, LogCategory.Status);

            List <WebTemplateInfo> webTemplateInfos = new List <WebTemplateInfo>();

            try
            {
                SPSite caSite  = null;
                SPWeb  rootWeb = null;

                if (context.Site == null)
                {
                    //Do this as from item templates the site is always null
                    SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                    caSite  = caWebApp.Sites[0];
                    rootWeb = caSite.RootWeb;
                }
                else
                {
                    caSite  = context.Site;
                    rootWeb = context.Web;
                }

                SPWebTemplateCollection webTemplates = caSite.GetWebTemplates((uint)rootWeb.Locale.LCID);

                foreach (SPWebTemplate item in webTemplates)
                {
                    //Check the temaplate is a site defintion and has a display category
                    if (!String.IsNullOrEmpty(item.DisplayCategory) && !item.IsCustomTemplate)
                    {
                        WebTemplateInfo info = new WebTemplateInfo();

                        info.Id               = item.ID;
                        info.ImageUrl         = item.ImageUrl;
                        info.Name             = item.Name;
                        info.Description      = item.Description;
                        info.DisplayCategory  = item.DisplayCategory;
                        info.IsCustomTemplate = item.IsCustomTemplate;
                        info.IsHidden         = item.IsHidden;
                        info.IsRootWebOnly    = item.IsRootWebOnly;
                        info.IsSubWebOnly     = item.IsSubWebOnly;
                        info.Lcid             = item.Lcid;
                        info.Title            = item.Title;
                        info.SetupPath        = typeof(SPWebTemplate).InvokeMember("SetupPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty, null, item, null) as string;

                        webTemplateInfos.Add(info);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Logger.WriteLine(String.Format(Resources.WebTemplateSharePointCommands_RetrievingException,
                                                       ex.Message,
                                                       Environment.NewLine,
                                                       ex.StackTrace), LogCategory.Error);
            }

            return(webTemplateInfos.ToArray());
        }
        private void loadTemplates(string validtemplates)
        {
            Hashtable hshTemplates          = new Hashtable();
            SPWebTemplateCollection sptemps = SPContext.Current.Web.GetAvailableWebTemplates(SPContext.Current.Web.Language);

            SortedList sl = new SortedList();

            foreach (SPWebTemplate webTemplate in sptemps)
            {
                if (!webTemplate.IsHidden)
                {
                    hshTemplates.Add(webTemplate.Title, webTemplate.Title);
                }
            }

            using (SPWeb web = SPContext.Current.Web)
            {
                string[] templates = validtemplates.Split('|');
                foreach (string template in templates)
                {
                    if (hshTemplates.Contains(template))
                    {
                        lstSelectedTemplates.Items.Add(new ListItem(hshTemplates[template].ToString(), template));
                        hshTemplates.Remove(template);
                    }
                }
            }

            foreach (DictionaryEntry de in hshTemplates)
            {
                lstAllTemplates.Items.Add(new ListItem(de.Value.ToString(), de.Key.ToString()));
            }
        }
Exemple #5
0
        private SPWebTemplate GetWebTemplate(string template, SPSite site, SPWeb web)
        {
            SPWebTemplate           webTemplate;
            SPWebTemplateCollection templates = site.GetWebTemplates((uint)web.Locale.LCID);

            webTemplate = LocateTemplateByName(templates, template);

            return(webTemplate);
        }
Exemple #6
0
 private SPWebTemplate LocateTemplateByName(SPWebTemplateCollection templates, string templateTitle)
 {
     foreach (SPWebTemplate template in templates)
     {
         if (template.Title == templateTitle)
         {
             return(template);
         }
     }
     return(null);
 }
Exemple #7
0
 /// <summary>
 /// Return the web template description based on the name
 /// </summary>
 private static SPWebTemplate FindWebTemplate(SPWebTemplateCollection templateCollection, string templateName)
 {
     foreach (SPWebTemplate webTemplate in templateCollection)
     {
         // NB: Must use case-insentive here
         if (webTemplate.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase))
         {
             return(webTemplate);
         }
     }
     return(null);
 }
        private SPWebTemplate LookupTemplateIDInDefinitions(SPSite site, string templateName)
        {
            SPWebTemplateCollection templates = site.GetWebTemplates(LCID);

            foreach (SPWebTemplate template in templates)
            {
                if ((template.Name.ToLower() == templateName.ToLower()) || (template.Title.ToLower() == templateName.ToLower()))
                {
                    return(template);
                }
            }
            return(null);
        }
Exemple #9
0
        private string LookupTemplateIDInGallery(SPSite site)
        {
            SPWebTemplateCollection templates = site.GetCustomWebTemplates(LCID);

            foreach (SPWebTemplate template in templates)
            {
                if ((template.Name.ToLower() == TemplateName.ToLower()) || (template.Title.ToLower() == TemplateName.ToLower()))
                {
                    return(template.Name);
                }
            }
            return(string.Empty);
        }
Exemple #10
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);
        }
Exemple #11
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
     {
     }
 }
        private void SetAvailableSubWebs(SPWebEventProperties properties)
        {
            SPWeb web = properties.Web;

            if (!web.AllProperties.ContainsKey("__WebTemplates"))
            {
                web.AllProperties.Add("__WebTemplates", "");
            }

            web.AllowAllWebTemplates();

            web.Update();

            SPWebTemplateCollection existingLanguageNeutralTemplatesCollection  = web.GetAvailableCrossLanguageWebTemplates();
            SPWebTemplateCollection existingLanguageSpecificTemplatesCollection = web.GetAvailableWebTemplates(web.Language);

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

            foreach (SPWebTemplate existingTemplate in existingLanguageNeutralTemplatesCollection)
            {
                if (existingTemplate.DisplayCategory.Contains("WebSite"))
                {
                    newLanguageNeutralTemplatesCollection.Add(existingTemplate);
                }
            }
            foreach (SPWebTemplate existingTemplate in existingLanguageSpecificTemplatesCollection)
            {
                if (existingTemplate.DisplayCategory.Contains("WebSite"))
                {
                    newLanguageSpecificTemplatesCollection.Add(existingTemplate);
                }
            }

            if (newLanguageNeutralTemplatesCollection.Count != 0)
            {
                web.SetAvailableCrossLanguageWebTemplates(newLanguageNeutralTemplatesCollection);
            }

            if (newLanguageSpecificTemplatesCollection.Count != 0)
            {
                web.SetAvailableWebTemplates(newLanguageSpecificTemplatesCollection, web.Language);
            }

            web.Update();
        }
        private void lnkShowAllTemplates_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SPWeb web = Util.RetrieveWeb(txtTargetSite.Text, rtbSiteValidateMessage);

            if (web == null)
            {
                return;
            }
            txtTargetSite.Text = web.Url;

            SPWebTemplateCollection templates = web.Site.GetWebTemplates(1033);

            rtbDisplay.Clear();
            SmartStepUtil.AddToRTB(rtbDisplay, "Site Template Information\r\n", Color.Blue, 10, true);
            foreach (SPWebTemplate template in templates)
            {
                SmartStepUtil.AddToRTB(rtbDisplay, "name:" + template.Name + ", title:" + template.Title + "\r\n");
            }
        }
        private static WebTemplateInfo[] GetAvailableWebTemplatesByCategory(ISharePointCommandContext context, string category)
        {
            context.Logger.WriteLine(Resources.WebTemplateSharePointCommands_TryingToRetrieveAvailableWebTemplates, LogCategory.Status);

            List <WebTemplateInfo> webTemplateInfos = new List <WebTemplateInfo>();

            try
            {
                SPWebTemplateCollection webTemplates = context.Web.GetAvailableWebTemplates((uint)context.Web.Locale.LCID, true);

                foreach (SPWebTemplate item in webTemplates)
                {
                    if (item.DisplayCategory == category)
                    {
                        WebTemplateInfo info = new WebTemplateInfo();

                        info.Id               = item.ID;
                        info.ImageUrl         = item.ImageUrl;
                        info.Name             = item.Name;
                        info.Description      = item.Description;
                        info.DisplayCategory  = item.DisplayCategory;
                        info.IsCustomTemplate = item.IsCustomTemplate;
                        info.IsHidden         = item.IsHidden;
                        info.IsRootWebOnly    = item.IsRootWebOnly;
                        info.IsSubWebOnly     = item.IsSubWebOnly;
                        info.Lcid             = item.Lcid;
                        info.Title            = item.Title;
                        info.SetupPath        = typeof(SPWebTemplate).InvokeMember("SetupPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty, null, item, null) as string;

                        webTemplateInfos.Add(info);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Logger.WriteLine(String.Format(Resources.WebTemplateSharePointCommands_RetrievingException,
                                                       ex.Message,
                                                       Environment.NewLine,
                                                       ex.StackTrace), LogCategory.Error);
            }

            return(webTemplateInfos.ToArray());
        }
Exemple #15
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();
            });
        }
        /// <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);
        }
        private List <SPSKeyValuePair> GetAvailableSiteTemplates()
        {
            SPWeb  web  = SPContext.Current.Web;
            SPSite site = web.Site;
            SPWebTemplateCollection siteTemplates = site.GetCustomWebTemplates((uint)web.Locale.LCID);
            var templates = new List <SPSKeyValuePair>();

            foreach (SPWebTemplate template in siteTemplates)
            {
                templates.Add(new SPSKeyValuePair(template.Title, template.DisplayCategory));
            }

            siteTemplates = site.GetWebTemplates((uint)web.Locale.LCID);

            foreach (SPWebTemplate template in siteTemplates)
            {
                if (!template.IsHidden)
                {
                    templates.Add(new SPSKeyValuePair(template.Title, template.DisplayCategory));
                }
            }

            return(templates);
        }
Exemple #18
0
        public static string CreateSite(this SPSite site, string tempalteName, string siteName, string title, string description)
        {
            string siteDepartmentUrl = string.Empty;

            try
            {
                site.AllowUnsafeUpdates = true;

                SPWebTemplateCollection templates = site.GetWebTemplates(1033);
                var deptsite = templates.Cast <SPWebTemplate>().Where(p => p.Name.Contains(tempalteName)).FirstOrDefault();

                SPWeb web = site.RootWeb.Webs.Add(siteName, title, description, 1033, deptsite.Name, true, false);

                web.Update();
                siteDepartmentUrl = web.Url;

                web.Dispose();
            }
            catch (Exception ex)
            {
                Utility.LogInfo("CreateSite " + ex.ToString(), "AIA.Intranet.Common.Extensions");
            }
            return(siteDepartmentUrl);
        }
 /// <summary>
 /// Return the web template description based on the name
 /// </summary>
 private static SPWebTemplate FindWebTemplate(SPWebTemplateCollection templateCollection, string templateName)
 {
     foreach (SPWebTemplate webTemplate in templateCollection)
     {
         // NB: Must use case-insentive here
         if (webTemplate.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase))
             return webTemplate;
     }
     return null;
 }
Exemple #20
0
        internal static void DoInstallation(Package.InstallationStateData installationStateData, BackgroundWorker _wrkr, DoWorkEventArgs e, FileInfo packageContentLocation)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (_wrkr.CancellationPending)
                {
                    e.Cancel = true;
                    e.Result = false;
                    return;
                }
                try
                {
                    string _format = "Trying to create or reuse the site collection at {0}, configured site template {1}, LCID {2}.";
                    _wrkr.ReportProgress(1, String.Format(_format, installationStateData.SiteCollectionURL, installationStateData.SiteTemplate, installationStateData.LCID));
                    using (SiteCollectionHelper m_SiteCollectionHelper = SiteCollectionHelper.GetSPSite(
                               FarmHelpers.WebApplication,
                               installationStateData.SiteCollectionURL,
                               installationStateData.Title,
                               installationStateData.Description,
                               installationStateData.LCID,
                               null,
                               installationStateData.OwnerLogin,
                               installationStateData.OwnerName,
                               installationStateData.OwnerEmail))
                    {
                        installationStateData.SiteCollectionCreated = true;
                        _wrkr.ReportProgress(1, "Site collection is created");
                        if (m_SiteCollectionHelper.NewTemplateRequired)
                        {
                            _wrkr.ReportProgress(1, "Applying new template - select required from dialog.");
                            s_EndOFUIAction.Reset();
                            SPWebTemplateCollection _cllctn = m_SiteCollectionHelper.GetWebTemplates(installationStateData.LCID);
                            _wrkr.ReportProgress(1, new SPWebTeplateEventArgs(_cllctn, GetTemplate, 1, "Getting Site template")); //GetTemplate( FarmHelpers.WebApplication.Sites[ _urlSite ], installationStateData );
                            s_EndOFUIAction.WaitOne();
                            _wrkr.ReportProgress(1, String.Format("Applying new template {0}", WebTemplateDialog.SPWebTemplateToString(installationStateData.SPWebTemplate)));
                            m_SiteCollectionHelper.ApplayTemplate(installationStateData.SPWebTemplate);
                        }
                        _format = "The site template is configured to Name: {0}/ Id: {1}.";
                        _wrkr.ReportProgress(1, String.Format(_format, m_SiteCollectionHelper.SiteTemplate, m_SiteCollectionHelper.SiteTemplateID));
                        using (PackageContent _PackageContent = new PackageContent(packageContentLocation))
                        {
                            foreach (Solution _sltn in installationStateData.SolutionsToInstall.Values)
                            {
                                FileInfo _fi = _sltn.SolutionFileInfo(_PackageContent.ContentLocation);
                                _wrkr.ReportProgress(1, String.Format("Deploying solution: {0}", _fi.Name));
                                switch (_sltn.FeatureDefinitionScope)
                                {
                                case FeatureDefinitionScope.Farm:
                                    TimeSpan _timeout            = new TimeSpan(0, 0, Properties.Settings.Default.SolutionDeploymentTimeOut);
                                    string _waitingForCompletion = String.Format("Waiting for completion .... It could take up to {0} s. ", _timeout);
                                    _wrkr.ReportProgress(1, _waitingForCompletion);
                                    SPSolution _sol = null;
                                    if (_sltn.Global)
                                    {
                                        _sol = FarmHelpers.DeploySolution(_fi, _timeout);
                                    }
                                    else
                                    {
                                        _sol = FarmHelpers.DeploySolution(_fi, FarmHelpers.WebApplication, _timeout);
                                    }
                                    _sltn.SolutionGuid = _sol.Id;
                                    _wrkr.ReportProgress(1, String.Format("Solution deployed Name={0}, Deployed={1}, DeploymentState={2}, DisplayName={3} Status={4}", _sol.Name, _sol.Deployed, _sol.DeploymentState, _sol.DisplayName, _sol.Status));
                                    break;

                                case FeatureDefinitionScope.Site:
                                    SPUserSolution _solution = null;
                                    _solution          = m_SiteCollectionHelper.DeploySolution(_fi);
                                    _sltn.SolutionGuid = _solution.SolutionId;
                                    _wrkr.ReportProgress(1, String.Format("Solution deployed: {0}", _solution.Name));
                                    break;

                                case FeatureDefinitionScope.None:
                                default:
                                    throw new ApplicationException("Wrong FeatureDefinitionScope in the configuration file");
                                }
                                _sltn.Deployed = true;
                                foreach (Feature _fix in _sltn.Fetures)
                                {
                                    bool _repeat;
                                    do
                                    {
                                        _repeat = false;
                                        try
                                        {
                                            if (!_fix.AutoActivate)
                                            {
                                                _wrkr.ReportProgress(1, String.Format("Skipping activation of the feature: {0} at: {1} because tha activation is set false", _fix.FetureGuid, m_SiteCollectionHelper.SiteCollection.Url));
                                                break;
                                            }
                                            _wrkr.ReportProgress(1, String.Format("Activating Feature: {0} at: {1}", _fix.FetureGuid, m_SiteCollectionHelper.SiteCollection.Url));
                                            SPFeature _ffeature = m_SiteCollectionHelper.ActivateFeature(_fix.FetureGuid, _sltn.SPFeatureDefinitionScope);
                                            _wrkr.ReportProgress(1, String.Format("Feature activated : {0}", _ffeature.Definition.DisplayName));
                                            _fix.DisplayName = _ffeature.Definition.DisplayName;
                                            _fix.Version     = _ffeature.Version.ToString();
                                            _fix.SPScope     = _ffeature.Definition.Scope;
                                        }
                                        catch (Exception ex)
                                        {
                                            string _msg = String.Format(Properties.Resources.FeatureActivationFailureMBox, ex.Message);
                                            Tracing.TraceEvent.TraceError(516, "SetUpData.Install", _msg);
                                            switch (MessageBox.Show(_msg, "Install ActivateFeature", MessageBoxButton.YesNoCancel, MessageBoxImage.Error, MessageBoxResult.No))
                                            {
                                            case MessageBoxResult.Cancel:
                                                throw ex;

                                            case MessageBoxResult.Yes:
                                                _repeat = true;
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                    } while (_repeat);
                                }//foreach (Feature _fix in _sltn.Fetures)
                                _sltn.Activated = true;
                            }
                        } //foreach (Solution _sltn
                        //TODO installationStateData.Save();
                        _wrkr.ReportProgress(1, "Product installation successfully completed");
                    }
                }
                catch (Exception ex)
                {
                    //TODO
                    //try
                    //{
                    //  installationStateData.Save();
                    //}
                    //catch ( Exception _SaveEx )
                    //{
                    //  InstallationListBox.AddMessage( _SaveEx.Message );
                    //}
                    string _msg = String.Format(Properties.Resources.LastOperationFailedWithError, ex.Message);
                    _wrkr.ReportProgress(1, _msg);
                    throw ex;
                }
            });
        }
 public SPWebTeplateEventArgs(SPWebTemplateCollection collection, Action onSelected, int progressPercentage, string userState) :
     base(progressPercentage, userState)
 {
     WebTemplates         = collection;
     SPWebTeplateSelected = onSelected;
 }
        /// <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);
        }
Exemple #24
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);
        }
Exemple #25
0
        public static SPWebTemplate GetWebTemplate(this SPWeb web, String templateName)
        {
            SPWebTemplateCollection wtc = web.GetAvailableWebTemplates(Convert.ToUInt32(web.Locale.LCID));

            return(wtc.Cast <SPWebTemplate>().FirstOrDefault(wt => wt.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase)));
        }