Пример #1
0
        public static string InstallVirtualSite(string sitename, string virtualPath, string siteLocation, string poolName = null, bool isnetcore = false)
        {
            try
            {
                if (!virtualPath.StartsWith("/"))
                {
                    virtualPath = "/" + virtualPath;
                }

                using (ServerManager iisManager = new ServerManager())
                {
                    var app         = iisManager.Sites[sitename].Applications;
                    var application = app.Add(virtualPath, siteLocation);
                    if (!string.IsNullOrEmpty(poolName))
                    {
                        //看pool是否存在
                        var isPoolExist = IsApplicationPoolExist(poolName);
                        if (!isPoolExist)
                        {
                            //不存在就创建
                            ApplicationPool newPool = iisManager.ApplicationPools.Add(poolName);
                            newPool.ManagedRuntimeVersion = !isnetcore ? "v4.0" : null;
                            newPool.ManagedPipelineMode   = ManagedPipelineMode.Integrated;
                        }

                        application.ApplicationPoolName = poolName;
                    }
                    //app.VirtualDirectories.Add(virtualPath, siteLocation);
                    iisManager.CommitChanges();
                    return(string.Empty);
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Пример #2
0
        private void Create()
        {
            if (this.AppPoolExists())
            {
                if (!this.Force)
                {
                    this.LogBuildError(string.Format(CultureInfo.CurrentCulture, "The Application Pool: {0} already exists on: {1}", this.Name.Get(this.ActivityContext), this.MachineName.Get(this.ActivityContext)));
                    return;
                }

                this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Application Pool: {0} on: {1}", this.Name.Get(this.ActivityContext), this.MachineName.Get(this.ActivityContext)));
                this.iisServerManager.ApplicationPools.Remove(this.pool);
                this.iisServerManager.CommitChanges();
            }

            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Creating Application Pool: {0} on: {1}", this.Name.Get(this.ActivityContext), this.MachineName.Get(this.ActivityContext)));

            if (this.IdentityType == "SpecificUser" && (string.IsNullOrEmpty(this.PoolIdentity) || string.IsNullOrEmpty(this.IdentityPassword)))
            {
                this.LogBuildError("PoolIdentity and PoolPassword must be specified if the IdentityType is SpecificUser");
                return;
            }

            this.pool = this.iisServerManager.ApplicationPools.Add(this.Name.Get(this.ActivityContext));
            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Setting ManagedPipelineMode to: {0}", this.PipelineMode), BuildMessageImportance.Low);
            this.pool.ManagedPipelineMode = this.managedPM;
            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Setting ProcessModelIdentityType to: {0}", this.IdentityType), BuildMessageImportance.Low);
            this.pool.ProcessModel.IdentityType = this.processModelType;
            if (this.IdentityType == "SpecificUser")
            {
                this.pool.ProcessModel.UserName = this.PoolIdentity;
                this.pool.ProcessModel.Password = this.IdentityPassword;
            }

            this.SetCommonInfo();
            this.iisServerManager.CommitChanges();
        }
Пример #3
0
        /// <summary>
        /// 操作应用程序池
        /// </summary>
        /// <param name="appPoolName"></param>
        /// <param name="method">Start==启动 Recycle==回收 Stop==停止</param>
        /// <returns></returns>
        public static bool DoAppPool(string appPoolName, string method)
        {
            bool            result     = false;
            ServerManager   iisManager = new ServerManager();
            ApplicationPool appPool    = iisManager.ApplicationPools[appPoolName];

            if (appPool != null)
            {
                try
                {
                    switch (method.ToLower())
                    {
                    case "stop":
                        appPool.Stop();
                        break;

                    case "start":
                        appPool.Start();
                        break;

                    case "recycle":
                        appPool.Recycle();
                        break;

                    default:
                        return(false);
                    }
                    iisManager.CommitChanges();
                    result = true;
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return(result);
        }
Пример #4
0
 public static bool CreateAppPool(string serverName, string appPoolName, string managedRuntimeVersion, string managedPipelineMode, string enable32Bit, string identityType, string userName, string password, out string message)
 {
     try
     {
         using (ServerManager serverManager = ServerManager.OpenRemote(serverName))
         {
             ApplicationPool newPool = serverManager.ApplicationPools.Add(appPoolName);
             newPool.ManagedRuntimeVersion     = managedRuntimeVersion;
             newPool.Enable32BitAppOnWin64     = Convert.ToBoolean(enable32Bit);
             newPool.ManagedPipelineMode       = (ManagedPipelineMode)Enum.Parse(typeof(ManagedPipelineMode), managedPipelineMode, true);
             newPool.ProcessModel.IdentityType = (ProcessModelIdentityType)Enum.Parse(typeof(ProcessModelIdentityType), identityType, true);
             newPool.ProcessModel.UserName     = userName;
             newPool.ProcessModel.Password     = password;
             serverManager.CommitChanges();
             message = "";
             return(true);
         }
     }
     catch (Exception exe)
     {
         message = exe.Message;
         return(false);
     }
 }
Пример #5
0
        //public static void CreateVirtualDirectory(string siteName, string applicationName, string virtualDirectoryName, string path)
        //{
        //    using (ServerManager serverManager = new ServerManager())
        //    {
        //        var application = GetApplication(serverManager, siteName, applicationName);
        //        application.VirtualDirectories.Add("/" + virtualDirectoryName, path);
        //        serverManager.CommitChanges();
        //    }
        //}

        public static void SetApplicationApplicationPool(string siteName, string applicationName, string applicationPoolName)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                ApplicationPool appPool = serverManager.ApplicationPools[applicationName];
                if (appPool == null)
                {
                    return;
                }
                //does not work to query site outside in this case.  check this out http://stackoverflow.com/a/10386994/393159
                //var site = GetSite(siteName);

                var site = serverManager.Sites.FirstOrDefault(x => x.Name == siteName);
                if (site != null)
                {
                    var app = site.Applications["/" + applicationName];
                    if (app != null)
                    {
                        app.ApplicationPoolName = appPool.Name;
                    }
                }
                serverManager.CommitChanges();
            }
        }
Пример #6
0
        private static void SetToDefaults(ApplicationPool pool, ApplicationPoolDefaults defaults)
        {
            pool.ManagedPipelineMode   = defaults.ManagedPipelineMode;
            pool.ManagedRuntimeVersion = defaults.ManagedRuntimeVersion;
            pool.Enable32BitAppOnWin64 = defaults.Enable32BitAppOnWin64;
            pool.QueueLength           = defaults.QueueLength;
            pool.AutoStart             = defaults.AutoStart;

            pool.Cpu.Limit                     = defaults.Cpu.Limit;
            pool.Cpu.ResetInterval             = defaults.Cpu.ResetInterval;
            pool.Cpu.Action                    = defaults.Cpu.Action;
            pool.Cpu.SmpAffinitized            = defaults.Cpu.SmpAffinitized;
            pool.Cpu.SmpProcessorAffinityMask  = defaults.Cpu.SmpProcessorAffinityMask;
            pool.Cpu.SmpProcessorAffinityMask2 = defaults.Cpu.SmpProcessorAffinityMask2;

            if (pool.ProcessModel.Schema.HasAttribute(IdleTimeoutActionAttribute))
            {
                pool.ProcessModel.IdleTimeoutAction = defaults.ProcessModel.IdleTimeoutAction;
            }

            pool.ProcessModel.MaxProcesses      = defaults.ProcessModel.MaxProcesses;
            pool.ProcessModel.PingingEnabled    = defaults.ProcessModel.PingingEnabled;
            pool.ProcessModel.IdleTimeout       = defaults.ProcessModel.IdleTimeout;
            pool.ProcessModel.PingInterval      = defaults.ProcessModel.PingInterval;
            pool.ProcessModel.PingResponseTime  = defaults.ProcessModel.PingResponseTime;
            pool.ProcessModel.ShutdownTimeLimit = defaults.ProcessModel.ShutdownTimeLimit;
            pool.ProcessModel.StartupTimeLimit  = defaults.ProcessModel.StartupTimeLimit;

            pool.Recycling.LogEventOnRecycle              = defaults.Recycling.LogEventOnRecycle;
            pool.Recycling.DisallowOverlappingRotation    = defaults.Recycling.DisallowOverlappingRotation;
            pool.Recycling.DisallowRotationOnConfigChange = defaults.Recycling.DisallowRotationOnConfigChange;
            pool.Recycling.PeriodicRestart.PrivateMemory  = defaults.Recycling.PeriodicRestart.PrivateMemory;
            pool.Recycling.PeriodicRestart.Memory         = defaults.Recycling.PeriodicRestart.Memory;
            pool.Recycling.PeriodicRestart.Requests       = defaults.Recycling.PeriodicRestart.Requests;
            pool.Recycling.PeriodicRestart.Time           = defaults.Recycling.PeriodicRestart.Time;
        }
Пример #7
0
        /// <summary>
        /// 创建新站点
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="protocol"></param>
        /// <param name="bindingInformation"></param>
        /// <param name="physicalPath"></param>
        /// <param name="createAppPool"></param>
        /// <param name="appPoolName"></param>
        /// <param name="identityType"></param>
        /// <param name="appPoolUserName"></param>
        /// <param name="appPoolPassword"></param>
        /// <param name="appPoolPipelineMode"></param>
        /// <param name="managedRuntimeVersion"></param>
        private static void createSite(string siteName, string protocol, string bindingInformation, string physicalPath,
                                       bool createAppPool, string appPoolName, ProcessModelIdentityType identityType,
                                       string appPoolUserName, string appPoolPassword, ManagedPipelineMode appPoolPipelineMode, string managedRuntimeVersion)
        {
            using (ServerManager mgr = new ServerManager())
            {
                Site site = mgr.Sites.Add(siteName, protocol, bindingInformation, physicalPath);

                // PROVISION APPPOOL IF NEEDED
                if (createAppPool)
                {
                    ApplicationPool pool = mgr.ApplicationPools.FirstOrDefault(p => p.Name == appPoolName);
                    if (pool == null)
                    {
                        pool = mgr.ApplicationPools.Add(appPoolName);
                        if (pool.ProcessModel.IdentityType != identityType)
                        {
                            pool.ProcessModel.IdentityType = identityType;
                        }
                        if (!String.IsNullOrEmpty(appPoolUserName))
                        {
                            pool.ProcessModel.UserName = appPoolUserName;
                            pool.ProcessModel.Password = appPoolPassword;
                        }
                        if (appPoolPipelineMode != pool.ManagedPipelineMode)
                        {
                            pool.ManagedPipelineMode = appPoolPipelineMode;
                        }
                    }

                    site.Applications["/"].ApplicationPoolName = pool.Name;
                }

                mgr.CommitChanges();
            }
        }
Пример #8
0
        private void Initialize(ApplicationPool iisPoolObject, IISCodeGenerator.IisPoolAndSitesOptions iisOptions)
        {
            this.Key = GetPoolVariableName(iisPoolObject.Name);

            this.AddAttribute("Name", iisPoolObject.Name);

            if (iisOptions.KeepAppPoolsRunning)
            {
                this.AddAttributeWithOverrideValue("AutoStart", "True", iisPoolObject.AutoStart.ToString());
            }

            this.AddAttribute("ManagedPipelineMode", iisPoolObject.ManagedPipelineMode.ToString());
            this.AddAttribute("ManagedRuntimeVersion", iisPoolObject.ManagedRuntimeVersion);
            this.AddAttribute("IdentityType", iisPoolObject.ProcessModel.IdentityType.ToString());
            this.AddAttribute("Enable32BitAppOnWin64", iisPoolObject.Enable32BitAppOnWin64.ToString());

            if (iisOptions.StandardizeAppPoolRecycles)
            {
                this.AddAttributeWithOverrideValue("RestartSchedule", "@(\"02:00:00\")", GetScheduleString(iisPoolObject));
            }
            else
            {
                this.AddAttribute("RestartSchedule", GetScheduleString(iisPoolObject));
            }

            if (iisOptions.KeepAppPoolsRunning)
            {
                this.AddAttributeWithOverrideValue("IdleTimeout", "00:00:00", iisPoolObject.ProcessModel.IdleTimeout.ToString());
                this.AddAttributeWithOverrideValue("RestartTimeLimit", "00:00:00", iisPoolObject.Recycling.PeriodicRestart.Time.ToString());
            }
            else
            {
                this.AddAttribute("IdleTimeout", iisPoolObject.ProcessModel.IdleTimeout.ToString());
                this.AddAttribute("RestartTimeLimit", iisPoolObject.Recycling.PeriodicRestart.Time.ToString());
            }
        }
        internal static bool TryRecycleApplicationPool(ServerManager serverManager, string applicationPoolName)
        {
            bool result;

            try
            {
                ApplicationPoolCollection applicationPools = serverManager.ApplicationPools;
                ApplicationPool           applicationPool  = applicationPools[applicationPoolName];
                if (applicationPool == null)
                {
                    result = false;
                }
                else
                {
                    applicationPool.Recycle();
                    result = true;
                }
            }
            catch (COMException)
            {
                result = false;
            }
            return(result);
        }
Пример #10
0
 public void RecycleApplicationPool(string serverName, string appPoolName)
 {
     if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(appPoolName))
     {
         try
         {
             using (ServerManager manager = ServerManager.OpenRemote(serverName))
             {
                 ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == appPoolName);
                 if (appPool != null)
                 {
                     bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting;
                     bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping;
                     if (appPoolStopped)
                     {
                         while (appPool.State == ObjectState.Stopping)
                         {
                             System.Threading.Thread.Sleep(3000);
                         }
                         appPool.Start();
                     }
                 }
                 else
                 {
                     log.Info(string.Format("An Application Pool does not exist with the name {0}.{1}", serverName, appPoolName));
                     throw new Exception(string.Format("An Application Pool does not exist with the name {0}.{1}", serverName, appPoolName));
                 }
             }
         }
         catch (Exception ex)
         {
             log.Error(ex);
             throw new Exception(string.Format("Unable to restart the application pools for {0}.{1}", serverName, appPoolName), ex.InnerException);
         }
     }
 }
Пример #11
0
        public static void iis7_create_site(string siteName, string applicationPoolName, string path, int port)
        {
            if (string.IsNullOrEmpty(siteName))
            {
                throw new StringIsNullOrEmptyException("siteName");
            }

            if (string.IsNullOrEmpty(applicationPoolName))
            {
                throw new StringIsNullOrEmptyException("applicationPoolName");
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new StringIsNullOrEmptyException("path");
            }

            using (var iisManager = new ServerManager())
            {
                if (iisManager.Sites[siteName] != null)
                {
                    throw new SiteAlreadyExistsException(siteName);
                }

                iisManager.Sites.Add(siteName, new DirectoryInfo(path.Replace('\\', '/')).FullName, port);

                ApplicationPool applicationPool = iisManager.ApplicationPools[applicationPoolName];
                if (applicationPool == null)
                {
                    iisManager.ApplicationPools.Add(applicationPoolName);
                }

                iisManager.Sites[siteName].Applications[0].ApplicationPoolName = applicationPoolName;
                iisManager.CommitChanges();
            }
        }
Пример #12
0
        // Add an app pool for a site. If it already exists, return the existing one.
        public ApplicationPool AddApplicationPool(string name)
        {
            ApplicationPool appPool = null;

            // Create an application pool.
            if (sm.ApplicationPools != null)
            {
                // If one already exists make sure not to overlap names
                if (sm.ApplicationPools.Count > 0)
                {
                    appPool = sm.ApplicationPools.FirstOrDefault(p => p.Name == name);
                    if (appPool != null)
                    {
                        return(appPool);
                    }
                    // If it does not exist, then add it.
                    else
                    {
                        appPool = sm.ApplicationPools.Add(name);
                    }
                }
                // Otherwise just make it.
                else
                {
                    appPool = sm.ApplicationPools.Add(name);
                }
            }

            // Now verify configuration with the app pool.
            if (appPool != null)
            {
                sm.CommitChanges();
            }

            return(appPool);
        }
        public ApplicationPoolBasicSettingsDialog(IServiceProvider serviceProvider, ApplicationPool pool, ApplicationPoolDefaults defaults, ApplicationPoolCollection collection)
            : base(serviceProvider)
        {
            InitializeComponent();
            Pool = pool;
            var add = pool == null;

            if (pool == null)
            {
                Text                 = "Add Application Pool";
                cbStart.Checked      = defaults.AutoStart;
                cbMode.SelectedIndex = (int)defaults.ManagedPipelineMode;
                SetRuntimeVersion(defaults.ManagedRuntimeVersion);
            }
            else
            {
                Text                 = "Edit Application Pool";
                txtName.Text         = pool.Name;
                txtName.Enabled      = false;
                cbStart.Checked      = pool.AutoStart;
                cbMode.SelectedIndex = (int)pool.ManagedPipelineMode;
                SetRuntimeVersion(Pool.ManagedRuntimeVersion);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Pool == null)
                {
                    if (collection.Any(item => item.Name == txtName.Text))
                    {
                        ShowMessage("An application pool with this name already exists.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        txtName.Focus();
                        return;
                    }

                    Pool = collection.Add(txtName.Text);
                }
                else
                {
                    Pool.Name = txtName.Text;
                }

                if (cbVersion.SelectedIndex == 0)
                {
                    Pool.ManagedRuntimeVersion = "v4.0";
                }
                else if (cbVersion.SelectedIndex == 1)
                {
                    Pool.ManagedRuntimeVersion = "v2.0";
                }
                else
                {
                    Pool.ManagedRuntimeVersion = string.Empty;
                }

                if (add && collection.Parent.Mode == WorkingMode.IisExpress)
                {
                    Pool["CLRConfigFile"] = @"%IIS_USER_HOME%\config\aspnet.config";
                }

                Pool.AutoStart           = cbStart.Checked;
                Pool.ManagedPipelineMode = (ManagedPipelineMode)cbMode.SelectedIndex;
                DialogResult             = DialogResult.OK;
            }));
        }
        private bool IsStarted([NotNull] ApplicationPool pool)
        {
            Assert.ArgumentNotNull(pool, nameof(pool));

            return(pool.State == ObjectState.Started || pool.State == ObjectState.Starting);
        }
        public async Task <object> Patch(string id, [FromBody] dynamic model)
        {
            // Cut off the notion of uuid from beginning of request
            string name = AppPoolId.CreateFromUuid(id).Name;

            // Set settings
            ApplicationPool appPool = AppPoolHelper.UpdateAppPool(name, model);

            if (appPool == null)
            {
                return(NotFound());
            }

            if (model.identity != null && !await IsAppPoolIdentityAllowed(appPool))
            {
                return(new ForbidResult());
            }

            // Start/Stop
            if (model.status != null)
            {
                Status status = DynamicHelper.To <Status>(model.status);
                try {
                    switch (status)
                    {
                    case Status.Stopped:
                        appPool.Stop();
                        break;

                    case Status.Started:
                        appPool.Start();
                        break;

                    case Status.Recycling:
                        appPool.Recycle();
                        break;
                    }
                }
                catch (COMException e) {
                    // If pool is fresh and status is still unknown then COMException will be thrown when manipulating status
                    throw new ApiException("Error setting application pool status", e);
                }
            }

            // Update changes
            ManagementUnit.Current.Commit();

            // Refresh data
            appPool = ManagementUnit.ServerManager.ApplicationPools[appPool.Name];

            //
            // Create response
            dynamic pool = AppPoolHelper.ToJsonModel(appPool, Context.Request.GetFields());

            // The Id could change by changing apppool name
            if (pool.id != id)
            {
                return(LocationChanged(AppPoolHelper.GetLocation(pool.id), pool));
            }

            return(pool);
        }
        internal static object WpToJsonModel(WorkerProcess wp, Fields fields = null, bool full = true)
        {
            if (wp == null)
            {
                throw new ArgumentNullException(nameof(wp));
            }

            if (fields == null)
            {
                fields = Fields.All;
            }

            Process p = Process.GetProcessById(wp.ProcessId);

            dynamic obj = new ExpandoObject();

            //
            // name
            if (fields.Exists("name"))
            {
                obj.name = p.ProcessName;
            }

            //
            // id
            obj.id = new WorkerProcessId(p.Id, Guid.Parse(wp.ProcessGuid)).Uuid;

            //
            // status
            if (fields.Exists("status"))
            {
                obj.status = Enum.GetName(typeof(WorkerProcessState), wp.State).ToLower();
            }

            //
            // process_id
            if (fields.Exists("process_id"))
            {
                obj.process_id = p.Id;
            }

            //
            // process_guid
            if (fields.Exists("process_guid"))
            {
                obj.process_guid = wp.ProcessGuid;
            }

            //
            // start_time
            if (fields.Exists("start_time"))
            {
                obj.start_time = p.StartTime;
            }

            //
            // working_set
            if (fields.Exists("working_set"))
            {
                obj.working_set = p.WorkingSet64;
            }

            //
            // peak_working_set
            if (fields.Exists("peak_working_set"))
            {
                obj.peak_working_set = p.PeakWorkingSet64;
            }

            //
            // private_memory_size
            if (fields.Exists("private_memory_size"))
            {
                obj.private_memory_size = p.PrivateMemorySize64;
            }

            //
            // virtual_memory_size
            if (fields.Exists("virtual_memory_size"))
            {
                obj.virtual_memory_size = p.VirtualMemorySize64;
            }

            //
            // peak_virtual_memory_size
            if (fields.Exists("peak_virtual_memory_size"))
            {
                obj.peak_virtual_memory_size = p.PeakVirtualMemorySize64;
            }

            //
            // total_processor_time
            if (fields.Exists("total_processor_time"))
            {
                obj.total_processor_time = p.TotalProcessorTime;
            }

            //
            // application_pool
            if (fields.Exists("application_pool"))
            {
                ApplicationPool pool = AppPoolHelper.GetAppPool(wp.AppPoolName);
                obj.application_pool = AppPoolHelper.ToJsonModelRef(pool);
            }

            return(Core.Environment.Hal.Apply(Defines.Resource.Guid, obj, full));
        }
        public void Ready()
        {
            Receive <GetServiceStatus>(ic =>
            {
                var self = Self;
                Task.Run(() =>
                {
                    List <ServiceModel> services = new List <ServiceModel>();
                    services.Add(new ServiceModel("Service", "Lighthouse", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Service", "Lighthouse2", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Service", "Worker", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Service", "Worker2", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Service", "WorkerWithWebApi", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Service", "Tasker", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("Website", "Default", Dns.GetHostName(), ""));
                    services.Add(new ServiceModel("AppPool", "Default", Dns.GetHostName(), ""));

                    foreach (var serviceModel in services.Where(x => x.Type == "Service"))
                    {
                        try
                        {
                            using (var sc = new ServiceController(serviceModel.ServiceName, serviceModel.MachineName))
                            {
                                serviceModel.Status = sc.Status.ToString();
                            }
                        }
                        catch (Exception ex)
                        {
                            serviceModel.Status = "Error: " + ex.Message;
                        }
                    }

                    foreach (var serviceModel in services.Where(x => x.Type == "Website"))
                    {
                        try
                        {
                            using (ServerManager manager = ServerManager.OpenRemote(serviceModel.MachineName))
                            {
                                var website = manager.Sites.FirstOrDefault(ap => ap.Name == serviceModel.ServiceName);

                                //Don't bother trying to recycle if we don't have an app pool
                                if (website != null)
                                {
                                    //Get the current state of the app pool
                                    serviceModel.Status = website.State.ToString();
                                }
                                else
                                {
                                    serviceModel.Status = string.Format("An Application does not exist with the name {0}", serviceModel.ServiceName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            serviceModel.Status = "Error: " + ex.Message;
                        }
                    }

                    foreach (var serviceModel in services.Where(x => x.Type == "AppPool"))
                    {
                        try
                        {
                            using (ServerManager manager = ServerManager.OpenRemote(serviceModel.MachineName))
                            {
                                ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == serviceModel.ServiceName);

                                //Don't bother trying to recycle if we don't have an app pool
                                if (appPool != null)
                                {
                                    //Get the current state of the app pool
                                    serviceModel.Status = appPool.State.ToString();
                                }
                                else
                                {
                                    serviceModel.Status = string.Format("An Application Pool does not exist with the name {0}.{1}", serviceModel.MachineName, serviceModel.ServiceName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            serviceModel.Status = "Error: " + ex.Message;
                        }
                    }

                    return(services);
                }, _cancel.Token).ContinueWith((x) =>
                {
                    if (x.IsCanceled || x.IsFaulted)
                    {
                        return(new Finished(x.Result.ToList(), x.Exception));
                    }
                    return(new Finished(x.Result.ToList(), null));
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously)
                .PipeTo(self);

                // switch behavior
                Become(Working);
            });
        }
Пример #18
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            base.InternalProcessRecord();
            ServerIdParameter serverIdParameter = new ServerIdParameter();
            Server            server            = (Server)base.GetDataObject <Server>(serverIdParameter, base.DataSession, null, new LocalizedString?(Strings.ErrorServerNotFound(serverIdParameter.ToString())), new LocalizedString?(Strings.ErrorServerNotUnique(serverIdParameter.ToString())));

            if (!server.IsClientAccessServer && !server.IsCafeServer)
            {
                base.ThrowTerminatingError(server.GetServerRoleError(ServerRole.ClientAccess), ErrorCategory.InvalidOperation, server);
            }
            using (ServerManager serverManager = new ServerManager())
            {
                ApplicationPool applicationPool = serverManager.ApplicationPools["MSExchangeOWAAppPool"];
                if (applicationPool == null)
                {
                    base.ThrowTerminatingError(new ADNoSuchObjectException(Strings.ErrorOWAVdirAppPoolNotExist), ErrorCategory.ObjectNotFound, serverManager.ApplicationPools);
                }
                applicationPool.ManagedPipelineMode = 0;
                serverManager.CommitChanges();
            }
            QueryFilter filter = new ComparisonFilter(ComparisonOperator.NotEqual, ADOwaVirtualDirectorySchema.OwaVersion, OwaVersions.Exchange2003or2000);

            base.WriteVerbose(TaskVerboseStringHelper.GetFindDataObjectsVerboseString(base.DataSession, typeof(ADOwaVirtualDirectory), filter, server.Identity, true));
            IConfigDataProvider dataSession = base.DataSession;
            IEnumerable <ADOwaVirtualDirectory> enumerable = dataSession.FindPaged <ADOwaVirtualDirectory>(filter, server.Identity, true, null, 0);

            foreach (ADOwaVirtualDirectory adowaVirtualDirectory in enumerable)
            {
                if (adowaVirtualDirectory.WebSite.Equals("Exchange Back End", StringComparison.OrdinalIgnoreCase))
                {
                    string metabasePath = adowaVirtualDirectory.MetabasePath;
                    try
                    {
                        base.WriteVerbose(Strings.VerboseConnectingIISVDir(metabasePath));
                        using (IisUtility.CreateIISDirectoryEntry(metabasePath))
                        {
                            if (!DirectoryEntry.Exists(metabasePath))
                            {
                                this.WriteWarning(Strings.OwaAdOrphanFound(adowaVirtualDirectory.Identity.ToString()));
                                continue;
                            }
                            if (!IisUtility.WebDirObjectExists(metabasePath, this.owaVersion))
                            {
                                base.WriteVerbose(Strings.VerboseCreatingChildVDir(this.owaVersion, metabasePath));
                                CreateVirtualDirectory createVirtualDirectory = new CreateVirtualDirectory();
                                createVirtualDirectory.Name   = this.owaVersion;
                                createVirtualDirectory.Parent = metabasePath;
                                createVirtualDirectory.CustomizedVDirProperties = OwaVirtualDirectoryHelper.GetVersionVDirProperties();
                                createVirtualDirectory.LocalPath = (string)IisUtility.GetIisPropertyValue("Path", createVirtualDirectory.CustomizedVDirProperties);
                                createVirtualDirectory.Initialize();
                                createVirtualDirectory.Execute();
                            }
                        }
                        OwaVirtualDirectoryHelper.CreateLegacyVDirs(metabasePath, true);
                        OwaVirtualDirectoryHelper.CreateOwaCalendarVDir(metabasePath, VirtualDirectoryRole.Mailbox);
                        if (ExchangeServiceVDirHelper.IsBackEndVirtualDirectory(adowaVirtualDirectory))
                        {
                            WebAppVirtualDirectoryHelper.UpdateMetabase(adowaVirtualDirectory, metabasePath, true);
                        }
                    }
                    catch (COMException ex)
                    {
                        base.WriteError(new IISGeneralCOMException(ex.Message, ex.ErrorCode, ex), ErrorCategory.InvalidOperation, null);
                    }
                    if (adowaVirtualDirectory.ExchangeVersion.IsOlderThan(adowaVirtualDirectory.MaximumSupportedExchangeObjectVersion))
                    {
                        try
                        {
                            adowaVirtualDirectory.SetExchangeVersion(adowaVirtualDirectory.MaximumSupportedExchangeObjectVersion);
                            base.DataSession.Save(adowaVirtualDirectory);
                        }
                        catch (DataSourceTransientException exception)
                        {
                            base.WriteError(exception, ErrorCategory.WriteError, null);
                        }
                    }
                }
            }
            TaskLogger.LogExit();
        }
        private bool DeployApplicationPool(
            ServerManager mgr, ActionType action, string appPoolName, ProcessModelIdentityType identityType, string userName, string password,
            string managedRuntimeVersion, bool autoStart, bool enable32BitAppOnWin64, ManagedPipelineMode managedPipelineMode)
        {
            ApplicationPool appPool = mgr.ApplicationPools[appPoolName];

            if (action == ActionType.CreateOrUpdate)
            {
                if (appPool != null)
                {
                    base.Log.LogMessage("Updating IIS application pool '" + appPoolName + "'...");
                }
                else
                {
                    base.Log.LogMessage("Creating IIS application pool '" + appPoolName + "'...");
                    appPool = mgr.ApplicationPools.Add(appPoolName);
                }
            }
            else if (action == ActionType.Create)
            {
                if (appPool != null)
                {
                    base.Log.LogWarning("DeployAction is set to Create but the IIS application pool '" + appPoolName + "' already exists. Skipping.");
                    return(true);
                }

                base.Log.LogMessage("Creating IIS application pool '" + appPoolName + "'...");
                appPool = mgr.ApplicationPools.Add(appPoolName);
            }
            else if (action == ActionType.Update)
            {
                if (appPool == null)
                {
                    base.Log.LogError("DeployAction is set to Update but the IIS application pool '" + appPoolName + "' does not exist.");
                    return(false);
                }

                base.Log.LogMessage("Updating IIS application pool '" + appPoolName + "'...");
            }

            if (identityType == ProcessModelIdentityType.SpecificUser)
            {
                appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                appPool.ProcessModel.UserName     = userName;
                appPool.ProcessModel.Password     = password;
            }
            else
            {
                appPool.ProcessModel.IdentityType = identityType;
            }

            appPool.ManagedRuntimeVersion = managedRuntimeVersion;
            appPool.AutoStart             = autoStart;
            appPool.Enable32BitAppOnWin64 = enable32BitAppOnWin64;
            appPool.ManagedPipelineMode   = managedPipelineMode;

            mgr.CommitChanges();
            base.Log.LogMessage("Created/updated IIS application pool '" + appPoolName + "'.");

            return(true);
        }
Пример #20
0
        public static void SetMwaApplicationPool(ILogSink logger, IisAppPoolConfiguration config, ApplicationPool pool)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            var configProperties = Persistence.GetPersistentProperties(config.GetType(), false)
                                   .Where(p => Attribute.IsDefined(p, typeof(ScriptAliasAttribute)));

            foreach (var configProperty in configProperties)
            {
                if (SkipTemplateProperty(config, configProperty))
                {
                    continue;
                }

                object value = configProperty.GetValue(config);

                var mappedProperty = FindMatchingProperty(configProperty.Name.Split('_'), pool);
                if (mappedProperty != null)
                {
                    mappedProperty.SetValue(value);
                }
                else
                {
                    logger.LogWarning($"Matching MWA property \"{configProperty.Name}\" was not found.");
                }
            }
        }
Пример #21
0
        public static IisAppPoolConfiguration FromMwaApplicationPool(ILogSink logger, ApplicationPool pool, IisAppPoolConfiguration template = null)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            var config = new IisAppPoolConfiguration();

            config.Name   = pool.Name;
            config.Status = (IisObjectState)pool.State;
            if (template == null)
            {
                return(config);
            }

            var templateProperties = Persistence.GetPersistentProperties(template.GetType(), false)
                                     .Where(p => Attribute.IsDefined(p, typeof(ScriptAliasAttribute)));

            foreach (var templateProperty in templateProperties)
            {
                if (SkipTemplateProperty(template, templateProperty))
                {
                    continue;
                }

                var mappedProperty = FindMatchingProperty(templateProperty.Name.Split('_'), pool);
                if (mappedProperty != null)
                {
                    templateProperty.SetValue(config, mappedProperty.GetValue());
                }
                else
                {
                    logger.LogWarning($"Matching MWA property \"{templateProperty.Name}\" was not found.");
                }
            }

            return(config);
        }
Пример #22
0
        /// <summary>
        /// Adds a virtual application to a IIS site
        /// </summary>
        /// <param name="settings">The settings of the application to add</param>
        /// <returns>If the application was added.</returns>
        public bool AddApplication(ApplicationSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (string.IsNullOrWhiteSpace(settings.SiteName))
            {
                throw new ArgumentException("Site name cannot be null!");
            }

            if (string.IsNullOrWhiteSpace(settings.ApplicationPath))
            {
                throw new ArgumentException("Applicaiton path cannot be null!");
            }



            //Get Pool
            ApplicationPool appPool = _Server.ApplicationPools.SingleOrDefault(p => p.Name == settings.ApplicationPool);

            if (appPool == null)
            {
                throw new Exception("Application Pool '" + settings.ApplicationPool + "' does not exist.");
            }



            //Get Site
            Site site = _Server.Sites.SingleOrDefault(p => p.Name == settings.SiteName);

            if (site != null)
            {
                //Get Application
                Application app = site.Applications.SingleOrDefault(p => p.Path == settings.ApplicationPath);

                if (app != null)
                {
                    throw new Exception("Application '" + settings.ApplicationPath + "' already exists.");
                }

                app      = site.Applications.CreateElement();
                app.Path = settings.ApplicationPath;
                app.ApplicationPoolName = settings.ApplicationPool;

                if (!String.IsNullOrEmpty(settings.AlternateEnabledProtocols))
                {
                    app.EnabledProtocols = settings.AlternateEnabledProtocols;
                }

                //Get Directory
                VirtualDirectory vDir = app.VirtualDirectories.CreateElement();
                // While creating application only ApplicationPath is used by IIS, so we leave default one here.
                vDir.Path         = "/";
                vDir.PhysicalPath = this.GetPhysicalDirectory(settings);

                app.VirtualDirectories.Add(vDir);

                // Security
                var serverType = "webServer";
                var hostConfig = GetWebConfiguration();

                hostConfig.SetAuthentication(serverType, settings.SiteName, settings.ApplicationPath, settings.Authentication, _Log);
                hostConfig.SetAuthorization(serverType, settings.SiteName, settings.ApplicationPath, settings.Authorization);

                // Commit
                site.Applications.Add(app);
                _Server.CommitChanges();

                // Settings that need to be modified after the app is created
                var isModified = false;

                if (settings.EnableDirectoryBrowsing)
                {
                    var appConfig = app.GetWebConfiguration();
                    appConfig.EnableDirectoryBrowsing();
                    isModified = true;
                }

                if (isModified)
                {
                    _Server.CommitChanges();
                }

                return(true);
            }
            else
            {
                throw new Exception("Site '" + settings.SiteName + "' does not exist.");
            }
        }
Пример #23
0
        static void Main(string[] args)
        {
            var hostFile    = Path.Combine(Environment.SystemDirectory, "drivers\\etc\\hosts");
            var hostContent = File.ReadAllText(hostFile);

            if (!hostContent.Contains("sso.baibaomen.com"))
            {
                Console.WriteLine("正在添加演示域名到host文件");
                var toAppend = @"
127.0.0.1 sso.baibaomen.com
127.0.0.1 java-client.net
127.0.0.1 php-client.cn";
                File.AppendAllText(hostFile, toAppend);
            }
            else
            {
                Console.WriteLine("演示域名已存在于host文件中,跳过添加步骤");
            }

            Console.WriteLine("正在安装证书");

            string certFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wildcard.baibaomen.com.pfx");
            var    cert     = new X509Certificate2(File.ReadAllBytes(certFile), "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

            InstallCert(new X509Store(StoreName.Root, StoreLocation.LocalMachine), cert);

            InstallCert(new X509Store(StoreName.My, StoreLocation.LocalMachine), cert);

            ServerManager iisManager = new ServerManager();

            var smSite = iisManager.Sites.FirstOrDefault(s => s.Name.Contains("sso.baibaomen.com"));

            if (smSite == null)
            {
                Console.WriteLine("正在创建IIS站点");

                var sites = new string[] { "sso.baibaomen.com", "java-client.net", "php-client.cn" };

                foreach (var site in sites)
                {
                    ApplicationPool newPool = iisManager.ApplicationPools.Add(site);
                    newPool.ManagedRuntimeVersion = "v4.0";
                    newPool.ManagedPipelineMode   = ManagedPipelineMode.Integrated;
                }

                iisManager.CommitChanges();

                foreach (var site in sites)
                {
                    iisManager.Sites.Add(site, "http", "*:80:" + site, Path.Combine(RootFolderPath, "Lesson1\\" + site));
                    var theSite = iisManager.Sites.FirstOrDefault(s => s.Name.Equals(site));
                    theSite.ApplicationDefaults.ApplicationPoolName = site;
                }

                iisManager.CommitChanges();

                smSite = iisManager.Sites.FirstOrDefault(s => s.Name.Equals("sso.baibaomen.com"));
                Binding binding = smSite.Bindings.CreateElement("binding");
                binding["protocol"]             = "https";
                binding["certificateHash"]      = cert.GetCertHashString();
                binding["certificateStoreName"] = "Root";
                binding["bindingInformation"]   = "*:443:sso.baibaomen.com";
                smSite.Bindings.Add(binding);
                iisManager.CommitChanges();
            }
            else
            {
                Console.WriteLine("IIS站点已存在,跳过创建");
            }

            Console.WriteLine("正在打开站点页面");

            var p = Process.Start("https://sso.baibaomen.com");

            p = Process.Start("http://java-client.net");
            p = Process.Start("http://php-client.cn");
        }
Пример #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="applicationPoolName"></param>
 /// <param name="identityType"></param>
 /// <param name="applicationPoolIdentity"></param>
 /// <param name="password"></param>
 /// <param name="managedRuntimeVersion"></param>
 /// <param name="autoStart"></param>
 /// <param name="enable32BitAppOnWin64"></param>
 /// <param name="managedPipelineMode"></param>
 /// <param name="queueLength"></param>
 /// <param name="idleTimeout"></param>
 /// <param name="periodicRestartPrivateMemory"></param>
 /// <param name="periodicRestartTime"></param>
 /// <returns></returns>
 public static bool CreateApplicationPool(string applicationPoolName, ProcessModelIdentityType identityType, string applicationPoolIdentity, string password,
                                          string managedRuntimeVersion, bool autoStart, bool enable32BitAppOnWin64, ManagedPipelineMode managedPipelineMode, long queueLength, TimeSpan idleTimeout,
                                          long periodicRestartPrivateMemory, TimeSpan periodicRestartTime)
 {
     try
     {
         if (identityType == ProcessModelIdentityType.SpecificUser)
         {
             if (string.IsNullOrEmpty(applicationPoolName))
             {
                 throw new ArgumentNullException("applicationPoolName", "CreateApplicationPool: applicationPoolName is null or empty.");
             }
             if (string.IsNullOrEmpty(applicationPoolIdentity))
             {
                 throw new ArgumentNullException("applicationPoolIdentity", "CreateApplicationPool: applicationPoolIdentity is null or empty.");
             }
             if (string.IsNullOrEmpty(password))
             {
                 throw new ArgumentNullException("password", "CreateApplicationPool: password is null or empty.");
             }
         }
         using (ServerManager mgr = new ServerManager())
         {
             if (mgr.ApplicationPools[applicationPoolName] != null)
             {
                 return(true);   // already exists
             }
             ApplicationPool newAppPool = mgr.ApplicationPools.Add(applicationPoolName);
             if (identityType == ProcessModelIdentityType.SpecificUser)
             {
                 newAppPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                 newAppPool.ProcessModel.UserName     = applicationPoolIdentity;
                 newAppPool.ProcessModel.Password     = password;
             }
             else
             {
                 newAppPool.ProcessModel.IdentityType = identityType;
             }
             if (!string.IsNullOrEmpty(managedRuntimeVersion))
             {
                 newAppPool.ManagedRuntimeVersion = managedRuntimeVersion;
             }
             newAppPool.AutoStart             = autoStart;
             newAppPool.Enable32BitAppOnWin64 = enable32BitAppOnWin64;
             newAppPool.ManagedPipelineMode   = managedPipelineMode;
             if (queueLength > 0)
             {
                 newAppPool.QueueLength = queueLength;
             }
             if (idleTimeout != TimeSpan.MinValue)
             {
                 newAppPool.ProcessModel.IdleTimeout = idleTimeout;
             }
             if (periodicRestartPrivateMemory > 0)
             {
                 newAppPool.Recycling.PeriodicRestart.PrivateMemory = periodicRestartPrivateMemory;
             }
             if (periodicRestartTime != TimeSpan.MinValue)
             {
                 newAppPool.Recycling.PeriodicRestart.Time = periodicRestartTime;
             }
             mgr.CommitChanges();
         }
     }
     catch// (Exception ex)
     {
         throw;
     }
     return(true);
 }
Пример #25
0
        private bool Deploy(ServerManager mgr, ITaskItem ti)
        {
            string appPoolName  = ti.GetMetadata("AppPoolName");
            string physicalPath = ti.GetMetadata("PhysicalPath");

            if (string.IsNullOrWhiteSpace(physicalPath) || string.IsNullOrWhiteSpace(appPoolName))
            {
                base.Log.LogError("Required metadata values PhysicalPath or AppPoolName are missing.");
                return(false);
            }

            // Convert a relative path to an absolute path
            if (!Path.IsPathRooted(physicalPath))
            {
                string currentDirectory = Environment.CurrentDirectory;
                Environment.CurrentDirectory = this.MSBuildProjectDirectory;
                physicalPath = new DirectoryInfo(physicalPath).FullName;
                Environment.CurrentDirectory = currentDirectory;
            }

            ApplicationPool appPool = mgr.ApplicationPools[appPoolName];

            if (appPool == null)
            {
                base.Log.LogError("Cannot find IIS application pool '" + appPoolName + "'.");
                return(false);
            }

            string userName = null;

            switch (appPool.ProcessModel.IdentityType)
            {
            case ProcessModelIdentityType.LocalService:
                userName = "******";
                break;

            case ProcessModelIdentityType.LocalSystem:
                userName = "******";
                break;

            case ProcessModelIdentityType.NetworkService:
                userName = "******";
                break;

            case ProcessModelIdentityType.SpecificUser:
                userName = appPool.ProcessModel.UserName;
                userName = userName.Replace(".\\", string.Empty);
                break;

            case ProcessModelIdentityType.ApplicationPoolIdentity:
                userName = @"IIS AppPool\" + appPoolName;
                break;

            default:
                base.Log.LogError("Invalid value in IdentityType metadata element");
                return(false);
            }

            base.Log.LogMessage("Granting NTFS permissions on '" + physicalPath + "' to '" + userName + "'...");
            SetDirectorySecurity(physicalPath, userName, FileSystemRights.ReadAndExecute | FileSystemRights.ListDirectory, AccessControlType.Allow);
            base.Log.LogMessage("Granted NTFS permissions on '" + physicalPath + "'.");

            return(true);
        }
Пример #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="applicationPath"></param>
        /// <param name="applicationPool"></param>
        /// <param name="virtualDirectoryPath"></param>
        /// <param name="physicalPath"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool AddApplication(string siteName, string applicationPath, string applicationPool, string physicalPath, string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(siteName))
                {
                    throw new ArgumentNullException("siteName", "AddApplication: siteName is null or empty.");
                }
                if (string.IsNullOrEmpty(applicationPath))
                {
                    throw new ArgumentNullException("applicationPath", "AddApplication: application path is null or empty.");
                }
                if (string.IsNullOrEmpty(physicalPath))
                {
                    throw new ArgumentNullException("PhysicalPath", "AddApplication: Invalid physical path.");
                }
                if (string.IsNullOrEmpty(applicationPool))
                {
                    throw new ArgumentNullException("ApplicationPool", "AddApplication: application pool namespace is Nullable or empty.");
                }
                using (ServerManager mgr = new ServerManager())
                {
                    ApplicationPool appPool = mgr.ApplicationPools[applicationPool];
                    if (appPool == null)
                    {
                        throw new Exception("Application Pool: " + applicationPool + " does not exist.");
                    }

                    Site site = mgr.Sites[siteName];
                    if (site != null)
                    {
                        Application app = site.Applications[applicationPath];
                        if (app != null)
                        {
                            throw new Exception("Application: " + applicationPath + " already exists.");
                        }
                        else
                        {
                            app = site.Applications.Add(applicationPath, physicalPath);
                            app.ApplicationPoolName = applicationPool;

                            //VirtualDirectory vDir = app.VirtualDirectories.CreateElement();
                            //vDir.Path = virtualDirectoryPath;
                            //vDir.PhysicalPath = physicalPath;
                            //if (!string.IsNullOrEmpty(userName))
                            //{
                            //    if (string.IsNullOrEmpty(password))
                            //        throw new Exception("Invalid Virtual Directory User Account Password.");
                            //    else
                            //    {
                            //        vDir.UserName = userName;
                            //        vDir.Password = password;
                            //    }
                            //}
                            //app.VirtualDirectories.Add(vDir);
                        }
                        //site.Applications.Add(app);
                        mgr.CommitChanges();
                        return(true);
                    }
                    else
                    {
                        throw new Exception("Site: " + siteName + " does not exist.");
                    }
                }
            }
            catch// (Exception ex)
            {
                throw;
            }
        }
Пример #27
0
        /// <summary>
        /// 部署
        /// </summary>
        /// <param name="stnm"></param>
        /// <param name="tcode"></param>
        /// <param name="ip"></param>
        public override void Deploy(string stnm, string tcode, string ip)
        {
            bool flag = false;

            try
            {
                //查询网络站点
                bool          WebIsExist = false;
                ServerManager sm         = new ServerManager();
                for (int i = 0; i < sm.Sites.Count; i++)
                {
                    if (sm.Sites[i].Name.ToLower() == name.ToLower())
                    {
                        WebIsExist = true; break;
                    }
                }
                //判断站点是否存在
                if (WebIsExist)
                {
                    report.Add(comment + "升级...");
                    flag = Update(stnm, tcode, ip);//升级
                }
                else
                {
                    report.Add(comment + "安装...");
                    //通用安装
                    if (!Install(stnm, tcode, ip))
                    {
                        return;
                    }

                    try
                    {
                        report.Add("创建程序池...");
                        if (sm.ApplicationPools[name] == null)
                        {
                            sm.ApplicationPools.Add(name);
                            ApplicationPool curAppPool = sm.ApplicationPools[name];
                            curAppPool.ManagedPipelineMode                  = ManagedPipelineMode.Integrated;
                            curAppPool.Failure.RapidFailProtection          = true;
                            curAppPool.Enable32BitAppOnWin64                = true;
                            sm.ApplicationPools[name].ManagedRuntimeVersion = "v4.0";//必须这么写才能选中默认V4.0.30319
                            curAppPool.AutoStart = true;
                        }
                        report.Add("创建站点...");
                        DirectoryInfo dir = GetDir_FromDeploy(name);

                        Site curweb = sm.Sites.Add(name, "http", ip + ":" + port + ":", dir.FullName);
                        //绑定默认IP
                        curweb.Bindings.Add("202.202.202.1:" + port + ":", "http");
                        curweb.Applications[0].ApplicationPoolName = name;
                        //开启站点
                        if (AutoStart)
                        {
                            curweb.ServerAutoStart = true;
                        }

                        report.Add("创建虚拟目录...");
                        foreach (KeyValuePair <string, string> vf in list_vf)
                        {
                            curweb.Applications[0].VirtualDirectories.Add("/" + vf.Key, vf.Value);
                        }

                        report.Add("设置权限...");
                        Helper_FileDir.AddSecurityControll2Folder(dir.FullName);
                        sm.CommitChanges();

                        if (Directory.Exists(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319"))
                        {
                            report.Add("注册IIS...");
                            List <string> cmds = new List <string>();
                            cmds.Add(@"cd C:\Windows\Microsoft.NET\Framework\v4.0.30319");
                            cmds.Add("C:");//切换盘符
                            cmds.Add("aspnet_regiis.exe -i");
                            cmds.Add("exit");
                            Common_Handle.RunCMD(cmds);
                        }
                        flag = true;
                    }
                    catch (Exception e) { report.Error("站点搭建异常", e); }
                }
            }
            catch (Exception e)
            {
                report.Error("部署" + comment + "异常", e);
            }
            finally
            {
                report.Add("部署-" + comment, flag ? "成功" : "失败");
            }
        }
Пример #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="applicationPoolName"></param>
        /// <param name="siteName"></param>
        /// <param name="domainName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="contentPath"></param>
        /// <param name="ipAddress"></param>
        /// <param name="tcpPort"></param>
        /// <param name="hostHeader"></param>
        /// <returns></returns>
        public static bool CreateFtpSite(string applicationPoolName, string siteName, string domainName, string userName, string password, string contentPath, string ipAddress, string tcpPort, string hostHeader)
        {
            try
            {
                //provision the application pool
                using (ServerManager mgr = new ServerManager())
                {
                    ApplicationPool appPool = mgr.ApplicationPools[applicationPoolName];

                    //per IIS7 team recommendation, we always create a new application pool
                    //create new application pool
                    if (appPool == null)
                    {
                        appPool = mgr.ApplicationPools.Add(applicationPoolName);

                        //set the application pool attribute
                        appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                        appPool.ProcessModel.UserName     = domainName + "\\" + userName;
                        appPool.ProcessModel.Password     = password;
                    }

                    //if the appPool is null, we throw an exception. The appPool should be created or already exists.
                    if (appPool == null)
                    {
                        throw new Exception("Invalid Application Pool.");
                    }

                    //if the site already exists, throw an exception
                    if (mgr.Sites[siteName] != null)
                    {
                        throw new Exception("Site already exists.");
                    }

                    //create site
                    Site newSite = mgr.Sites.CreateElement();
                    newSite.Id = GenerateNewSiteID(mgr, siteName);
                    newSite.SetAttributeValue("name", siteName);
                    newSite.ServerAutoStart = true;
                    mgr.Sites.Add(newSite);

                    //create the default application for the site
                    Application newApp = newSite.Applications.CreateElement();
                    newApp.SetAttributeValue("path", "/"); //set to default root path
                    newApp.SetAttributeValue("applicationPool", applicationPoolName);
                    newSite.Applications.Add(newApp);

                    //create the default virtual directory
                    VirtualDirectory newVirtualDirectory = newApp.VirtualDirectories.CreateElement();
                    newVirtualDirectory.SetAttributeValue("path", "/");
                    newVirtualDirectory.SetAttributeValue("physicalPath", contentPath);
                    newApp.VirtualDirectories.Add(newVirtualDirectory);

                    //add the bindings
                    Binding binding = newSite.Bindings.CreateElement();
                    binding.SetAttributeValue("protocol", "ftp");
                    binding.SetAttributeValue("bindingInformation", ipAddress + ":" + tcpPort + ":" + hostHeader);
                    newSite.Bindings.Add(binding);


                    //commit the changes
                    mgr.CommitChanges();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
            return(true);
        }
Пример #29
0
        /// <summary>
        /// Removes the application - reachable at the specified port - and its application pools from IIS.
        /// Note: Stops the application pools and the application if necessary
        /// </summary>
        /// <param name="port">The port.</param>
        private static void Delete(int port)
        {
            mut.WaitOne();

            try
            {
                using (ServerManager serverMgr = new ServerManager())
                {
                    Site currentSite = null;
                    foreach (Site site in serverMgr.Sites)
                    {
                        if (site.Bindings[0].EndPoint.Port == port)
                        {
                            currentSite = site;
                            break;
                        }
                    }

                    int retryCount = 20;
                    while (retryCount > 0)
                    {
                        try
                        {
                            serverMgr.Sites[currentSite.Name].Stop();
                            break;
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            // todo log exception
                        }

                        retryCount--;
                    }

                    int time = 0;
                    while (serverMgr.Sites[currentSite.Name].State != ObjectState.Stopped && time < 300)
                    {
                        Thread.Sleep(100);
                        time++;
                    }

                    if (time == 300)
                    {
                        KillApplicationProcesses(currentSite.Applications["/"].ApplicationPoolName);
                    }

                    serverMgr.Sites.Remove(currentSite);
                    serverMgr.CommitChanges();
                    FirewallTools.ClosePort(port);
                    ApplicationPool applicationPool = serverMgr.ApplicationPools[currentSite.Applications["/"].ApplicationPoolName];
                    serverMgr.ApplicationPools[applicationPool.Name].Stop();
                    time = 0;
                    while (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time < 300)
                    {
                        Thread.Sleep(100);
                        time++;
                    }

                    if (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time == 300)
                    {
                        KillApplicationProcesses(applicationPool.Name);
                    }

                    serverMgr.ApplicationPools.Remove(applicationPool);
                    serverMgr.CommitChanges();
                    string username = null;
                    username = applicationPool.ProcessModel.UserName;
                    if (username != null)
                    {
                        string path = currentSite.Applications["/"].VirtualDirectories["/"].PhysicalPath;
                        if (Directory.Exists(path))
                        {
                            DirectoryInfo     deploymentDir         = new DirectoryInfo(path);
                            DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();
                            deploymentDirSecurity.RemoveAccessRuleAll(new FileSystemAccessRule(username, FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow));
                            deploymentDir.SetAccessControl(deploymentDirSecurity);
                        }
                    }
                }
            }
            finally
            {
                mut.ReleaseMutex();
            }
        }
Пример #30
0
        private static Site SetSite(Site site, dynamic model, IFileProvider fileProvider)
        {
            Debug.Assert(site != null);
            Debug.Assert((bool)(model != null));

            //
            // Name
            DynamicHelper.If((object)model.name, v => { site.Name = v; });

            //
            // Server Auto Start
            site.ServerAutoStart = DynamicHelper.To <bool>(model.server_auto_start) ?? site.ServerAutoStart;


            //
            // Physical Path
            string physicalPath = DynamicHelper.Value(model.physical_path);

            if (physicalPath != null)
            {
                physicalPath = physicalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                var expanded = System.Environment.ExpandEnvironmentVariables(physicalPath);

                if (!PathUtil.IsFullPath(expanded))
                {
                    throw new ApiArgumentException("physical_path");
                }
                if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read))
                {
                    throw new ForbiddenArgumentException("physical_path", physicalPath);
                }
                if (!Directory.Exists(expanded))
                {
                    throw new NotFoundException("physical_path");
                }

                var rootApp = site.Applications["/"];
                if (rootApp != null)
                {
                    var rootVDir = rootApp.VirtualDirectories["/"];

                    if (rootVDir != null)
                    {
                        rootVDir.PhysicalPath = physicalPath;
                    }
                }
            }

            //
            // Enabled Protocols
            string enabledProtocols = DynamicHelper.Value(model.enabled_protocols);

            if (enabledProtocols != null)
            {
                var rootApp = site.Applications["/"];

                if (rootApp != null)
                {
                    rootApp.EnabledProtocols = enabledProtocols;
                }
            }

            //
            // Limits
            if (model.limits != null)
            {
                dynamic limits = model.limits;

                site.Limits.MaxBandwidth   = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth;
                site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections;

                if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute))
                {
                    site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments;
                }

                long?connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue);
                site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout;
            }

            //
            // Bindings
            if (model.bindings != null)
            {
                IEnumerable <dynamic> bindings = (IEnumerable <dynamic>)model.bindings;

                // If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in
                // the foreach loop.
                // This means that the bindings collection won't be deleted, so the bindings are safe from harm.

                List <Binding> newBindings = new List <Binding>();

                // Iterate over the bindings to create a new binding list
                foreach (dynamic b in bindings)
                {
                    Binding binding = site.Bindings.CreateElement();
                    SetBinding(binding, b);

                    foreach (Binding addedBinding in newBindings)
                    {
                        if (addedBinding.Protocol.Equals(binding.Protocol, StringComparison.OrdinalIgnoreCase) &&
                            addedBinding.BindingInformation.Equals(binding.BindingInformation, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new AlreadyExistsException("binding");
                        }
                    }

                    // Add to bindings list
                    newBindings.Add(binding);
                }

                // All bindings have been verified and added to the list
                // Clear the old list, and add the new
                site.Bindings.Clear();
                newBindings.ForEach(binding => site.Bindings.Add(binding));
            }

            //
            // App Pool
            if (model.application_pool != null)
            {
                // Extract the uuid from the application_pool object provided in model
                string appPoolUuid = DynamicHelper.Value(model.application_pool.id);

                // It is an error to provide an application pool object without specifying its id property
                if (appPoolUuid == null)
                {
                    throw new ApiArgumentException("application_pool.id");
                }

                // Create application pool id object from uuid provided, use this to obtain the application pool
                AppPoolId       appPoolId = AppPoolId.CreateFromUuid(appPoolUuid);
                ApplicationPool pool      = AppPoolHelper.GetAppPool(appPoolId.Name);

                Application rootApp = site.Applications["/"];

                if (rootApp == null)
                {
                    throw new ApiArgumentException("application_pool", "Root application does not exist.");
                }

                // REVIEW: Should we create the root application if it doesn't exist and they specify an application pool?
                // We decided not to do this for physical_path.
                // Application pool for a site is extracted from the site's root application
                rootApp.ApplicationPoolName = pool.Name;
            }

            return(site);
        }