Exemplo n.º 1
0
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            output = string.Empty;



            string name                = Params["name"].Value;
            long   storagemaxlevel     = 0;
            long   storagewarninglevel = 0;

            try
            {
                if (Params["storagemaxlevel"].UserTypedIn)
                {
                    storagemaxlevel = long.Parse(Params["storagemaxlevel"].Value) * 1024 * 1024; // Convert to bytes
                }
                if (Params["storagewarninglevel"].UserTypedIn)
                {
                    storagewarninglevel = long.Parse(Params["storagewarninglevel"].Value) * 1024 * 1024;
                }
            }
            catch
            {
                throw new SPException("Please specify levels in terms of whole numbers between 0 and " + (long.MaxValue / 1024) / 1024 + ".");
            }
            SPFarm       farm       = SPFarm.Local;
            SPWebService webService = farm.Services.GetValue <SPWebService>("");

            SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;

            if (quotaColl[name] == null)
            {
                output = "The template specified does not exist.";
                return((int)ErrorCodes.GeneralError);
            }
            SPQuotaTemplate newTemplate = new SPQuotaTemplate();

            newTemplate.Name = name;
            if (Params["storagemaxlevel"].UserTypedIn)
            {
                newTemplate.StorageMaximumLevel = storagemaxlevel;
            }
            else
            {
                newTemplate.StorageMaximumLevel = quotaColl[name].StorageMaximumLevel;
            }

            if (Params["storagewarninglevel"].UserTypedIn)
            {
                newTemplate.StorageWarningLevel = storagewarninglevel;
            }
            else
            {
                newTemplate.StorageWarningLevel = quotaColl[name].StorageWarningLevel;
            }

            quotaColl[name] = newTemplate;

            return((int)ErrorCodes.NoError);
        }
Exemplo n.º 2
0
        private List <SPJobDefinition> GetTimerJobsByName(string displayName)
        {
            List <SPJobDefinition> AllJobs = new List <SPJobDefinition>();

            //For all Servers in the Farm (could be different)
            foreach (SPServer server in farm.Servers)
            {
                //Each Service Instance on the Server
                foreach (SPServiceInstance svc in server.ServiceInstances)
                {
                    if (svc.Service.JobDefinitions.Count > 0)
                    {
                        //If its a Web Service, must get the WebApp from the Web Service Entity
                        if (svc.Service is SPWebService)
                        {
                            SPWebService websvc = (SPWebService)svc.Service;
                            AllJobs.AddRange(from webapp in websvc.WebApplications
                                             from def in webapp.JobDefinitions
                                             where def.DisplayName.ToLower() == displayName.ToLower()
                                             select def);
                        }
                        else
                        {
                            //Otherwise Get it directly from the Service
                            AllJobs.AddRange(svc.Service.JobDefinitions.Where(def => def.DisplayName.ToLower() == displayName.ToLower()));
                        }
                    }
                }
            }

            return(AllJobs);
        }
Exemplo n.º 3
0
        private static List <SPJobDefinition> GetAdminCmdLineJobs(SPServer server)
        {
            List <SPJobDefinition> list = new List <SPJobDefinition>();

            foreach (KeyValuePair <Guid, SPService> pair in GetLocalProvisionedServices())
            {
                SPService service = pair.Value;
                foreach (SPJobDefinition definition in service.JobDefinitions)
                {
                    if (ShouldRunAdminCmdLineJob(definition, server))
                    {
                        list.Add(definition);
                    }
                }
                SPWebService service2 = service as SPWebService;
                if (service2 != null)
                {
                    foreach (SPWebApplication application in service2.WebApplications)
                    {
                        foreach (SPJobDefinition definition2 in application.JobDefinitions)
                        {
                            if (ShouldRunAdminCmdLineJob(definition2, server))
                            {
                                list.Add(definition2);
                            }
                        }
                    }
                    continue;
                }
            }
            return(list);
        }
Exemplo n.º 4
0
        protected override void InternalValidate()
        {
            if (TargetUrl != null)
            {
                TargetUrl = TargetUrl.Trim();
                siteUri   = new Uri(TargetUrl, UriKind.Absolute);
                if (!Uri.UriSchemeHttps.Equals(siteUri.Scheme, StringComparison.OrdinalIgnoreCase) && !Uri.UriSchemeHttp.Equals(siteUri.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("The specified target URL is not valid.");
                }
            }
            string serverRelUrlFromFullUrl = Utilities.GetServerRelUrlFromFullUrl(TargetUrl);
            string siteRoot = null;

            if (this.HostHeaderWebApplication == null)
            {
                webApp   = new SPWebApplicationPipeBind(TargetUrl).Read(false);
                siteRoot = Utilities.FindSiteRoot(webApp.Prefixes, serverRelUrlFromFullUrl);
                if ((siteRoot == null) || !siteRoot.Equals(serverRelUrlFromFullUrl, StringComparison.OrdinalIgnoreCase))
                {
                    throw new SPCmdletException("A managed path for the site could not be found.");
                }
            }
            else
            {
                webApp = this.HostHeaderWebApplication.Read();
                useHostHeaderAsSiteName = true;
                SPWebService service = SPFarm.Local.Services.GetValue <SPWebService>();
                if (service == null)
                {
                    throw new InvalidOperationException("A default web service could not be found.");
                }
                siteRoot = Utilities.FindSiteRoot(service.HostHeaderPrefixes, serverRelUrlFromFullUrl);
                if ((siteRoot == null) || !siteRoot.Equals(serverRelUrlFromFullUrl, StringComparison.OrdinalIgnoreCase))
                {
                    throw new SPCmdletException("A managed path for the site could not be found.");
                }
            }
            if (this.ContentDatabase != null)
            {
                this.contentDb = this.ContentDatabase.Read();
                if (null == this.contentDb)
                {
                    throw new SPException("The specified content database could not be found.");
                }
            }
            if (this.QuotaTemplate != null)
            {
                quotaTemplate = this.QuotaTemplate.Read().Name;
            }
            if (this.SiteSubscription != null)
            {
                this.siteSubscription = this.SiteSubscription.Read();
                if (this.siteSubscription == null)
                {
                    base.WriteError(new ArgumentException("The provided site subscription object is invalid."), ErrorCategory.InvalidArgument, this);
                    base.SkipProcessCurrentRecord();
                }
            }
        }
Exemplo n.º 5
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();
                }
            }
        }
Exemplo n.º 6
0
        public static FeatureParent GetFeatureParent(SPWebService farmWebService)
        {
            FeatureParent p = null;

            try
            {
                if (farmWebService == null)
                {
                    return(GetFeatureParentUndefined());
                }
                p = new FeatureParent()
                {
                    DisplayName = "Farm",
                    Url         = "Farm",
                    Id          = farmWebService.Id,
                    Scope       = SPFeatureScope.Farm
                };
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to get Farm object.", ex);
                return(GetFeatureParentUndefined(ex.Message));
            }

            try
            {
                var farmFeatures = farmWebService.Features;
                p.ActivatedFeatures = ActivatedFeature.MapSpFeatureToActivatedFeature(farmFeatures, p);
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to load Farm features.", ex);
            }
            return(p);
        }
        private void Refresh_ContentDatabases()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPServiceCollection services = SPFarm.Local.Services;

                GridPanel panel = new GridPanel();
                IList <SPContentDatabaseEntity> list = new List <SPContentDatabaseEntity>();

                foreach (SPService service in services)
                {
                    if (service is SPWebService)
                    {
                        SPWebService webservice = (SPWebService)service;

                        foreach (SPWebApplication webapp in webservice.WebApplications)
                        {
                            foreach (SPContentDatabase cd in webapp.ContentDatabases)
                            {
                                list.Add(new SPContentDatabaseEntity(cd));
                            }
                        }
                    }
                }

                panel.Title          = "Content Databases";
                panel.GridColumns    = GridColumns_ContentDatabases;
                panel.GridDataSource = list;

                AddPanel(panel);
            });
        }
        public void CanGetFetaureParentFromFarm()
        {
            // Arrange
            var parentScope = SPFeatureScope.Farm;
            // var parentUrl = TestContent.SharePointContainers.WebApplication.Url;


            SPWebService parent = SPWebService.ContentService;


            var testFeatureHealthy = parent.Features[TestContent.TestFeatures.HealthyFarm.Id];
            // var testFeatureFaulty = parent.Features[TestContent.TestFeatures.FaultyFarm.Id];

            // Act
            var parentRetrievedWithScope = FeatureParent.GetFeatureParent(testFeatureHealthy, parentScope);
            var parentRetrievedNoScope   = FeatureParent.GetFeatureParent(testFeatureHealthy);


            // Assert
            Assert.Equal("Farm", parentRetrievedWithScope.DisplayName);
            Assert.Equal(parent.Id, parentRetrievedWithScope.Id);
            Assert.Equal("Farm", parentRetrievedWithScope.Url);
            Assert.Equal(parentScope, parentRetrievedWithScope.Scope);

            Assert.Equal("Farm", parentRetrievedNoScope.DisplayName);
            Assert.Equal(parent.Id, parentRetrievedNoScope.Id);
            Assert.Equal("Farm", parentRetrievedNoScope.Url);
            Assert.Equal(parentScope, parentRetrievedNoScope.Scope);
        }
Exemplo n.º 9
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //load sitecollections unto list
            lstSiteCollections.Items.Clear();

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                SPServiceCollection services = SPFarm.Local.Services;
                foreach (SPService curService in services)
                {
                    if (curService is SPWebService)
                    {
                        SPWebService webService = (SPWebService)curService;

                        foreach (SPWebApplication webApp in webService.WebApplications)
                        {
                            foreach (SPSite sc in webApp.Sites)
                            {
                                try
                                {
                                    lstSiteCollections.Items.Add(sc.Url);
                                }
                                catch (Exception ex)
                                {
                                    //Console.WriteLine("Exception occured: {0}\r\n{1}", ex.Message, ex.StackTrace);
                                }
                            }
                        }
                    }
                }
            });

            ChangeToolStripTextInAnotherThread("Ready");
        }
Exemplo n.º 10
0
        private void UnregisterHttpModule(SPFeatureReceiverProperties properties)
        {
            SPWebConfigModification webConfigModification = CreateWebModificationObject();

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPWebService contentService = properties.Definition.Farm.Services.GetValue <SPWebService>();

                int numberOfModifications = contentService.WebConfigModifications.Count;

                //Iterate over all WebConfigModification and delete only those we have created
                for (int i = numberOfModifications - 1; i >= 0; i--)
                {
                    SPWebConfigModification currentModifiction = contentService.WebConfigModifications[i];

                    if (currentModifiction.Owner.Equals(webConfigModification.Owner))
                    {
                        contentService.WebConfigModifications.Remove(currentModifiction);
                    }
                }

                //Update only if we have something deleted
                if (numberOfModifications > contentService.WebConfigModifications.Count)
                {
                    contentService.Update();
                    contentService.ApplyWebConfigModifications();
                }
            });
        }
Exemplo n.º 11
0
        private void Refresh_Sites()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPServiceCollection services = SPFarm.Local.Services;

                foreach (SPService service in services)
                {
                    if (service is SPWebService)
                    {
                        SPWebService webservice = (SPWebService)service;

                        foreach (SPWebApplication webapp in webservice.WebApplications)
                        {
                            foreach (SPSite sitec in webapp.Sites)
                            {
                                GridPanel panel          = new GridPanel();
                                IList <SPWebEntity> list = new List <SPWebEntity>();

                                foreach (SPWeb web in sitec.AllWebs)
                                {
                                    list.Add(new SPWebEntity(web));
                                }

                                panel.Title          = "Sites under Site Collection " + sitec.HostName + " (" + sitec.Url + ")";
                                panel.GridColumns    = GridColumns_Sites;
                                panel.GridDataSource = list;

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

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebService parentService = properties.Feature.Parent as SPWebService;

            if (parentService != null)
            {
                SPFarm farm = parentService.Farm;

                string serviceId = Visigo.Sharepoint.FormsBasedAuthentication.FBADiagnosticsService.ServiceName;
                // remove service if it allready exists
                foreach (SPService service in farm.Services)
                {
                    if (service is Visigo.Sharepoint.FormsBasedAuthentication.FBADiagnosticsService)
                    {
                        if (service.Name == serviceId)
                        {
                            service.Delete();
                        }
                    }
                }

                // install the service
                farm.Services.Add(Visigo.Sharepoint.FormsBasedAuthentication.FBADiagnosticsService.Local);
            }
        }
        private bool IsFeatureActivatedInAnyWebApp(SPWebApplication thisWebApplication, Guid thisFeatureId)
        {
            // Indicates whether the feature is activated for any other web application in the
            // SharePoint farm.

            // Attempt to access the Web service associated with the content application.
            SPWebService webService = SPWebService.ContentService;

            if (webService == null)
            {
                throw new ApplicationException("Cannot access the Web service associated with the content application.");
            }

            // Iterate through the collection of web applications. If this feature is
            // activated for any web application other than the current web application,
            // return true; otherwise, return false.
            SPWebApplicationCollection webApps = webService.WebApplications;

            foreach (SPWebApplication webApp in webApps)
            {
                if (webApp != thisWebApplication)
                {
                    if (webApp.Features[thisFeatureId] != null)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 14
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWebService service = SPWebService.ContentService;

                Collection <SPWebConfigModification> modsCollection = service.WebConfigModifications;

                // Find the most recent modification of a specified owner
                int modsCount1 = modsCollection.Count;
                for (int i = modsCount1 - 1; i > -1; i--)
                {
                    //I will remove from the web.config just the lines related to this solution and not the ones deployed from other solutions.
                    if (modsCollection[i].Owner.Equals("DH"))
                    {
                        modsCollection.Remove(modsCollection[i]);
                    }
                }

                // Save web.config changes.
                service.Update();
                // Applies the list of web.config modifications to all Web applications in this Web service across the farm.
                service.ApplyWebConfigModifications();
            }
            catch (Exception exception)
            {
                //This is a logging class I use to write exceptions to the ULS Logs. There are plenty of options in this area as well.
                ULSLog2013.LogError(exception);
                throw;
            }
        }
        private void UpdateWebApplications(Settings settings)
        {
            var services  = SPFarm.Local.Services;
            var featureId = new Guid("acee21c4-259c-4ec9-a806-7361f762bd0d");

            foreach (var service in services)
            {
                if (service is SPWebService)
                {
                    SPWebService wService = service as SPWebService;
                    foreach (SPWebApplication app in wService.WebApplications)
                    {
                        var feature = app.Features[featureId];
                        if (feature != null)
                        {
                            var site = GetRootSiteFromApplication(app);
                            if (site != null)
                            {
                                using (var web = site.OpenWeb())
                                {
                                    SetMailTo(web, settings.MailTo);
                                    SetVisibleTo(web, settings.VisibleTo);
                                    web.Update();
                                }
                            }
                        }
                    }
                }
            }
        }
        private void Refresh_ManagedPaths()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPServiceCollection services = SPFarm.Local.Services;

                GridPanel panel = new GridPanel();
                IList <SPManagedPathEntity> list = new List <SPManagedPathEntity>();

                foreach (SPService service in services)
                {
                    if (service is SPWebService)
                    {
                        SPWebService webservice = (SPWebService)service;

                        foreach (SPWebApplication webapp in webservice.WebApplications)
                        {
                            foreach (SPPrefix p in webapp.Prefixes)
                            {
                                list.Add(new SPManagedPathEntity(p)
                                {
                                    ParentWebApplication = webapp.DisplayName
                                });
                            }
                        }
                    }
                }

                panel.Title          = "Managed Paths";
                panel.GridColumns    = GridColumns_ManagedPaths;
                panel.GridDataSource = list;

                AddPanel(panel);
            });
        }
Exemplo n.º 17
0
        private static void UpdateService(SPWebApplication app)
        {
            app.Update(true);
            SPWebService service = app.Farm.Services.GetValue <SPWebService>();

            //service.Update();
            service.ApplyWebConfigModifications();
        }
 /// <summary>Retrieves various pieces of information related to SharePoint Central Administration and
 /// the SPSite-to-LearningStore mappings. </summary>
 /// <param name="adminWebService">The SharePoint Central Administrationt web service.</param>
 /// <returns>Set to the collection of <c>SlkSPSiteMapping</c> objects
 ///     stored in SharePoint's configuration database.</returns>
 static SlkSPSiteMappingCollection GetMappingInfo(SPWebService adminWebService)
 {
     if (adminWebService == null)
     {
         adminWebService = SlkAdministration.GetAdminWebService();
     }
     return(new SlkSPSiteMappingCollection(adminWebService));
 }
Exemplo n.º 19
0
        private static void DeleteQuotaTemplate(string name)
        {
            SPFarm farm = SPFarm.Local;

            SPWebService webService             = farm.Services.GetValue <SPWebService>("");
            SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;

            quotaColl.Delete(name);
        }
        /// <summary>Loads SLK configuration information from WSS and LearningStore, in a form that's
        /// suitable for copying to Configure.aspx form fields. </summary>
        ///
        /// <param name="spSiteGuid">The GUID of the SPSite to retrieve configuration information
        ///     from.</param>
        ///
        /// <returns>An AdministrationConfiguration.</returns>
        ///
        /// <remarks>
        /// This method is static so it can used outside the context of IIS.  Only SharePoint
        /// administrators can perform this function.
        /// </remarks>
        ///
        /// <exception cref="SafeToDisplayException">
        /// An error occurred that can be displayed to a browser user.
        /// </exception>
        ///
        public static AdministrationConfiguration LoadConfiguration(Guid spSiteGuid)
        {
            AdministrationConfiguration configuration = new AdministrationConfiguration(spSiteGuid);

            // only SharePoint administrators can perform this action
            CheckPermissions();

            // set <mapping> to the mapping between <spSiteGuid> and the LearningStore connection
            // information for that SPSite
            SlkSPSiteMapping mapping = SlkSPSiteMapping.GetMapping(spSiteGuid);

            // set "out" parameters based on <mappingExists> and <mapping>
            if (mapping != null)
            {
                // the mapping exists -- set "out" parameters based on <mapping>
                configuration.DatabaseServer       = mapping.DatabaseServer;
                configuration.DatabaseName         = mapping.DatabaseName;
                configuration.InstructorPermission = mapping.InstructorPermission;
                configuration.LearnerPermission    = mapping.LearnerPermission;

                // The below given condition will be true only during the migration of SLK from
                // 'SLK without Observer role' to 'SLK with Observer role' implementation
                if (mapping.ObserverPermission == null)
                {
                    mapping.ObserverPermission = LoadCulture(spSiteGuid).Resources.DefaultSlkObserverPermissionName;
                }
                configuration.ObserverPermission = mapping.ObserverPermission;
            }
            else
            {
                SlkCulture        siteCulture    = LoadCulture(spSiteGuid);
                AppResourcesLocal adminResources = SlkCulture.GetResources();

                configuration.IsNewConfiguration = true;
                mapping = SlkSPSiteMapping.CreateMapping(spSiteGuid);
                // the mapping doesn't exist -- set "out" parameters to default values
                SPWebService adminWebService = SlkAdministration.GetAdminWebService();
                configuration.DatabaseServer       = adminWebService.DefaultDatabaseInstance.Server.Address;
                configuration.DatabaseName         = adminResources.DefaultSlkDatabaseName;
                mapping.DatabaseServer             = configuration.DatabaseServer;
                mapping.DatabaseName               = configuration.DatabaseName;
                configuration.InstructorPermission = siteCulture.Resources.DefaultSlkInstructorPermissionName;
                configuration.LearnerPermission    = siteCulture.Resources.DefaultSlkLearnerPermissionName;
                configuration.ObserverPermission   = siteCulture.Resources.DefaultSlkObserverPermissionName;
            }

            // set "out" parameters that need to be computed
            bool createDatabaseResult = false;

            SlkUtilities.ImpersonateAppPool(delegate()
            {
                createDatabaseResult = !DatabaseExists(mapping.DatabaseServerConnectionString, mapping.DatabaseName);
            });
            configuration.CreateDatabase = createDatabaseResult;

            return(configuration);
        }
Exemplo n.º 21
0
 public static void Disable()
 {
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         SPWebService webservice = SPWebService.ContentService;
         webservice.RemoteAdministratorAccessDenied = true;
         webservice.Update();
     });
 }
Exemplo n.º 22
0
        public WebApplicationNode(SPWebService service, SPWebApplication app)
        {
            this.SPParent      = service;
            this.Tag           = app;
            this.DefaultExpand = true;

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
Exemplo n.º 23
0
        public static Location ToLocation(this SPWebService farm)
        {
            var id = farm.Id;

            var webAppsCount = SpLocationHelper.GetAllWebApplications().Count();

            var location = LocationFactory.GetFarm(id, webAppsCount);

            return(location);
        }
Exemplo n.º 24
0
        public WebApplicationNode(SPWebService service, SPWebApplication app)
        {
            this.SPParent = service;
            this.Tag = app;
            this.DefaultExpand = true;

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
Exemplo n.º 25
0
        public static Location ToLocation(this SPWebService farm)
        {
            var id = farm.Id;
            var activatedFeatures = farm.Features.ToActivatedFeatures(id, Scope.Farm, "Farm");

            var webAppsCount = Services.SpDataService.GetAllWebApplications().Count();

            var location = LocationFactory.GetFarm(id, activatedFeatures, webAppsCount);

            return(location);
        }
Exemplo n.º 26
0
        public WebServiceNode(string name, SPWebService service, bool defaultExpand)
        {
            this.CustomName = name;
            this.ToolTipText = service.GetType().Name;
            this.Tag = service;
            this.DefaultExpand = defaultExpand;

            Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
Exemplo n.º 27
0
        public WebServiceNode(string name, SPWebService service, bool defaultExpand)
        {
            this.CustomName    = name;
            this.ToolTipText   = service.GetType().Name;
            this.Tag           = service;
            this.DefaultExpand = defaultExpand;

            Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        protected override void UpdateDataObject()
        {
            SPQuotaTemplate quota = new SPQuotaTemplate();

            if (Identity != null)
            {
                SPQuotaTemplate clone = Identity.Read();
                quota.Name = clone.Name;
                quota.StorageMaximumLevel  = clone.StorageMaximumLevel;
                quota.StorageWarningLevel  = clone.StorageWarningLevel;
                quota.UserCodeMaximumLevel = clone.UserCodeMaximumLevel;
                quota.UserCodeWarningLevel = clone.UserCodeWarningLevel;
            }
            else
            {
                throw new SPCmdletException("A quota template is required.");
            }


            if (StorageMaximumLevel.HasValue)
            {
                if (StorageMaximumLevel.Value > quota.StorageWarningLevel)
                {
                    quota.StorageMaximumLevel = StorageMaximumLevel.Value;
                    quota.StorageWarningLevel = StorageWarningLevel.Value;
                }
                else
                {
                    quota.StorageWarningLevel = StorageWarningLevel.Value;
                    quota.StorageMaximumLevel = StorageMaximumLevel.Value;
                }
            }

            if (UserCodeMaximumLevel.HasValue)
            {
                if (UserCodeMaximumLevel.Value > quota.UserCodeWarningLevel)
                {
                    quota.UserCodeMaximumLevel = UserCodeMaximumLevel.Value;
                    quota.UserCodeWarningLevel = UserCodeWarningLevel.Value;
                }
                else
                {
                    quota.UserCodeWarningLevel = UserCodeWarningLevel.Value;
                    quota.UserCodeMaximumLevel = UserCodeMaximumLevel.Value;
                }
            }
            SPWebService webService = SPWebService.ContentService;

            webService.QuotaTemplates[quota.Name] = quota;

            webService.Update();
        }
Exemplo n.º 29
0
        private void RegisterHttpModule(SPFeatureReceiverProperties properties)
        {
            SPWebConfigModification webConfigModification = CreateWebModificationObject();

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPWebService contentService = SPWebService.ContentService;

                contentService.WebConfigModifications.Add(webConfigModification);
                contentService.Update();
                contentService.ApplyWebConfigModifications();
            });
        }
Exemplo n.º 30
0
        public QuotaTemplateCollectionNode(SPWebService webService)
        {
            this.Tag = webService.QuotaTemplates;
            this.SPParent = webService.Farm;

            Setup();

            int index = Program.Window.Explorer.AddImage(this.ImageUrl());
            this.ImageIndex = index;
            this.SelectedImageIndex = index;

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
Exemplo n.º 31
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // #### bind combox of all web app url.
            SPFarm       Farm    = SPFarm.Local;
            SPWebService service = Farm.Services.GetValue <SPWebService>("");

            foreach (SPWebApplication webapp in service.WebApplications)
            {
                cbWebApp.Items.Add(webapp.GetResponseUri(SPUrlZone.Default).AbsoluteUri);
                cbImportwebapp.Items.Add(webapp.GetResponseUri(SPUrlZone.Default).AbsoluteUri);
            }
            // #### bind combox of all web app url.
        }
Exemplo n.º 32
0
 internal static List <SPWebApplication> GetApplications()
 {
     try
     {
         SPWebService _srvcs = Farm.Services.GetValue <SPWebService>("");
         return(_srvcs.WebApplications.ToList <SPWebApplication>());
     }
     catch (Exception ex)
     {
         string _msg = Resources.GettingAccess2LocalFarmException + ex.Message;
         throw new ApplicationException(_msg);;
     }
 }
Exemplo n.º 33
0
        private SPWebApplication GetDefaultPortWebApp()
        {
            SPFarm       farm    = SPFarm.Local;
            SPWebService service = farm.Services.GetValue <SPWebService>(string.Empty);

            SPWebApplication defaultPortWebApp = service.WebApplications.FirstOrDefault(wa => wa.GetResponseUri(SPUrlZone.Default).Port == 80);

            if (defaultPortWebApp == null)
            {
                throw new InvalidOperationException("Failed to initialize temporary test SPSite! Can't find default port 80 web application on which to create site.");
            }

            return(defaultPortWebApp);
        }
Exemplo n.º 34
0
        public WebApplicationCollectionNode(SPWebService service)
        {
            this.Text = SPMLocalization.GetString("WebApplications_Text");
            this.ToolTipText = SPMLocalization.GetString("WebApplications_ToolTip");
            this.Name = "WebApplications";
            this.Tag = service.WebApplications;
            this.SPParent = service;
            this.DefaultExpand = true;

            this.ImageIndex = 2;
            this.SelectedImageIndex = 2;

            this.Nodes.Add("Dummy");
        }
        /// <summary>
        /// Reverting Web.config changes made for the DocuSign Feature on deactivation
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            spSite = (SPSite)properties.Feature.Parent;
            spWeb = spSite.OpenWeb();
            webApp = spWeb.Site.WebApplication;
            spWebService = SPWebService.ContentService;

            Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name);
            string configFilePath = config.FilePath;
            doc = new XmlDocument();
            XmlNode nodeTrust = null;
            XmlNode nodeEnableSessionState = null;
            doc.Load(configFilePath);

            nodeServiceModel = doc.SelectSingleNode("configuration/system.serviceModel");
            nodeSmtpServer = doc.SelectSingleNode("configuration/appSettings/add[@key='smtpServer']");
            nodeUserName = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignUserName']");
            nodePassword = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignPassword']");
            nodeTrust = doc.SelectSingleNode("configuration/system.web/trust");
            nodeEnableSessionState = doc.SelectSingleNode("configuration/system.web/pages");
            //int count=0;

            if (webApp != null)
            {
                    // Set the enableSessionState attribute to false
                    if (nodeEnableSessionState != null)
                    {
                        XmlAttribute attributeEnableSessionState = nodeEnableSessionState.Attributes["enableSessionState"];
                        if (attributeEnableSessionState != null)
                        {
                            attributeEnableSessionState.Value = "false";
                        }
                    }

                    // Set the level attribute to WSS_Minimal
                    if (nodeTrust != null)
                    {
                        XmlAttribute attributeLevel = nodeTrust.Attributes["level"];
                        if (attributeLevel != null)
                        {
                            attributeLevel.Value = "WSS_Minimal";
                        }
                    }

                    // Remove serviceModel node - DocuSign Webservice info
                    if (nodeServiceModel != null)
                    {
                        nodeServiceModel.ParentNode.RemoveChild(nodeServiceModel);
                    }

                    //Remove smtpServer node
                    if (nodeSmtpServer != null)
                    {
                        nodeSmtpServer.ParentNode.RemoveChild(nodeSmtpServer);
                    }

                    //Remove Password node
                    if (nodePassword != null)
                    {
                        nodePassword.ParentNode.RemoveChild(nodePassword);
                    }

                    // Remove UserName node
                    if (nodeUserName != null)
                    {
                        nodeUserName.ParentNode.RemoveChild(nodeUserName);
                    }

                    doc.Save(configFilePath);

                    // Apply the config modifications to the application

                }
        }
        /// <summary>
        /// Make modifications to the web.config when the feature is activated.
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            spSite = (SPSite)properties.Feature.Parent;
            spWeb = spSite.OpenWeb();
            spWebService = SPWebService.ContentService;

            Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name);
            string smtpServer = string.Empty;
            string configFilePath = config.FilePath;
            doc = new XmlDocument();
            doc.Load(configFilePath);
            AppSettingsSection appSettings = config.AppSettings;

            if (appSettings.ElementInformation.IsPresent)
            {
                nodeSmtpServer = doc.SelectSingleNode("configuration/appSettings/add[@key='smtpServer']");
                nodeUserName = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignUserName']");
                nodePassword = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignPassword']");

                // Add smtpServer to web.config file
                if(nodeSmtpServer == null)
                    ModifyWebConfigData("add[@key='SMTPServer']", "configuration/appSettings", "<add key='smtpServer' value='" + SMTP_SERVER + "' />");

                // Add DocuSign Service user Credentials to web.config file
                if (nodeUserName == null)
                    ModifyWebConfigData("add[@key='userName']", "configuration/appSettings", "<add key='docuSignUserName' value='" + DOCUSIGN_USERNAME + "' />");

                // Add Profiles to web.config file
                if(nodePassword == null)
                    ModifyWebConfigData("add[@key='password']", "configuration/appSettings", "<add key='docuSignPassword' value='" + DOCUSIGN_PASSWORD + "' />");
            }
            else
                ModifyWebConfigData("add[@key='SMTPServer']", "configuration", "<appSettings><add key='smtpServer' value='" + SMTP_SERVER + "' /><add key='docuSignUserName' value='" + DOCUSIGN_USERNAME + "' /><add key='docuSignPassword' value='" + DOCUSIGN_PASSWORD + "' /></appSettings>");

            nodeServiceModel = doc.SelectSingleNode("configuration/system.serviceModel");

            // Add ServiceModel to web.config file
            if(nodeServiceModel == null)
                ModifyWebConfigData("ServiceModel", "configuration", GetServiceModelTag());

            XmlNode nodeTrust = null;
            XmlNode nodeEnableSessionState = null;
            nodeTrust = doc.SelectSingleNode("configuration/system.web/trust");
            nodeEnableSessionState = doc.SelectSingleNode("configuration/system.web/pages");

            if (nodeEnableSessionState != null)
            {
                XmlAttribute attributeEnableSessionState = nodeEnableSessionState.Attributes["enableSessionState"];
                if (attributeEnableSessionState != null)
                {
                    attributeEnableSessionState.Value = "true";
                }
            }

            // Set the level attribute to WSS_Minimal
            if (nodeTrust != null)
            {
                XmlAttribute attributeLevel = nodeTrust.Attributes["level"];
                if (attributeLevel != null)
                {
                    attributeLevel.Value = "Full";
                }
            }
            doc.Save(configFilePath);
            ModifyWebConfigData("add[@name='Session']", "configuration/system.web/httpModules", "<add name='Session' type='System.Web.SessionState.SessionStateModule' />");

            spWebService.Update();
            spWebService.ApplyWebConfigModifications();
        }