Пример #1
0
 public void Update(object ensure)
 {
     if (ensure == null || ensure == Null.Value || ensure == Undefined.Value)
     {
         m_webApplication.Update();
     }
     else
     {
         m_webApplication.Update(TypeConverter.ToBoolean(ensure));
     }
 }
Пример #2
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                configurationproperties = properties.Feature.Properties;
                if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
                {
                    SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

                    //SPSite site = webApp.Sites.Where(p => p.ServerRelativeUrl.Equals("/", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    CreateVirtualDirectory(webApp);

                    SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                    List <SPWebConfigModification> process = new List <SPWebConfigModification>();
                    process.AddRange(ZimbraWebConfigModification.Modifications);

                    foreach (SPWebConfigModification mod in process)
                    {
                        try
                        {
                            if (!wap.WebConfigModifications.Contains(mod))
                            {
                                wap.WebConfigModifications.Add(mod);
                            }

                            if (!SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Contains(mod))
                            {
                                SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Add(mod);
                            }
                        }
                        catch (Exception ex)
                        {
                            diagSvc.WriteEvent(0,
                                               new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                               EventSeverity.Error,
                                               "Exception occured {0}", new object[] { ex });
                        }
                    }

                    try
                    {
                        wap.Update(false);
                        SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                        SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                        //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                        wap.WebConfigModifications.Clear();
                        wap.Update(false);
                    }
                    catch { };
                }
            });
        }
Пример #3
0
        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private void FeatureCleaning(SPFeatureReceiverProperties properties)
        {
            if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
            {
                webApp = properties.Feature.Parent as SPWebApplication;
                SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                List <SPWebConfigModification> toDelete = new List <SPWebConfigModification>();
                bool found = false;
                try
                {
                    foreach (SPWebConfigModification mod in wap.WebConfigModifications)
                    {
                        if (mod.Owner.Contains("ClubCloud"))
                        {
                            toDelete.Add(mod);
                            found = true;
                        }
                    }

                    foreach (SPWebConfigModification mod in toDelete)
                    {
                        wap.WebConfigModifications.Remove(mod);
                        SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Remove(mod);
                    }

                    wap.Update(false);
                    SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                    SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                    wap.WebConfigModifications.Clear();
                    wap.Update();
                }
                catch (Exception ex)
                {
                    diagSvc.WriteEvent(0,
                                       new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                       EventSeverity.Error,
                                       "Exception occured {0}", new object[] { ex });
                    found = true;
                }
                finally { toDelete = new List <SPWebConfigModification>(); }

                //if(found)
                //{
                //    FeatureUninstalling(properties);
                //}
            }
        }
        internal static void AddUserPolicy(string login, string username, string[] permissions, SPWebApplication webApp, SPPolicyCollection policies)
        {
            login = Utilities.TryGetNT4StyleAccountName(login, webApp);

            List <SPPolicyRole> roles = new List <SPPolicyRole>();

            foreach (string roleName in permissions)
            {
                SPPolicyRole role = webApp.PolicyRoles[roleName.Trim()];
                if (role == null)
                {
                    throw new SPException(string.Format("The policy permission '{0}' was not found.", roleName.Trim()));
                }

                roles.Add(role);
            }
            SPPolicy policy = policies.Add(login, username);

            foreach (SPPolicyRole role in roles)
            {
                policy.PolicyRoleBindings.Add(role);
            }

            webApp.Update();
        }
        private void DeployPeoplePickerSettings(object modelHost, SPWebApplication webApplication, PeoplePickerSettingsDefinition definition)
        {
            var settings = GetCurrentPeoplePickerSettings(webApplication);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = settings,
                ObjectType = typeof(SPPeoplePickerSettings),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            MapPeoplePickerSettings(settings, definition);

            // reSP doesn't like updating SPWebApplication here, don't see an other way though
            webApplication.Update();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = settings,
                ObjectType = typeof(SPPeoplePickerSettings),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            return;

            SPSite           currentSite   = properties.Feature.Parent as SPSite;
            SPWebApplication currentWebApp = currentSite.WebApplication;

            Collection <SPWebConfigModification> colMods       = currentWebApp.WebConfigModifications;
            Collection <SPWebConfigModification> colForRemoval = new Collection <SPWebConfigModification>();

            foreach (SPWebConfigModification mod in colMods)
            {
                if (mod.Owner == m_ModificationOwner)
                {
                    colForRemoval.Add(mod);
                }
            }

            foreach (SPWebConfigModification modForRemoval in colForRemoval)
            {
                colMods.Remove(modForRemoval);
            }

            if (colForRemoval.Count > 0)
            {
                currentWebApp.WebService.ApplyWebConfigModifications();
                currentWebApp.Update();
            }
        }
Пример #7
0
        public static void RemoveAllModifications(SPWebApplication webApp, List <string> names)
        {
            var modifications = new List <SPWebConfigModification>();

            foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
            {
                if (modification.Owner == ModificationOwner)
                {
                    modifications.Add(modification);
                }
            }

            foreach (SPWebConfigModification modification in modifications)
            {
                foreach (string name in names)
                {
                    if (modification.Name == name)
                    {
                        webApp.WebConfigModifications.Remove(modification);
                    }
                }
            }

            webApp.Update();
        }
Пример #8
0
        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private void RemoveAllCustomisations(SPWebApplication webApp)
        {
            if (webApp != null)
            {
                Collection <SPWebConfigModification> collection = webApp.WebConfigModifications;
                int iStartCount = collection.Count;

                // Remove any modifications that were originally created by the owner.
                for (int c = iStartCount - 1; c >= 0; c--)
                {
                    SPWebConfigModification configMod = collection[c];

                    if (configMod.Owner == "SPExcelWebAppRedirecter")
                    {
                        collection.Remove(configMod);
                    }
                }

                // Apply changes only if any items were removed.
                if (iStartCount > collection.Count)
                {
                    webApp.Update();
                    webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                }
            }
        }
Пример #9
0
        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private static void ModifyWebConfig(SPWebApplication webApplication, bool remove)
        {
            const string assembly   = @"Nauplius.WAS.2013, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1458f7a17eac05e9";
            const string _namespace = @"Nauplius.WAS";

            var modification = new SPWebConfigModification
            {
                Owner    = "Nauplius.WAS",
                Sequence = 0,
                Path     = "configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes/targetFx[@version='v4.0']",
                Name     =
                    string.Format(
                        "authorizedType[@Assembly='{0}'][@Namespace='{1}'][@TypeName='*'][@Authorized='True']", assembly,
                        _namespace),
                Value =
                    string.Format("<authorizedType Assembly='{0}' Namespace='{1}' TypeName='*' Authorized='True'/>",
                                  assembly, _namespace)
            };

            if (!remove)
            {
                webApplication.WebConfigModifications.Add(modification);
            }
            else
            {
                webApplication.WebConfigModifications.Remove(modification);
            }

            webApplication.Update();
            webApplication.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
        }
Пример #10
0
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Collection <SPWebConfigModification> mods = webApplication.WebConfigModifications;
                int initialModificationsCount             = mods.Count;

                for (int i = initialModificationsCount - 1; i >= 0; i--)
                {
                    if (mods[i].Owner == "SampleToDeployAPage")
                    {
                        SPWebConfigModification modToRemove = mods[i];
                        mods.Remove(modToRemove);
                    }
                }

                if (initialModificationsCount > mods.Count)
                {
                    webApplication.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                    webApplication.Update();
                }
            });
        }
Пример #11
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);

            WebSiteControllerWebConfigManager.ClearWebConfigModifications(webApp);
            SPWebConfigModification mod = WebSiteControllerWebConfigManager.GetHttpModuleEntry();

            if (!webApp.WebConfigModifications.Contains(mod))
            {
                webApp.WebConfigModifications.Add(mod);
            }

            mod = WebSiteControllerWebConfigManager.GetModuleEntry();
            if (!webApp.WebConfigModifications.Contains(mod))
            {
                webApp.WebConfigModifications.Add(mod);
            }

            try
            {
                webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                webApp.Update();
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                //ex.ToString();
            }
        }
        /// <summary>
        /// Remove the web.config entries once deactivated
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            string asmDetails = typeof(DownloadFileHandler).AssemblyQualifiedName;

            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

            if (webApp == null)
            {
                return;
            }

            List <SPWebConfigModification>       configModsFound = new List <SPWebConfigModification>();
            Collection <SPWebConfigModification> modsCollection  = webApp.WebConfigModifications;

            for (int i = 0; i < modsCollection.Count; i++)
            {
                if (modsCollection[i].Owner == asmDetails)
                {
                    configModsFound.Add(modsCollection[i]);
                }
            }

            if (configModsFound.Count > 0)
            {
                foreach (SPWebConfigModification mod in configModsFound)
                {
                    modsCollection.Remove(mod);
                }

                webApp.Update();
                webApp.WebService.ApplyWebConfigModifications();
            }
        }
Пример #13
0
        private void UpdateServices()
        {
            try
            {
                _webApplication.Update();
                Thread.Sleep(1000);
                Debug.WriteLine("WebApplication updated.");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Source);
                Debug.WriteLine(ex);
                Debug.WriteLine("WebApplication NOT updated.");
            }

            try
            {
                _webApplication.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                Thread.Sleep(1000);
                Debug.WriteLine("Services updated.");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Source);
                Debug.WriteLine(ex);
                Debug.WriteLine("Services NOT updated.");
            }
        }
        private void DeployPeoplePickerSettings(object modelHost, SPWebApplication webApplication, PeoplePickerSettingsDefinition definition)
        {
            var settings = GetCurrentPeoplePickerSettings(webApplication);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = settings,
                ObjectType       = typeof(SPPeoplePickerSettings),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            MapPeoplePickerSettings(settings, definition);

            // reSP doesn't like updating SPWebApplication here, don't see an other way though
            webApplication.Update();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = settings,
                ObjectType       = typeof(SPPeoplePickerSettings),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });
        }
Пример #15
0
        /// <summary>
        /// Method to add one or multiple WebConfig modifications
        /// NOTE: There should not have 2 modifications with the same Owner.
        /// </summary>
        /// <param name="webApp">The current Web Application</param>
        /// <param name="webConfigModificationCollection">The collection of WebConfig modifications to remove-and-add</param>
        /// <remarks>All SPWebConfigModification Owner should be UNIQUE !</remarks>
        public void AddAndCleanWebConfigModification(SPWebApplication webApp, Collection <SPWebConfigModification> webConfigModificationCollection)
        {
            // Verify emptyness
            if (webConfigModificationCollection == null || !webConfigModificationCollection.Any())
            {
                throw new ArgumentNullException("webConfigModificationCollection");
            }

            SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webApp.Id];

            // Start by cleaning up any existing modification for all owners
            // By Good practice, owners should be unique, so we do this to remove duplicates entries if any.
            var owners = webConfigModificationCollection.Select(modif => modif.Owner).Distinct().ToList();

            this.RemoveExistingModificationsFromOwner(webApplication, owners);

            // Add WebConfig modifications
            foreach (var webConfigModification in webConfigModificationCollection)
            {
                webApplication.WebConfigModifications.Add(webConfigModification);
            }

            // Commit modification additions to the specified web application
            webApplication.Update();

            // Push modifications through the farm
            webApplication.WebService.ApplyWebConfigModifications();

            // Wait for timer job
            WaitForWebConfigPropagation(webApplication.Farm);
        }
Пример #16
0
        /// <summary>
        /// Extends the web app.
        /// </summary>
        /// <param name="webApplication">The web application.</param>
        /// <param name="description">The description.</param>
        /// <param name="hostHeader">The host header.</param>
        /// <param name="port">The port.</param>
        /// <param name="loadBalancedUrl">The load balanced URL.</param>
        /// <param name="path">The path.</param>
        /// <param name="allowAnonymous">if set to <c>true</c> [allow anonymous].</param>
        /// <param name="useNtlm">if set to <c>true</c> [use NTLM].</param>
        /// <param name="useSsl">if set to <c>true</c> [use SSL].</param>
        /// <param name="zone">The zone.</param>
        public static void ExtendWebApp(SPWebApplication webApplication, string description, string hostHeader, int port, string loadBalancedUrl, string path, bool allowAnonymous, bool useNtlm, bool useSsl, SPUrlZone zone)
        {
            SPServerBinding serverBinding = null;
            SPSecureBinding secureBinding = null;

            if (!useSsl)
            {
                serverBinding            = new SPServerBinding();
                serverBinding.Port       = port;
                serverBinding.HostHeader = hostHeader;
            }
            else
            {
                secureBinding      = new SPSecureBinding();
                secureBinding.Port = port;
            }

            SPIisSettings settings = new SPIisSettings(description, allowAnonymous, useNtlm, serverBinding, secureBinding, new DirectoryInfo(path.Trim()));

            settings.PreferredInstanceId = GetPreferredInstanceId(description);

            webApplication.IisSettings.Add(zone, settings);
            webApplication.AlternateUrls.SetResponseUrl(new SPAlternateUrl(new Uri(loadBalancedUrl), zone));
            webApplication.AlternateUrls.Update();
            webApplication.Update();
            webApplication.ProvisionGlobally();
        }
Пример #17
0
        }// END Method Close

        public void AddPluginInterface(string pluginInterfaceName)
        {
            if (this.web.ContainsKey(Thread.CurrentThread))
            {
                SPWeb web = this.web[Thread.CurrentThread];
                XMLDocumentPersistenceDriver p = GetXMLDocumentPersistenceDriver(web);

                p.AddPluginInterface(pluginInterfaceName);

                web.Properties[KEY] = p.Document.InnerXml;
                web.Update();
            }

            else if (this.webApplication.ContainsKey(Thread.CurrentThread))
            {
                SPWebApplication             webApplication = this.webApplication[Thread.CurrentThread];
                XMLDocumentPersistenceDriver p = GetXMLDocumentPersistenceDriver(webApplication);

                p.AddPluginInterface(pluginInterfaceName);

                webApplication.Properties[KEY] = p.Document.InnerXml;
                webApplication.Update();
            }

            else if (farm.Contains(Thread.CurrentThread))
            {
                SPFarm localFarm = SPFarm.Local;
                XMLDocumentPersistenceDriver p = GetXMLDocumentPersistenceDriver(localFarm);

                p.AddPluginInterface(pluginInterfaceName);

                localFarm.Properties[KEY] = p.Document.InnerXml;
                localFarm.Update();
            }
        }// END Method AddPluginInterface
        public void RemoveExistingModificationsFromOwner(SPWebApplication webApplication, string owner)
        {
            var removeCollection       = new Collection <SPWebConfigModification>();
            var modificationCollection = webApplication.WebConfigModifications;

            int count = modificationCollection.Count;

            for (int i = 0; i < count; i++)
            {
                SPWebConfigModification modification = modificationCollection[i];
                if (modification.Owner == owner)
                {
                    // collect modifications to delete
                    removeCollection.Add(modification);
                }
            }

            // now delete the modifications from the web application
            if (removeCollection.Count > 0)
            {
                foreach (SPWebConfigModification modificationItem in removeCollection)
                {
                    webApplication.WebConfigModifications.Remove(modificationItem);
                }

                // Commit modification removals to the specified web application
                webApplication.Update();

                // Push modifications through the farm
                webApplication.WebService.ApplyWebConfigModifications();
            }
        }
Пример #19
0
        private void OverrideBrowserCaps(SPFeatureReceiverProperties properties)
        {
            if (webApp != null)
            {
                SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);

                /*
                 * <browserCaps>
                 *  <result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                 *  <filter>isMobileDevice=false</filter>
                 * </browserCaps>
                 */
                SPWebConfigModification mod = new SPWebConfigModification("add[@type='System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a']", "configuration/system.web/browserCaps");
                mod.Owner    = properties.Feature.DefinitionId.ToString();
                mod.Sequence = 0;
                mod.Type     = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                mod.Value    = @"<result type=""System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" /><filter>isMobileDevice=false</filter>";
                if (!webApp.WebConfigModifications.Contains(mod))
                {
                    webApp.WebConfigModifications.Add(mod);
                }
                try
                {
                    SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);
                    webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                    ////webApp.WebService.ApplyWebConfigModifications();
                    webApp.Update();
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            }
        }
        /// <summary>
        /// Remove modifications from the web application.
        /// </summary>
        /// <param name="webApp">The web application to remove the modifications from.</param>
        /// <param name="owner"Remove all modifications that belong to the owner></param>
        private void RemoveWebConfigModificationsByOwner(SPWebApplication webApp, string owner)
        {
            Collection <SPWebConfigModification> modificationCollection = webApp.WebConfigModifications;
            Collection <SPWebConfigModification> removeCollection       = new Collection <SPWebConfigModification>();

            int count = modificationCollection.Count;

            for (int i = 0; i < count; i++)
            {
                SPWebConfigModification modification = modificationCollection[i];
                if (modification.Owner == owner)
                {
                    // Collect modifications to delete.
                    removeCollection.Add(modification);
                }
            }

            // Delete the modifications from the web application.
            if (removeCollection.Count > 0)
            {
                foreach (SPWebConfigModification modificationItem in removeCollection)
                {
                    webApp.WebConfigModifications.Remove(modificationItem);
                }

                // Commit modification removals to the specified web application.
                webApp.Update();
                // Push modifications through the farm.
                webApp.WebService.ApplyWebConfigModifications();
            }
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            if (!webApp.IsAdministrationWebApplication)
            {
                Guid featureId = properties.Feature.DefinitionId;
                webApp.Features.Remove(featureId, true);
                webApp.Update();

                throw new SPException(string.Format(CultureInfo.InvariantCulture, "You can activate the feature with ID {0} on the Central Administration Web Application only!", featureId));
            }

            /*
             * else
             * {
             *  SPList list;
             *  SPWeb caWeb = webApp.Sites[0].OpenWeb();
             *  Guid guid = caWeb.Lists.Add("Hemrika License Files","", SPListTemplateType.DocumentLibrary);
             *  list = caWeb.Lists[guid];
             *  list.OnQuickLaunch = true;
             *  //list.Hidden = true;
             *  list.Update();
             * }
             */
        }
Пример #22
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                configurationproperties = properties.Feature.Properties;
                if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
                {
                    SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

                    //SPSite site = webApp.Sites.Where(p => p.ServerRelativeUrl.Equals("/", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    RemoveVirtualDirectory(webApp);

                    SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                    List <SPWebConfigModification> process = new List <SPWebConfigModification>();
                    process.AddRange(ZimbraWebConfigModification.Modifications);

                    foreach (SPWebConfigModification mod in process)
                    {
                        try
                        {
                            if (wap.WebConfigModifications.Contains(mod))
                            {
                                wap.WebConfigModifications.Remove(mod);
                            }

                            if (SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Contains(mod))
                            {
                                SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Remove(mod);
                            }
                        }
                        catch { };
                    }

                    try
                    {
                        wap.Update(false);
                        SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                        SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                        //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                        wap.WebConfigModifications.Clear();
                        wap.Update();
                    }
                    catch { };
                }
            });
        }
        private void ActivateHttpHandler_Robots(SPFeatureReceiverProperties properties)
        {
            if (webApp != null)
            {
                SPWebConfigModification mod =
                    new SPWebConfigModification(
                        "add[@type='Hemrika.SharePresence.WebSite.Robots.RobotsHandler, Hemrika.SharePresence.WebSite, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11e6604a27f32a11']",
                        "configuration/system.webServer/handlers");
                mod.Owner    = properties.Feature.DefinitionId.ToString();
                mod.Sequence = 0;
                mod.Type     = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                mod.Value    =
                    @"<add name=""RobotsHandler"" path=""robots.txt"" verb=""*"" type=""Hemrika.SharePresence.WebSite.Robots.RobotsHandler, Hemrika.SharePresence.WebSite, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11e6604a27f32a11"" />";
                if (!webApp.WebConfigModifications.Contains(mod))
                {
                    webApp.WebConfigModifications.Add(mod);
                }


                try
                {
                    SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);
                    webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                    //webApp.WebService.ApplyWebConfigModifications();
                    webApp.Update();
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }

                try
                {
                    webApp.BlockedFileExtensions.Remove("txt");
                    webApp.Update();
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            }

            //webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, "/_layouts/CustomErrorPages/AccessDenied.aspx");
        }
Пример #24
0
        private static void UpdateService(SPWebApplication app)
        {
            app.Update(true);
            SPWebService service = app.Farm.Services.GetValue <SPWebService>();

            //service.Update();
            service.ApplyWebConfigModifications();
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            return;

            bool   bApplyChanges = ApplyWebConfigMods(properties);
            SPSite currentSite   = properties.Feature.Parent as SPSite;

            if (bApplyChanges)
            {
                string sExpressionBuilderType =
                    string.Format("AlphaMosaik.SharePoint.ConfigurationStore.ConfigStoreExpressionBuilder, {0}",
                                  Assembly.GetExecutingAssembly().FullName);

                // add web.config entries..
                SPWebConfigModification siteEntry = addAppSetting(m_SiteUrlModification, m_AppSettingsXPath,
                                                                  m_ConfigSiteAppSettingsKey,
                                                                  currentSite.Url, 100);
                SPWebConfigModification webEntry = addAppSetting(m_WebNameModification, m_AppSettingsXPath,
                                                                 m_ConfigWebAppSettingsKey,
                                                                 string.Empty, 200);
                SPWebConfigModification listEntry = addAppSetting(m_ListNameModification, m_AppSettingsXPath,
                                                                  m_ConfigListAppSettingsKey,
                                                                  m_DefaultListName, 300);
                SPWebConfigModification cacheFileEntry = addAppSetting(m_CacheFileModification, m_AppSettingsXPath,
                                                                       m_CacheFileAppSettingsKey,
                                                                       m_CacheDependencyFile, 400);
                SPWebConfigModification expressionBuilderEntry = addExpressionBuilder(m_ExpressionBuilderModification,
                                                                                      m_ExpressionBuildersXPath,
                                                                                      m_ExpressionBuilderPrefix,
                                                                                      sExpressionBuilderType, 500);

                SPWebApplication currentWebApp = currentSite.WebApplication;
                currentWebApp.WebConfigModifications.Add(siteEntry);
                currentWebApp.WebConfigModifications.Add(listEntry);
                currentWebApp.WebConfigModifications.Add(webEntry);
                currentWebApp.WebConfigModifications.Add(cacheFileEntry);
                currentWebApp.WebConfigModifications.Add(expressionBuilderEntry);

                currentWebApp.WebService.ApplyWebConfigModifications();
                currentWebApp.Update();
            }

            // Déjà fait
            //// and also add list event receivers..
            //SPWeb rootWeb = currentSite.RootWeb;

            //SPList configStoreList = null;
            //try
            //{
            //    configStoreList = rootWeb.Lists[m_DefaultListName];
            //    addEventReceivers(configStoreList);
            //    configStoreList.Update();
            //}
            //catch
            //{
            //    // if we can't find the list we won't try and add event receivers..
            //}
        }
Пример #26
0
 public static void RemoveMapping(SPWebApplication webApp, SPUrlZone zone)
 {
     if (webApp == null)
     {
         return;
     }
     webApp.SiteDataServers.Remove(zone);
     webApp.Update();
 }
Пример #27
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            SPWebConfigModificationHelper.CleanUpWebConfigModifications(webApp, owner);

            webApp.Update();
            webApp.WebService.ApplyWebConfigModifications();
        }
        /// <summary>
        /// Method to add one or multiple WebConfig modifications
        /// NOTE: There should not have 2 modifications with the same Owner.
        /// </summary>
        /// <param name="webApp">The current Web Application</param>
        /// <param name="webConfigModificationCollection">The collection of WebConfig modifications to remove-and-add</param>
        /// <remarks>All SPWebConfigModification Owner should be UNIQUE !</remarks>
        public void AddAndCleanWebConfigModification(SPWebApplication webApp, Collection <SPWebConfigModification> webConfigModificationCollection)
        {
            // Verify emptyness
            if (webConfigModificationCollection == null || !webConfigModificationCollection.Any())
            {
                throw new ArgumentNullException("webConfigModificationCollection");
            }

            SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webApp.Id];

            // Start by cleaning up any existing modification for all owners
            foreach (var owner in webConfigModificationCollection.Select(modif => modif.Owner).Distinct())
            {
                // Remove all modification by the same owner.
                // By Good practice, owner should be unique, so we do this to remove duplicates entries if any.
                this.RemoveExistingModificationsFromOwner(webApplication, owner);
            }

            if (webApplication.Farm.TimerService.Instances.Count > 1)
            {
                // HACK:
                //
                // When there are multiple front-end Web servers in the
                // SharePoint farm, we need to wait for the timer job that
                // performs the Web.config modifications to complete before
                // continuing. Otherwise, we may encounter the following error
                // (e.g. when applying Web.config changes from two different
                // features in rapid succession):
                //
                // "A web configuration modification operation is already
                // running."
                WaitForOnetimeJobToFinish(
                    webApplication.Farm,
                    "Microsoft SharePoint Foundation Web.Config Update",
                    120);
            }

            // Add WebConfig modifications
            foreach (var webConfigModification in webConfigModificationCollection)
            {
                webApplication.WebConfigModifications.Add(webConfigModification);
            }

            // Commit modification additions to the specified web application
            webApplication.Update();

            // Push modifications through the farm
            webApplication.WebService.ApplyWebConfigModifications();

            if (webApplication.Farm.TimerService.Instances.Count > 1)
            {
                WaitForOnetimeJobToFinish(
                    webApplication.Farm,
                    "Microsoft SharePoint Foundation Web.Config Update",
                    120);
            }
        }
Пример #29
0
 public static void AddConfigModifications(SPWebApplication webApp, string owner, List <WebConfigManager> modifications)
 {
     foreach (WebConfigManager mod in modifications)
     {
         webApp.WebConfigModifications.Add(mod.GetModification(owner, 0));
     }
     webApp.WebService.ApplyWebConfigModifications();
     webApp.Update();
 }
Пример #30
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            ClubCloud.Common.RemoteAdministrator.Enable();

            FeatureCleaning(properties);

            if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
            {
                webApp = properties.Feature.Parent as SPWebApplication;
                SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                List <SPWebConfigModification> process = new List <SPWebConfigModification>();
                process.AddRange(ClubCloud.SignalR.SignalR.Modifications);

                foreach (SPWebConfigModification mod in process)
                {
                    try
                    {
                        if (!wap.WebConfigModifications.Contains(mod))
                        {
                            wap.WebConfigModifications.Add(mod);
                        }

                        if (!SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Contains(mod))
                        {
                            SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Add(mod);
                        }
                    }
                    catch { };
                }

                try
                {
                    wap.Update(false);
                    SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                    SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                    //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    wap.WebConfigModifications.Clear();
                    wap.Update(false);
                }
                catch { };
            }
        }
Пример #31
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);
            webApp.WebConfigModifications.Remove(WebSiteControllerWebConfigManager.GetHttpModuleEntry());
            webApp.WebConfigModifications.Remove(WebSiteControllerWebConfigManager.GetModuleEntry());
            webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
            webApp.Update();
        }
        public static void Install(SPWebApplication webApp)
        {
            foreach (var entry in AutofacConfigEntries)
            {
                webApp.WebConfigModifications.Add(entry.Prepare());
            }

            // set flag specifying, that DI of autofac is enabled on that site
            webApp.Properties[Constants.AUTOFAC_DI_ENABLED] = true;
            webApp.Update();
        }
        /// <summary>
        /// Uns the extend.
        /// </summary>
        /// <param name="webApp">The web app.</param>
        /// <param name="zone">The zone.</param>
        /// <param name="deleteIis">if set to <c>true</c> [delete IIS].</param>
        public static void UnExtend(SPWebApplication webApp, SPUrlZone zone, bool deleteIis)
        {
            webApp.UnprovisionGlobally(deleteIis);

            webApp.IisSettings.Remove(zone);
            if (zone != SPUrlZone.Default)
            {
                webApp.AlternateUrls.UnsetResponseUrl(zone);
                webApp.AlternateUrls.Update();
            }
            webApp.Update();
        }
        /// <summary>
        /// Adds the key/value pair as an appSettings entry in the web application's 
        /// SPWebConfigModification collection
        /// </summary>
        /// <param name="webApp">Current web application context</param>
        /// <param name="key">appSettings node key</param>
        /// <param name="value">appSettings node value</param>
        public void AddWebConfigNode(SPWebApplication webApp, string webConfigModxPath, XmlNode node, XmlAttributeCollection attributes)
        {
            SPWebConfigModification webConfigMod;
            string webConfigModName;

            webConfigModName = GetWebConfigModName(node.Name, attributes);
            webConfigMod = new SPWebConfigModification(webConfigModName, webConfigModxPath);
            webConfigMod.Owner = this.Owner;
            webConfigMod.Sequence = 0;
            webConfigMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            webConfigMod.Value = node.OuterXml;

            webApp.WebConfigModifications.Add(webConfigMod);
            webApp.Update();
        }
        public static void Uninstall(SPWebApplication webApp)
        {
            var modsCollection = webApp.WebConfigModifications;

            for (var i = modsCollection.Count - 1; i > -1; i--)
            {
                if (modsCollection[i].Owner == ConfigModsOwnerName)
                {
                    // Remove it and save the change to the configuration database  
                    modsCollection.Remove(modsCollection[i]);
                }
            }

            // remove flag
            if (webApp.Properties.ContainsKey(Constants.AUTOFAC_DI_ENABLED))
                webApp.Properties.Remove(Constants.AUTOFAC_DI_ENABLED);

            webApp.Update();
        }
        internal static void AddUserPolicy(string login, string username, string[] permissions, SPWebApplication webApp, SPPolicyCollection policies)
        {
            login = Utilities.TryGetNT4StyleAccountName(login, webApp);

            List<SPPolicyRole> roles = new List<SPPolicyRole>();
            foreach (string roleName in permissions)
            {
                SPPolicyRole role = webApp.PolicyRoles[roleName.Trim()];
                if (role == null)
                    throw new SPException(string.Format("The policy permission '{0}' was not found.", roleName.Trim()));

                roles.Add(role);
            }
            SPPolicy policy = policies.Add(login, username);

            foreach (SPPolicyRole role in roles)
                policy.PolicyRoleBindings.Add(role);

            webApp.Update();
        }
        private void DeployDefinition(WebApplicationModelHost modelHost, SPWebApplication webApp, WebConfigModificationDefinition definition)
        {
            var existingWebConfig = GetCurrentSPWebConfigModification(webApp, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = existingWebConfig,
                ObjectType = typeof(SPWebConfigModification),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            if (existingWebConfig != null)
                webApp.WebConfigModifications.Remove(existingWebConfig);

            existingWebConfig = new SPWebConfigModification();

            MapConfig(existingWebConfig, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = existingWebConfig,
                ObjectType = typeof(SPWebConfigModification),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            webApp.WebConfigModifications.Add(existingWebConfig);
            webApp.Update();

            //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            webApp.WebService.ApplyWebConfigModifications();
        }
        public void RemoveExistingModificationsFromOwner(SPWebApplication webApplication, IList<string> ownersOfModificationsToRemove)
        {
            if (webApplication == null)
            {
                throw new ArgumentNullException("webApplication");
            }

            var indicesOfNullWebConfigModifications = new List<int>();
            var modificationsToRemove = new Collection<SPWebConfigModification>();
            var modificationCollection = webApplication.WebConfigModifications;

            if (modificationCollection == null)
            {
                this.logger.Warn(
                    "WebConfigModificationHelper: Attempted to remove web.config modification from web app with ID {0} but no existing modification exists.",
                    webApplication.Id);
            }
            else
            {
                int currentIndex = 0;
                foreach (SPWebConfigModification modification in modificationCollection)
                {
                    if (modification != null)
                    {
                        if (!string.IsNullOrEmpty(modification.Owner))
                        {
                            if (ownersOfModificationsToRemove.Contains(modification.Owner))
                            {
                                // collect modifications to delete
                                modificationsToRemove.Add(modification);
                            }
                        }
                        else
                        {
                            this.logger.Warn(
                                "WebConfigModificationHelper: owner for existing modification {0} is empty. Cannot attempt removal.",
                                modification.Name);
                        }
                    }
                    else
                    {
                        indicesOfNullWebConfigModifications.Add(currentIndex);
                        this.logger.Warn(
                            "WebConfigModificationHelper: web application with ID {0} has a NULL modification.",
                            webApplication.Id);
                    }

                    currentIndex++;
                }

                // Now delete the modifications from the web application (and also clean up NULL values from web app's WebConfigModifications collection)
                if (modificationsToRemove.Count > 0 || indicesOfNullWebConfigModifications.Count > 0)
                {
                    var webAppConfigModifications = webApplication.WebConfigModifications;

                    if (indicesOfNullWebConfigModifications.Count > 0)
                    {
                        // WEIRD EDGE CASE: we detected NULL items in the web app's WebConfigModifications collection.
                        // Let's clean those up before moving on (otherwise further additions to the collection might fail
                        // to propagate correctly).
                        this.logger.Warn(
                                "WebConfigModificationHelper: web application with ID {0} has at least one NULL modification in its WebConfigModification collection. "
                                + "Attempting to delete those NULL entries now because they might interfere with new additions to WebConfigModifications.",
                                webApplication.Id);

                        foreach (int indexOfNullWebConfigModification in indicesOfNullWebConfigModifications)
                        {
                            webAppConfigModifications.RemoveAt(indexOfNullWebConfigModification);
                        }
                    }

                    // Remove the Owner's web config modification we want to clean up
                    foreach (SPWebConfigModification modificationItem in modificationsToRemove)
                    {
                        webAppConfigModifications.Remove(modificationItem);
                    }

                    // Commit modification removals to the specified web application
                    webApplication.Update();

                    if (webApplication.WebService == null)
                    {
                        throw new InvalidOperationException("Parent WebService of webApplication is unexpectedly NULL. Cannot attempt to ApplyWebConfigModifications.");
                    }

                    if (webApplication.Farm == null)
                    {
                        throw new InvalidOperationException("Parent Farm of webApplication is unexpectedly NULL. Cannot attempt to ApplyWebConfigModifications.");
                    }

                    // Push modifications through the farm
                    webApplication.WebService.ApplyWebConfigModifications();

                    // Wait for timer job 
                    try
                    {
                        WaitForWebConfigPropagation(webApplication.Farm);
                    }
                    catch (Exception exception)
                    {
                        this.logger.Fatal(
                            "WebConfigModificationHelper: Failed to wait for propagation of removal of web.config modification to all servers in the Farm. Exception: {0}",
                            exception.ToString());
                    }
                }
            }
        }
 protected void RemoveWebConfigEntries(SPWebApplication oWebApp, string owner)
 {
     Collection<SPWebConfigModification> webConfigModifications = oWebApp.WebConfigModifications;
     int num = webConfigModifications.Count;
     for (int i = num - 1; i >= 0; i--)
     {
         SPWebConfigModification modification = webConfigModifications[i];
         if (modification.Owner == owner)
         {
             webConfigModifications.Remove(modification);
         }
     }
     if (num > webConfigModifications.Count)
     {
         oWebApp.Update();
         SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
     }
 }
        /// <summary>
        /// Extends the web app.
        /// </summary>
        /// <param name="webApplication">The web application.</param>
        /// <param name="description">The description.</param>
        /// <param name="hostHeader">The host header.</param>
        /// <param name="port">The port.</param>
        /// <param name="loadBalancedUrl">The load balanced URL.</param>
        /// <param name="path">The path.</param>
        /// <param name="allowAnonymous">if set to <c>true</c> [allow anonymous].</param>
        /// <param name="useNtlm">if set to <c>true</c> [use NTLM].</param>
        /// <param name="useSsl">if set to <c>true</c> [use SSL].</param>
        /// <param name="zone">The zone.</param>
        public static void ExtendWebApp(SPWebApplication webApplication, string description, string hostHeader, int port, string loadBalancedUrl, string path, bool allowAnonymous, bool useNtlm, bool useSsl, SPUrlZone zone)
        {
            SPServerBinding serverBinding = null;
            SPSecureBinding secureBinding = null;
            if (!useSsl)
            {
                serverBinding = new SPServerBinding();
                serverBinding.Port = port;
                serverBinding.HostHeader = hostHeader;
            }
            else
            {
                secureBinding = new SPSecureBinding();
                secureBinding.Port = port;
            }

            SPIisSettings settings = new SPIisSettings(description, allowAnonymous, useNtlm, serverBinding, secureBinding, new DirectoryInfo(path.Trim()));
            settings.PreferredInstanceId = GetPreferredInstanceId(description);

            webApplication.IisSettings.Add(zone, settings);
            webApplication.AlternateUrls.SetResponseUrl(new SPAlternateUrl(new Uri(loadBalancedUrl), zone));
            webApplication.AlternateUrls.Update();
            webApplication.Update();
            webApplication.ProvisionGlobally();
        }
        private static void RemoveAllModifications(SPWebApplication application)
        {
            var modificationsToRemove = application.WebConfigModifications
                .Where(modification => modification.Owner == SPWebConfigModificationOwner)
                .ToList();

            foreach (var modification in modificationsToRemove)
            {
                application.WebConfigModifications.Remove(modification);
                application.Update();
            }
        }
        public void RemoveExistingModificationsFromOwner(SPWebApplication webApplication, string owner)
        {
            var removeCollection = new Collection<SPWebConfigModification>();
            var modificationCollection = webApplication.WebConfigModifications;

            int count = modificationCollection.Count;
            for (int i = 0; i < count; i++)
            {
                SPWebConfigModification modification = modificationCollection[i];
                if (modification.Owner == owner)
                {
                    // collect modifications to delete
                    removeCollection.Add(modification);
                }
            }

            // now delete the modifications from the web application
            if (removeCollection.Count > 0)
            {
                foreach (SPWebConfigModification modificationItem in removeCollection)
                {
                    webApplication.WebConfigModifications.Remove(modificationItem);
                }

                // Commit modification removals to the specified web application
                webApplication.Update();

                // Push modifications through the farm
                webApplication.WebService.ApplyWebConfigModifications();
            }
        }
        private static void ModifyWebConfig(SPWebApplication webApp, string name, string path, string value, SPWebConfigModification.SPWebConfigModificationType type)
        {
            if (AlreadyExists(webApp, name))
            {
                return;
            }

            var modification = new SPWebConfigModification(name, path)
                                   {
                                       Value = value,
                                       Sequence = 0,
                                       Type = type,
                                       Owner = SPWebConfigModificationOwner
                                   };

            try
            {
                webApp.WebConfigModifications.Add(modification);
                webApp.Update();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }