public void RemoveExistingModificationsFromOwner(SPWebApplication webApplication, IList<string> owners)
        {
            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 (owners.Contains(modification.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();
            }

            // Wait for timer job
            WaitForWebConfigPropagation(webApplication.Farm);
        }
 internal static void GetUrls(List<string> urls, SPWebApplication webApp)
 {
     foreach (SPAlternateUrl url in webApp.AlternateUrls)
     {
         GetUrls(urls, url);
     }
 }
        /// <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();
        }
        public virtual void RemoveConfigModifications(SPWebApplication WebApp, string Owner)
        {
            if (WebApp == null)
                throw new ArgumentException("WebApp is null, perhaps your feature is not scoped at WebApp level?", "WebApp");
            if (string.IsNullOrEmpty(Owner))
                throw new ArgumentException("Owner is null", "Owner");

            foreach (var mod in _modifications)
            {
                string message = string.Format("Removing Mod: {0}", mod.Path);
                _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", message);

                WebApp.WebConfigModifications.Remove(mod);
            }

            //WebApp.Update();
            //WebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

            _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", "Mods deleted, updating");
            SPWebService.ContentService.WebApplications[WebApp.Id].Update();
            _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", "Mods deleted, applying update");
            SPWebService.ContentService.WebApplications[WebApp.Id].WebService.ApplyWebConfigModifications();

            ForceRemoveConfigModifications(WebApp, Owner);
        }
        // We make absolutely sure no mods with this owner exist
        public void ForceRemoveConfigModifications(SPWebApplication WebApp, string Owner)
        {
            List<SPWebConfigModification> removeMods = new List<SPWebConfigModification>();
            foreach (var mod in WebApp.WebConfigModifications)
            {
                if (mod.Owner == Owner)
                {
                    removeMods.Add(mod);
                }
            }

            foreach (var mod in removeMods)
            {
                string message = string.Format("Removing additional owner based mod: {0}", mod.Path);
                _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", message);

                if (mod.Type != SPWebConfigModification.SPWebConfigModificationType.EnsureSection ||
                    (mod.Type == SPWebConfigModification.SPWebConfigModificationType.EnsureSection && !mod.Path.ToLower().Contains("system")))
                    WebApp.WebConfigModifications.Remove(mod);
                else
                {
                    string message2 = string.Format("Mod: {0} Type: {1} was not removed", mod.Path, mod.Type.ToString());
                    _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", message2);
                }
            }

            _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", "Mods deleted, updating");
            SPWebService.ContentService.WebApplications[WebApp.Id].Update();
            _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "WebConfigModificationHandler", "Info", "Mods deleted, applying update");
            SPWebService.ContentService.WebApplications[WebApp.Id].WebService.ApplyWebConfigModifications();
        }
Beispiel #6
0
        /// <summary>
        /// Flushes the BLOB cache for the specified Web Application.
        /// WARNING: This method needs to be run as Farm Admin and have security_admin SQL server role and the db_owner role
        /// on the web app's content DB in order to successfully flush the web app's BLOB cache.
        /// </summary>
        /// <param name="webApplication">The SharePoint web application.</param>
        public void FlushBlobCache(SPWebApplication webApplication)
        {
            try
            {
                PublishingCache.FlushBlobCache(webApplication);
            }
            catch (SPException exception)
            {
                this.logger.Error("Failed to flush the BLOB cache accross the web app. You need You need security_admin SQL server role and the db_owner role on the web app's content DB. Caught and swallowed exception: {0}", exception);
            }
            catch (AccessViolationException exception)
            {
                this.logger.Warn("Received an AccessViolationException when flushing BLOB Cache. Trying again with RemoteAdministratorAccessDenied set to true. Caught and swallowed exception: {0}", exception);

                bool initialRemoteAdministratorAccessDenied = true;
                SPWebService myService = SPWebService.ContentService;

                try
                {
                    initialRemoteAdministratorAccessDenied = myService.RemoteAdministratorAccessDenied;
                    myService.RemoteAdministratorAccessDenied = false;
                    myService.Update();

                    PublishingCache.FlushBlobCache(webApplication);
                }
                finally
                {
                    myService.RemoteAdministratorAccessDenied = initialRemoteAdministratorAccessDenied;
                    myService.Update();
                }
            }
        }
        protected SPContentDatabase GetCurrentContentDatabase(SPWebApplication webApp, ContentDatabaseDefinition definition)
        {
            var dbName = definition.DbName.ToUpper();

            return webApp.ContentDatabases.OfType<SPContentDatabase>()
                                          .FirstOrDefault(d => !string.IsNullOrEmpty(d.Name) && d.Name.ToUpper() == dbName);
        }
        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
            });
        }
        /// <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);
        }
 private static void DeleteJob(SPWebApplication application, string jobName)
 {
     var job = application.JobDefinitions.SingleOrDefault(c => jobName == c.Name);
     if (job != null)
     {
         job.Delete();
     }
 }
Beispiel #11
0
 public FeatureCollectionNode(SPWebApplication webApp)
     : this()
 {
     this.Text = SPMLocalization.GetString("SiteFeatures_Text");
     this.ToolTipText = SPMLocalization.GetString("SiteFeatures_ToolTip");
     this.Name = "SiteFeatures";
     this.Tag = webApp.Features;
     this.SPParent = webApp;
 }
Beispiel #12
0
 public IisSettingNode(SPWebApplication app, KeyValuePair<SPUrlZone, SPIisSettings> iisSettings)
 {
     this.Tag = iisSettings.Value;
     this.Name = iisSettings.Key.ToString();
     this.Text = iisSettings.Key.ToString();
     this.ToolTipText = iisSettings.Key.ToString();
     this.BrowserUrl = app.GetResponseUri(iisSettings.Key).ToString();
     this.Setup();
 }
        /// <summary>
        /// Method to add one or multiple WebConfig modifications
        /// NOTE: There should not have 2 modifications with the same Owner.
        /// </summary>
        /// <param name="web">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);
            }
        }
        protected SPAlternateUrl GetCurrentAlternateUrl(SPWebApplication webApp, AlternateUrlDefinition definition)
        {
            var alternateUrls = webApp.AlternateUrls;

            var url = definition.Url;
            var urlZone = (SPUrlZone)Enum.Parse(typeof(SPUrlZone), definition.UrlZone);

            return alternateUrls.GetResponseUrl(urlZone);
        }
 private void RemoveTimerJobs(SPWebApplication webApp)
 {
     foreach (SPJobDefinition job in webApp.JobDefinitions)
     {
         if (job.Name == GlymaExportWorkItemTimerJob.JobName)
         {
             job.Delete();
         }
     }
 }
Beispiel #16
0
        public WebApplicationNode(SPWebService service, SPWebApplication app)
        {
            this.SPParent = service;
            this.Tag = app;
            this.DefaultExpand = true;

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
 private void RemoveJobIfRegistered(SPWebApplication app)
 {
     foreach (SPJobDefinition job in app.JobDefinitions)
     {
         if (job.Title == JobName)
         {
             job.Delete();
         }
     }
 }
        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();
        }
 public static string SafeGetWebAppUrl(SPWebApplication webApp)
 {
     try
     {
         return GetWebAppUrl(webApp);
     }
     catch
     {
         return null;
     }
 }
 public static string SafeGetWebAppTitle(SPWebApplication webApp)
 {
     try
     {
         return webApp.Name;
     }
     catch
     {
         return null;
     }
 }
        /// <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();
        }
 private static void RegisterHttpHandlerFactory(SPWebApplication webApp)
 {
     var httpHandlerType = typeof(IronHttpHandler);
     SPWebConfigModification httpHandlerFacotry = new SPWebConfigModification();
     httpHandlerFacotry.Path = "configuration/system.webServer/handlers";
     httpHandlerFacotry.Name = String.Format("add[@type='{0}']", httpHandlerType.AssemblyQualifiedName);
     httpHandlerFacotry.Sequence = 0;
     httpHandlerFacotry.Owner = modificationOwner;
     httpHandlerFacotry.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
     httpHandlerFacotry.Value = String.Format("<add  name='IronHttpHandler' path='_iron/*' verb='*' type='{0}' />", httpHandlerType.AssemblyQualifiedName);
     webApp.WebConfigModifications.Add(httpHandlerFacotry);
 }
 private static void RegisterHttpModule(SPWebApplication webApp)
 {
     var httpModuleType = typeof(IronHttpModule);
     SPWebConfigModification httpModuleMod = new SPWebConfigModification();
     httpModuleMod.Path = "configuration/system.webServer/modules";
     httpModuleMod.Name = String.Format("add[@name='IronHttpModule'][@type='{0}']", httpModuleType.AssemblyQualifiedName);
     httpModuleMod.Sequence = 0;
     httpModuleMod.Owner = modificationOwner;
     httpModuleMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
     httpModuleMod.Value = String.Format("<add name='IronHttpModule' type='{0}' />", httpModuleType.AssemblyQualifiedName);
     webApp.WebConfigModifications.Add(httpModuleMod);
 }
Beispiel #24
0
        protected SPSite GetExistingSite(SPWebApplication webApp, SiteDefinition definition)
        {
            var siteCollectionUrl = SPUrlUtility.CombineUrl(definition.PrefixName, definition.Url);

            if (siteCollectionUrl.StartsWith("/"))
                siteCollectionUrl = siteCollectionUrl.Substring(1, siteCollectionUrl.Length - 1);

            if (webApp.Sites.Names.Contains(siteCollectionUrl))
                return webApp.Sites[siteCollectionUrl];

            return null;
        }
 private static void RegisterExpressionBuilder(SPWebApplication webApp)
 {
     var expressionBuilderType = typeof(IronExpressionBuilder);
     SPWebConfigModification expressionBuilderMod = new SPWebConfigModification();
     expressionBuilderMod.Path = "configuration/system.web/compilation/expressionBuilders";
     expressionBuilderMod.Name = String.Format("add[@expressionPrefix='Iron'][@type='{0}']", expressionBuilderType.AssemblyQualifiedName);
     expressionBuilderMod.Sequence = 0;
     expressionBuilderMod.Owner = modificationOwner;
     expressionBuilderMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
     expressionBuilderMod.Value = String.Format("<add expressionPrefix='Iron' type='{0}' />", expressionBuilderType.AssemblyQualifiedName);
     webApp.WebConfigModifications.Add(expressionBuilderMod);
 }
        public IisSettingsCollectionNode(SPWebApplication app)
        {
            this.Text = SPMLocalization.GetString("IisSettings_Text");
            this.ToolTipText = SPMLocalization.GetString("IisSettings_ToolTip");
            this.Name = "Iis settings";
            this.Tag = app.IisSettings;
            this.WebApplication = app;
            this.ImageIndex = 2;
            this.SelectedImageIndex = 2;

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        /// <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 string getConnectionString(SPWebApplication webApp)
        {
            string conString; string connectionStringKey = "OoyalaConnectionString";
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/",webApp.Name);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(config.FilePath);

            XmlNodeList list = xmlDoc.DocumentElement.SelectNodes(string.Format("appSettings/add[@key='{0}']", connectionStringKey));
            XmlNode node;

            node = list[0];
            conString=node.Attributes["value"].Value;

            return conString;
        }
Beispiel #29
0
        /// <summary>
        /// Ensures the BLOB cache is enabled or disabled in the specified Web Application.
        /// This method Updates the web application web.config file in order to enable or disable BLOB Cache.
        /// </summary>
        /// <param name="webApplication">The SharePoint web application.</param>
        /// <param name="enabled">Enable or disable the BLOB Cache.</param>
        public void EnsureBlobCache(SPWebApplication webApplication, bool enabled)
        {
            SPWebConfigModification modification = new SPWebConfigModification();
            modification.Path = "configuration/SharePoint/BlobCache";
            modification.Name = "enabled";
            modification.Value = enabled ? "true" : "false";
            modification.Sequence = 0;
            modification.Owner = "Dynamite-BlobCache";
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;

            var modifications = new Collection<SPWebConfigModification>();
            modifications.Add(modification);

            this.webConfigModificationHelper.AddAndCleanWebConfigModification(webApplication, modifications);
        }
 public static void CleanUpWebConfigModifications(SPWebApplication webApp, string owner)
 {
     Validation.ArgumentNotNull(webApp, "webApp");
     List<SPWebConfigModification> toBeDeleted = new List<SPWebConfigModification>();
     foreach (SPWebConfigModification spWebConfigModification in webApp.WebConfigModifications)
     {
         if (spWebConfigModification.Owner == owner)
         {
             toBeDeleted.Add(spWebConfigModification);
         }
     }
     foreach (SPWebConfigModification configModification in toBeDeleted)
     {
         webApp.WebConfigModifications.Remove(configModification);
     }
 }
Beispiel #31
0
        public void TraverseActivateFeaturesInWebApplication(SPWebApplication webapp)
        {
            ActivateFeaturesInWebApp(webapp);

            if (_featureset.SiteCollectionFeatureCount == 0 &&
                _featureset.WebFeatureCount == 0)
            {
                return;
            }

            foreach (SPSite site in webapp.Sites)
            {
                try
                {
                    TraverseActivateFeaturesInSiteCollection(site);
                }
                finally
                {
                    site.Dispose();
                }
            }
        }
Beispiel #32
0
        private void setProperty(string value, string Property)
        {
            SPWebApplication webApp = this.Selector.CurrentItem;

            if (webApp == null)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, "Cannot find WebApplication by id '{0}'", this.Selector.CurrentId);

                throw new FileNotFoundException(msg);
            }
            try
            {
                webApp.Properties[Property] =
                    value;
                webApp.Update();
                this.LabelMessage.Text += "Property " + Property + " has been successfully stored. ";
            }
            catch (Exception ex)
            {
                this.LabelMessage.Text += "Error while storing properties. Message: " + ex.Message + " ";
            }
        }
        // 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("SignalR"))
                        {
                            toDelete.Add(mod);
                            found = true;
                        }
                    }

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

                    wap.Update();
                    SPWebService.ContentService.WebApplications[wap.Id].Update();
                    SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                }
                catch { found = true; }
                finally { toDelete = new List <SPWebConfigModification>(); }

                if (found)
                {
                    FeatureUninstalling(properties);
                }
            }
        }
        public void ModifyWebConfigEntries(SPWebApplication oWebApp)
        {
            //SPWebConfigModification webConfigModifications = new SPWebConfigModification();

            //webConfigModifications.Path = "configuration/system.web/httpModules";
            //webConfigModifications.Name = "add[@name='CustomHttpModule']";
            //webConfigModifications.Sequence = 0;
            //webConfigModifications.Owner = "addCustomModule";


            //webConfigModifications.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            ////webConfigModifications.Value = @"<add name='CustomHttpModule' type='ClassName,AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cfba5cfbc4661d2d' />";
            //webConfigModifications.Value = string.Format("<add name='CustomHttpModule' type='SPGuysCustomFieldPermissionLibrary.RedirectModule,SPGuysCustomFieldPermissionLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a8a8bdc8ce8bd55f' />");
            //oWebApp.WebConfigModifications.Add(webConfigModifications);



            ////SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            //SPWebService.ContentService.WebApplications[oWebApp.Id].Update();
            ////Applies the web config settings in all the web application in the farm
            //SPWebService.ContentService.WebApplications[oWebApp.Id].WebService.ApplyWebConfigModifications();
        }
Beispiel #35
0
 private void EnumerateWebAppSites(SPWebApplication webApp)
 {
     foreach (SPSite site in webApp.Sites)
     {
         using (site)
         {
             // check site
             try
             {
                 CheckSite(site);
                 if (stopAtFirstHit && activationsFound > 0)
                 {
                     return;
                 }
             }
             catch (Exception exc)
             {
                 OnException(exc,
                             "Exception checking site: " + LocationManager.SafeGetSiteAbsoluteUrl(site)
                             );
             }
             // check subwebs
             try
             {
                 EnumerateSiteWebs(site);
                 if (stopAtFirstHit && activationsFound > 0)
                 {
                     return;
                 }
             }
             catch (Exception exc)
             {
                 OnException(exc,
                             "Exception enumerating webs of site: " + LocationManager.SafeGetSiteAbsoluteUrl(site)
                             );
             }
         }
     }
 }
Beispiel #36
0
        private ClaimsContext(SPContext context)
        {
            SPWebApplication webApplication = context.Site.WebApplication;

            foreach (SPAlternateUrl mapping in webApplication.AlternateUrls)
            {
                SPIisSettings settings = webApplication.GetIisSettingsWithFallback(mapping.UrlZone);
                if (settings.UseFormsClaimsAuthenticationProvider)
                {
                    this.FormsMembershipProvider = Membership.Providers[settings.FormsClaimsAuthenticationProvider.MembershipProvider];
                    this.FormsRoleProvider       = Roles.Providers[settings.FormsClaimsAuthenticationProvider.RoleProvider];
                    break;
                }
            }

            SPUser currentUser = context.Web.CurrentUser;

            if (currentUser != null && SPClaimProviderManager.IsEncodedClaim(currentUser.LoginName))
            {
                SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(currentUser.LoginName);
                this.IsWindowsUser = claim.OriginalIssuer == "Windows";

                if (claim.OriginalIssuer.StartsWith("Forms:"))
                {
                    if (this.FormsMembershipProvider != null && this.FormsMembershipProvider.Name.Equals(claim.OriginalIssuer.Substring(6), StringComparison.OrdinalIgnoreCase))
                    {
                        this.FormsUser = this.FormsMembershipProvider.GetUser(claim.Value, false);
                        if (this.FormsUser != null)
                        {
                            this.IsFormsUser      = true;
                            this.FormsUserId      = claim.Value;
                            this.FormsUserProfile = ProfileBase.Create(this.FormsUser.UserName);
                        }
                    }
                }
            }
            this.IsAnonymous = !this.IsFormsUser && !this.IsWindowsUser;
        }
        protected void Selector_ContextChange(object sender, EventArgs e)
        {
            app = webAppSelector.CurrentItem;
            HidVirtualServerUrl.Value = app.AlternateUrls[0].Uri.ToString().TrimEnd("/".ToCharArray());
            foreach (SPPrefix pref in app.Prefixes)
            {
                if (pref.PrefixType == SPPrefixType.ExplicitInclusion)
                {
                    try
                    {
                        using (SPSite site = new SPSite(HidVirtualServerUrl.Value + pref.Name))
                        { }
                    }
                    catch
                    {
                        DdlWildcardInclusion.Items.Add(new ListItem("/" + pref.Name, "1:/" + pref.Name));
                    }
                }
                else
                {
                    DdlWildcardInclusion.Items.Add(new ListItem("/" + pref.Name + "/", "0:/" + pref.Name + "/"));
                }
            }
            PickerOwner.WebApplicationId = webAppSelector.CurrentItem.Id;

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

            siteCollections.Add("(none)");
            foreach (SPSite site in app.Sites)
            {
                if (site.HostHeaderIsSiteName && site.PrimaryUri.AbsolutePath == "/")
                {
                    siteCollections.Add(site.Url);
                }
            }
            ddlSiteCollections.DataSource = siteCollections;
            ddlSiteCollections.DataBind();
        }
    /// <summary>
    /// Creates a SharePoint site collection, if it doesn't already exist.
    /// </summary>
    ///
    /// <param name="siteCollectionUrl">The URL of the site collection to create.</param>
    ///
    /// <param name="title">The title of the root Web site, of the new site collection, e.g.
    ///     "SLK Sample Web Site".  Not used if the site collection exists already.</param>
    ///
    static void CreateSiteCollection(string siteCollectionUrl, string title)
    {
        Console.WriteLine("Finding or creating site collection \"{0}\"", siteCollectionUrl);

        // set <loginName> to the "domain\login-name" of the current user
        string loginName;

        using (WindowsIdentity currentUser = WindowsIdentity.GetCurrent())
            loginName = currentUser.Name;

        // quit if the site collection already exists
        try
        {
            using (SPSite spSite = new SPSite(siteCollectionUrl))
            {
                // site collection exists -- quit
                Console.WriteLine("...exists already");
                return;
            }
        }
        catch (FileNotFoundException)
        {
            // site collection doesn't exist -- create it below
        }

        // create the site collection
        SPWebApplication webApp = SPWebApplication.Lookup(new Uri(siteCollectionUrl));

        using (SPSite spSite = webApp.Sites.Add(siteCollectionUrl, loginName, String.Empty))
        {
            using (SPWeb spWeb = spSite.RootWeb)
            {
                spWeb.Title = title;
                spWeb.Update();
            }
            Console.WriteLine("...created");
        }
    }
        public void CanGetActivatedFeatureFromWebApp()
        {
            // Arrange
            var parentScope = SPFeatureScope.WebApplication;
            var parentUrl   = TestContent.SharePointContainers.WebApplication.Url;

            using (SPSite site = new SPSite(TestContent.SharePointContainers.SiCoInActive.Url))
            {
                SPWebApplication parent = site.WebApplication;

                // Act

                var testFeatureHealthy = parent.Features[TestContent.TestFeatures.HealthyWebApp.Id];
                // web app features cannot easily be reproduced in faulty state
                // var testFeatureFaulty = parent.Features[TestContent.TestFeatures.FaultyWebApp.Id];

                var featureParent = FeatureParent.GetFeatureParent(parent);


                var sharePointFeatureHealthy = ActivatedFeature.GetActivatedFeature(testFeatureHealthy);
                var sharePointFeatureRetrievedWithParentHealthy = ActivatedFeature.GetActivatedFeature(testFeatureHealthy, featureParent);

                // Assert
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Id, sharePointFeatureHealthy.Id);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Name, sharePointFeatureHealthy.Name);
                Assert.Equal(featureParent.Url, sharePointFeatureHealthy.Parent.Url);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Version, sharePointFeatureHealthy.Version);
                Assert.Equal(parentScope, sharePointFeatureHealthy.Scope);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Faulty, sharePointFeatureHealthy.Faulty);

                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Id, sharePointFeatureRetrievedWithParentHealthy.Id);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Name, sharePointFeatureRetrievedWithParentHealthy.Name);
                Assert.Equal(featureParent.Url, sharePointFeatureRetrievedWithParentHealthy.Parent.Url);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Version, sharePointFeatureRetrievedWithParentHealthy.Version);
                Assert.Equal(parentScope, sharePointFeatureRetrievedWithParentHealthy.Scope);
                Assert.Equal(TestContent.TestFeatures.HealthyWebApp.Faulty, sharePointFeatureRetrievedWithParentHealthy.Faulty);
            }
        }
        /// <summary>
        /// Gets the rules from config DB.
        /// </summary>
        /// <returns>The WebSiteControllerRules</returns>
        private static WebSiteControllerConfig GetFromConfigDB()
        {
            if (!Exists())
            {
                CreateInConfigDB();
            }

            if (WebApp == null && HttpContext.Current != null)
            {
                SPSite site = new SPSite(HttpContext.Current.Request.Url.OriginalString);
                WebApp = site.WebApplication;
            }

            if (WebApp != null && WebApp != SPAdministrationWebApplication.Local)
            {
                return(WebApp.GetChild <WebSiteControllerConfig>(OBJECTNAME));
            }
            else
            {
                return(null);
                //return SPFarm.Local.GetObject(ID) as WebSiteControllerConfig;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Webapp"></param>
        /// <param name="url"></param>
        /// <param name="ruleType"></param>
        /// <returns></returns>
        public static bool HasRule(SPWebApplication Webapp, Uri url, string ruleType)
        {
            WebSiteControllerRulesCollection rules = GetFromConfigDB().rules;

            foreach (WebSiteControllerRule rule in rules)
            {
                try
                {
                    if (rule.RuleType == ruleType && rule.Url == url.ToString())
                    {
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            }

            return(false);
            //return GetFromConfigDB().rules[name];
        }
Beispiel #42
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication adminWebApplication = properties.Feature.Parent as SPWebApplication;

            foreach (SPJobDefinition job in adminWebApplication.JobDefinitions)
            {
                if (job.Name == tJobName)
                {
                    job.Delete();
                }
            }

            if (((SPWebApplication)properties.Feature.Parent).IsAdministrationWebApplication)
            {
                Nauplius.ADLDS.UserProfiles.ADLDSImportJob newTimerJob = new Nauplius.ADLDS.UserProfiles.ADLDSImportJob(tJobName, adminWebApplication);

                SPHourlySchedule jobSchedule = new SPHourlySchedule();
                jobSchedule.BeginMinute = 0;
                jobSchedule.EndMinute   = 59;
                newTimerJob.Schedule    = jobSchedule;
                newTimerJob.Update();
            }
        }
Beispiel #43
0
        public static FeatureParent GetFeatureParent(SPWebApplication webApp, string name = "")
        {
            try
            {
                if (webApp == null)
                {
                    return(GetFeatureParentUndefined());
                }

                var p = new FeatureParent()
                {
                    DisplayName = string.IsNullOrEmpty(name) ? webApp.Name : name,  // + " (" + web.Name + ")",
                    Url         = webApp.GetResponseUri(SPUrlZone.Default).ToString(),
                    Id          = webApp.Id,
                    Scope       = SPFeatureScope.WebApplication
                };
                return(p);
            }
            catch (Exception ex)
            {
                return(GetFeatureParentUndefined(ex.Message));
            }
        }
Beispiel #44
0
        private static void ModifyWebConfig(SPWebApplication webApp, string modificationName, string modificationPath,
                                            string modificationValue, SPWebConfigModification.SPWebConfigModificationType modificationType)
        {
            SPWebConfigModification modification = new SPWebConfigModification(modificationName, modificationPath);

            modification.Value    = modificationValue;
            modification.Sequence = 0;
            modification.Type     = modificationType;
            modification.Owner    = ModificationOwner;

            try
            {
                webApp.WebConfigModifications.Add(modification);
                webApp.Update();
            }
            catch (Exception ex)
            {
                EventLog eventLog = new EventLog();
                eventLog.Source = ModificationOwner;
                eventLog.WriteEntry(ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// Adds the managed path.
        /// </summary>
        /// <param name="targetUrl">The target URL.</param>
        /// <param name="haltOnWarning">if set to <c>true</c> [halt on warning].</param>
        private static void AddManagedPath(string targetUrl, bool haltOnWarning)
        {
            string serverRelUrlFromFullUrl = Utilities.GetServerRelUrlFromFullUrl(targetUrl);

            serverRelUrlFromFullUrl = serverRelUrlFromFullUrl.Trim(new char[] { '/', '*' });

            SPWebApplication   webApp           = SPWebApplication.Lookup(new Uri(targetUrl));
            SPPrefixCollection prefixCollection = webApp.Prefixes;

            if (prefixCollection.Contains(serverRelUrlFromFullUrl))
            {
                if (haltOnWarning)
                {
                    throw new SPException("Managed path already exists.");
                }
                else
                {
                    Logger.WriteWarning("Managed path already exists.");
                }
                return;
            }
            prefixCollection.Add(serverRelUrlFromFullUrl, SPPrefixType.ExplicitInclusion);
        }
        public static void EnsureChildNode(SPWebApplication webApp)
        {
            string connectionStringKey   = "OoyalaConnectionString";
            string connectionStringvalue = OoyalaConnectStringBuilder.BuildConnectionString();

            string fileTypeKey   = "OoyalaFileType";
            string fileTypeValue = InstallConfiguration.OoyalaFileType;

            string fileUploadLimitKey   = "OoyalaFileUploadLimitInMB";
            string fileUploadLimitValue = InstallConfiguration.OoyalaFileUploadLimitInMB;

            Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApp.Name);

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(config.FilePath);

            xmlDoc = AddOrModifyAppSettings(xmlDoc, connectionStringKey, connectionStringvalue);
            xmlDoc = AddOrModifyAppSettings(xmlDoc, fileTypeKey, fileTypeValue);
            xmlDoc = AddOrModifyAppSettings(xmlDoc, fileUploadLimitKey, fileUploadLimitValue);

            xmlDoc.Save(config.FilePath);
        }
Beispiel #47
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

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

            RemoveAllCustomisations(webApp);

            #region Enable session state

            SPWebConfigModification httpRuntimeModification = new SPWebConfigModification();
            httpRuntimeModification.Path     = "configuration/system.webServer/modules";
            httpRuntimeModification.Name     = "add[@name='ExcelWebAppRedirecter']";
            httpRuntimeModification.Sequence = 0;
            httpRuntimeModification.Owner    = "SPExcelWebAppRedirecter";
            httpRuntimeModification.Type     = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            httpRuntimeModification.Value    = "<add name=\"ExcelWebAppRedirecter\" type=\"ExcelWebAppRedirecter.Redirecter, ExcelWebAppRedirecter, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ab1b281a9b9b52f9\" />";
            webApp.WebConfigModifications.Add(httpRuntimeModification);

            #endregion

            /*Call Update and ApplyWebConfigModifications to save changes*/
            webApp.Update();
            webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
        }
Beispiel #48
0
/*
 *      private void ReportWebFeatureActivations()
 *      {
 *          IList<WebLoc> featuredWebs = InstallProcessControl.GetFeaturedWebs();
 *
 *          myList.View = View.Details;
 *          myList.Columns.Clear();
 *          myList.Columns.Add("WebApp", 100);
 *          myList.Columns.Add("Site Collection", 100);
 *          myList.Columns.Add("Site", 150);
 *          if (InstallConfiguration.FeatureId.Count > 1)
 *          {
 *              myList.Columns.Add("#Features", 50);
 *          }
 *
 *          foreach (WebLoc webloc in featuredWebs)
 *          {
 *              try
 *              {
 *                  using (SPSite site = new SPSite(webloc.siteInfo.SiteId))
 *                  {
 *                      string webappName = GetWebAppName(site.WebApplication);
 *                      ListViewItem item = new ListViewItem(webappName);
 *                      item.SubItems.Add(site.RootWeb.Title);
 *                      using (SPWeb web = site.OpenWeb(webloc.WebId))
 *                      {
 *                          item.SubItems.Add(web.Title);
 *                      }
 *                      if (InstallConfiguration.FeatureId.Count > 1)
 *                      {
 *                          item.SubItems.Add(string.Format("{0}/{1}", webloc.featureList.Count, InstallConfiguration.FeatureId.Count));
 *                      }
 *                      myList.Items.Add(item);
 *                  }
 *              }
 *              catch (Exception exc)
 *              {
 *                  myList.Items.Add("Exception(" + webloc.siteInfo.SiteId.ToString() + "," + webloc.WebId.ToString() + "): " + exc.Message);
 *              }
 *          }
 *      }
 * */
        public static string GetWebAppName(SPWebApplication webapp)
        {
            string name = webapp.Name;

            if (!String.IsNullOrEmpty(name))
            {
                return(name);
            }
            if (webapp.AlternateUrls.Count > 0)
            {
                name = webapp.AlternateUrls[0].IncomingUrl;
                if (!String.IsNullOrEmpty(name))
                {
                    return("(" + name + ")");
                }
            }
            name = webapp.DefaultServerComment;
            if (!String.IsNullOrEmpty(name))
            {
                return("(" + name + ")");
            }
            return(webapp.Id.ToString());
        }
Beispiel #49
0
        private void CreateJob(SPWebApplication site)
        {
            DateTime start = DateTime.Now.AddMinutes(-10);
            DateTime end   = start.AddMinutes(5);
            var      job   = new SSRSSyncTimerJob(JobName, site)
            {
                Schedule = new SPYearlySchedule()
                {
                    BeginMonth  = start.Month,
                    BeginDay    = start.Day,
                    BeginHour   = start.Hour,
                    BeginMinute = start.Minute,
                    BeginSecond = 0,
                    EndMonth    = end.Month,
                    EndDay      = end.Day,
                    EndHour     = end.Hour,
                    EndMinute   = end.Minute,
                    EndSecond   = end.Second
                }
            };

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


                try
                {
                    wap.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, 15, "/_layouts/ClubCloud/Common/403.aspx");
                    //webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Confirmation, "");
                    wap.UpdateMappedPage(SPWebApplication.SPCustomPage.Error, 15, "/_layouts/ClubCloud/Common/500.aspx");
                    wap.UpdateMappedPage(SPWebApplication.SPCustomPage.None, 15, "/_layouts/ClubCloud/Common/404.aspx");
                    //webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.RequestAccess, "");
                    //webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Signout, "");
                    wap.UpdateMappedPage(SPWebApplication.SPCustomPage.WebDeleted, 15, "/_layouts/ClubCloud/Common/404.aspx");
                    wap.Update(false);
                    SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                }
                catch { }
            }
        }
        //Função cria o TimerJob
        private bool CreateJob(SPWebApplication site)
        {
            bool jobCreated = false;

            try
            {
                Empresa.setor.TimerJob.TimerJob.TimerJobSolicitacoes job = new Empresa.setor.TimerJob.TimerJob.TimerJobSolicitacoes(JobName, site);

                //A cada hora exe
                SPHourlySchedule schedule = new SPHourlySchedule();
                schedule.BeginMinute = 1;
                schedule.EndMinute   = 5;

                job.Schedule = schedule;

                job.Update();
            }
            catch (Exception)
            {
                return(jobCreated);
            }
            return(jobCreated);
        }
        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = (SPWebApplication)Parent;

            SPSite trainingSite           = webApp.Sites[""];
            SPWeb  rootWeb                = trainingSite.AllWebs["/trainings"];
            SPList trainersList           = rootWeb.Lists["Trainers"];
            SPListItemCollection trainers = trainersList.Items;

            foreach (SPListItem trainer in trainers)
            {
                SPField emailField    = trainer.Fields.GetFieldByInternalName("Email");
                SPField fullNameField = trainer.Fields.GetFieldByInternalName("FullName");
                //string email = trainer[emailField.Id].ToString();
                string fullName = trainer[fullNameField.Id].ToString();

                SPList classes = rootWeb.Lists["Classes"];
                var    query   = new SPQuery();
                query.ViewFields = "<FieldRef Name='Trainer'/> <FieldRef Name='Venue'/> <FieldRef Name='StartDate'/> <FieldRef Name='_EndDate'/> <FieldRef Name='Registrations' />";
                query.Query      = "<Where><And><Eq><FieldRef Name='Trainer' /><Value Type='Lookup'>" + fullName + "</Value></Eq><Geq><FieldRef Name='StartDate'/><Value Type='DateTime'><Today /></Value></Geq></And></Where>";
                SPListItemCollection classesForTrainer = classes.GetItems(query);
            }
        }
Beispiel #53
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Server.ScriptTimeout = 300;

            try
            {
                SPWebApplication webapp = SPWebService.ContentService.WebApplications[new Guid(Request["WEBAPP"])];

                System.Collections.ObjectModel.Collection <SPWebApplication> apps = new System.Collections.ObjectModel.Collection <SPWebApplication>();
                apps.Add(webapp);

                SPFarm farm = SPFarm.Local;

                Install(new Guid("55aca119-d7c7-494a-b5a7-c3ade07d06eb"), farm, apps); // Core
                Install(new Guid("98e5c373-e1a0-45ce-8124-30c203cd8003"), farm, apps); // WebParts
                Install(new Guid("1858d521-0375-4a61-9281-f5210854bc12"), farm, apps); // Timesheets
                Install(new Guid("8f916fa9-1c2d-4416-8036-4a272256e23d"), farm, apps); // Dashboards
                Install(new Guid("5a3fe24c-2dc5-4a1c-aec1-6ce942825ceb"), farm, apps); // PFE
                Install(new Guid("171917a9-ea5c-49ec-b144-434a45222fc2"), farm, apps); // SP Forms
            }
            catch (Exception ex) { output = "Failed: " + ex.Message; return; }
            output = "Success";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Server.ScriptTimeout = 300;

            try
            {
                SPWebApplication webapp = SPWebService.ContentService.WebApplications[new Guid(Request["WEBAPP"])];

                System.Collections.ObjectModel.Collection <SPWebApplication> apps = new System.Collections.ObjectModel.Collection <SPWebApplication>();
                apps.Add(webapp);

                SPFarm farm = SPFarm.Local;

                Remove(new Guid("55aca119-d7c7-494a-b5a7-c3ade07d06eb"), farm, apps); // Core
                Remove(new Guid("98e5c373-e1a0-45ce-8124-30c203cd8003"), farm, apps); // WebParts
                Remove(new Guid("1858d521-0375-4a61-9281-f5210854bc12"), farm, apps); // Timesheets
                //Remove(new Guid("160f5e32-b93f-4682-95bc-6db38233535a"), farm, apps); //Old Dashboards solution
                Remove(new Guid("8f916fa9-1c2d-4416-8036-4a272256e23d"), farm, apps); //Dashboards
                Remove(new Guid("5a3fe24c-2dc5-4a1c-aec1-6ce942825ceb"), farm, apps); // PFE
            }
            catch (Exception ex) { output = "Failed: " + ex.Message; return; }
            output = "Success";
        }
        public override void LoadSettings(SPWebApplication webApp)
        {
            throw new NotImplementedException();
            //string enabledAsString;

            //if (ConfManager.TryGetSetting(webApp, Properties.Settings.Default.Settings_Storage_SpTraceLogProvider_Enabled, out enabledAsString))
            //{
            //    bool enabled;

            //    if (bool.TryParse(enabledAsString, out enabled))
            //    {
            //        Enabled = enabled;
            //    }
            //    else
            //    {
            //        Enabled = false; // Valeur par défaut
            //    }
            //}
            //else
            //{
            //    Enabled = false; // Valeur par défaut
            //}
        }
Beispiel #56
0
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                //SPSite site = properties.Feature.Parent as SPSite;
                SPSecurity.RunWithElevatedPrivileges(delegate() {
                    // delete the job
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;

                    foreach (SPJobDefinition lockjob in parentWebApp.JobDefinitions)
                    {
                        if (lockjob.Name == "Piwik PRO Analytics Job")
                        {
                            lockjob.Delete();
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                // Logger.WriteLog(Logger.Category.Unexpected, "Piwik FeatureDeactivating timer job", ex.Message);
            }
        }
Beispiel #57
0
        /// <summary>
        /// Clears the web config modifications.
        /// </summary>
        /// <param name="webApp">The web app where the config changes will be cleared</param>
        internal static void ClearWebConfigModifications(SPWebApplication webApp)
        {
            Collection <SPWebConfigModification> collection = webApp.WebConfigModifications;
            int startCount = collection.Count;

            // Remove any modifications that were originally created by the owner.
            for (int i = startCount - 1; i >= 0; i--)
            {
                SPWebConfigModification configMod = collection[i];
                if (configMod.Owner.Equals(OWNERNAME))
                {
                    collection.Remove(configMod);
                }
            }

            // Apply changes only if any items were removed.
            if (startCount > collection.Count)
            {
                SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180);
                webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications();
                webApp.Update();
            }
        }
Beispiel #58
0
        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            List <string>     emailTo   = new List <string>();
            SPWebApplication  webApp    = this.Parent as SPWebApplication;
            SPContentDatabase contentDB = webApp.ContentDatabases[targetInstanceId];

            if (contentDB == null)
            {
                contentDB = webApp.ContentDatabases[0];
            }
            SPWeb web = contentDB.Sites[0].RootWeb;


            // 取参数,通过Properties可以从外部传递参数,但要求参数可以被序列化和反列化
            string siteUrl = this.Properties["SiteUrl"].ToString();
            //上面的内容没有用到

            string  disPlayName = ConfigurationManager.AppSettings["emailDisplayName"];
            string  title       = ConfigurationManager.AppSettings["emailTitle"];
            string  body        = ConfigurationManager.AppSettings["emailBody"];
            string  showUrl     = ConfigurationManager.AppSettings["retUrl"];
            int     delayDays   = int.Parse(System.Configuration.ConfigurationManager.AppSettings["delayDays"]);
            SPList  oList       = web.Lists.TryGetList("讨论列表");
            SPQuery oQuery      = new SPQuery();
            string  userName    = "******";

            emailTo.Add("*****@*****.**");
            oQuery.Query = "<Where><And><Eq><FieldRef Name='Author' /><Value Type='User'>" + userName + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + DateTime.Today.AddDays(-delayDays).ToString("yyyy-MM-dd") + "</Value></Geq></And></Where>";
            SPListItemCollection lstItems = oList.GetItems(oQuery);

            if (lstItems.Count == 0)
            {
                //实现自己业务逻辑,找出复合条件的并发mail做相关通知。
                bool sendOk = SendMail("*****@*****.**", disPlayName, "110004cc", emailTo.ToArray(), title, body);
            }
        }
Beispiel #59
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication adminWebApplication = properties.Feature.Parent as SPWebApplication;

            foreach (SPJobDefinition job in adminWebApplication.JobDefinitions)
            {
                if (job.Name == tJobName)
                {
                    job.Delete();
                }
            }

            using (SPWeb web = adminWebApplication.Sites[0].OpenWeb())
            {
                SPList list = web.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - GlobalSettings");
                if (list != null)
                {
                    try
                    {
                        list.Delete();
                    }
                    catch (Exception)
                    { }
                }

                SPList list2 = web.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - WebAppSettings");
                if (list2 != null)
                {
                    try
                    {
                        list2.Delete();
                    }
                    catch (Exception)
                    { }
                }
            }
        }
        static void Main(string[] args)

        {
            SPSite site = new SPSite(siteUrl);

            // for create your site collection get object of web application class


            SPWebApplication webapp = site.WebApplication;

            // for create a brand new site collection use Add() method to add new site collection
            webapp.Sites.Add

            (

                "/sites/Training",   // site_url ,

                "Training Site",     // Title,

                "SPS 2013 Training", // Description ,

                1033,                // us-eng_code,

                "STS#0",             // type_of_site_template,

                @"Tabrez Ajaz",      // owner_of_site_collection,

                "Administrator",     // type

                "*****@*****.**"     //owner email

            );

            Console.WriteLine("New Site Collection Created Name : Tabrez Site");

            Console.ReadKey();
        }