Beispiel #1
0
        public static void GetApplicationPoolsAssociatedWithServer()
        {
            ServerManager server = new ServerManager();

            ApplicationPoolCollection applicationPools = server.ApplicationPools;

            foreach (ApplicationPool pool in applicationPools)
            {
                //get the AutoStart boolean value
                bool autoStart = pool.AutoStart;

                //get the name of the ManagedRuntimeVersion
                string runtime = pool.ManagedRuntimeVersion;

                //get the name of the ApplicationPool
                string appPoolName = pool.Name;

                //get the identity type
                ProcessModelIdentityType identityType = pool.ProcessModel.IdentityType;

                //get the username for the identity under which the pool runs
                string userName = pool.ProcessModel.UserName;

                //get the password for the identity under which the pool runs
                string password = pool.ProcessModel.Password;
            }
        }
Beispiel #2
0
        public override void RegisterRealTasks(PhysicalServer s)
        {
            var scrubbedPath = _path.GetPhysicalPath(s, PathOnServer, true);

            if (Version == IisVersion.Six)
            {
                s.AddTask(new Iis6Task
                {
                    PathOnServer         = scrubbedPath,
                    ServerName           = s.Name,
                    VirtualDirectoryPath = VdirPath,
                    WebsiteName          = WebsiteName,
                    AppPoolName          = AppPoolName
                });
                return;
            }
            s.AddTask(new Iis7Task
            {
                PathOnServer             = scrubbedPath,
                ServerName               = s.Name,
                VirtualDirectoryPath     = VdirPath,
                WebsiteName              = WebsiteName,
                AppPoolName              = AppPoolName,
                UseClassicPipeline       = ClassicPipelineRequested,
                ManagedRuntimeVersion    = this.ManagedRuntimeVersion,
                PathForWebsite           = this.PathForWebsite,
                PortForWebsite           = this.PortForWebsite,
                Enable32BitAppOnWin64    = Bit32Requested,
                SetProcessModelIdentity  = this.ProcessModelIdentityTypeSpecified,
                ProcessModelIdentityType = ProcessModelIdentityType.ToProcessModelIdentityType(),
                ProcessModelUsername     = this.ProcessModelUsername,
                ProcessModelPassword     = this.ProcessModelPassword,
                AuthenticationToSet      = this.AuthenticationToSet
            });
        }
Beispiel #3
0
        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.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();
            }
        }
Beispiel #4
0
        void SetApplicationPoolIdentity(ApplicationPool pool)
        {
            if (ProcessModelIdentityType != ProcessModelIdentityType.SpecificUser && pool.ProcessModel.IdentityType == ProcessModelIdentityType)
            {
                return;
            }

            pool.ProcessModel.IdentityType = ProcessModelIdentityType;
            var identityUsername = ProcessModelIdentityType.ToString();

            if (ProcessModelIdentityType == ProcessModelIdentityType.SpecificUser)
            {
                pool.ProcessModel.UserName = ProcessModelUsername;
                pool.ProcessModel.Password = ProcessModelPassword;
                identityUsername           = ProcessModelUsername;
            }
            LogIis("[iis7] Set process model identity '{0}'", identityUsername);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            DirectoryEntries appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children;

            foreach (DirectoryEntry appPool in appPools)
            {
                Console.WriteLine(appPool.Name);
            }

            //M-II
            foreach (var appPool in new ServerManager().ApplicationPools)
            {
                Console.WriteLine(appPool.Name);
            }


            //M-III
            ServerManager server = new ServerManager();

            ApplicationPoolCollection applicationPools = server.ApplicationPools;

            foreach (ApplicationPool pool in applicationPools)
            {
                //get the AutoStart boolean value
                bool autoStart = pool.AutoStart;

                //get the name of the ManagedRuntimeVersion
                string runtime = pool.ManagedRuntimeVersion;

                //get the name of the ApplicationPool
                string appPoolName = pool.Name;

                //get the identity type
                ProcessModelIdentityType identityType = pool.ProcessModel.IdentityType;

                //get the username for the identity under which the pool runs
                string userName = pool.ProcessModel.UserName;

                //get the password for the identity under which the pool runs
                string password = pool.ProcessModel.Password;
            }

            Console.ReadKey();
        }
        public override string Execute(IHoconElement param)
        {
            var hobj = param as HoconObject;

            if (hobj == null)
            {
                throw new Exception("change-pool command param error");
            }
            var name         = hobj.GetKey("Name").GetString();
            var identityType = hobj.GetKey("IdentityType")?.GetString() ?? "NetworkService";
            var version      = hobj.GetKey("RunTimeVersion")?.GetString() ?? "v4.0";
            ProcessModelIdentityType itype = ProcessModelIdentityType.NetworkService;

            switch (identityType)
            {
            case "NetworkService":
                itype = ProcessModelIdentityType.NetworkService;
                break;

            case "LocalService":
                itype = ProcessModelIdentityType.LocalService;
                break;

            case "LocalSystem":
                itype = ProcessModelIdentityType.LocalSystem;
                break;

            case "ApplicationPoolIdentity":
                itype = ProcessModelIdentityType.ApplicationPoolIdentity;
                break;

            case "SpecificUser":
                itype = ProcessModelIdentityType.SpecificUser;
                break;

            default:
                throw new Exception($"IdentityType {identityType} set error");
            }
            var msg = ChangeAppPool(name, version, itype);

            return(msg);
        }
Beispiel #7
0
 private string CreateAppPool(string poolname, string runtimeVersion, ProcessModelIdentityType type)
 {
     using (ServerManager serverManager = new ServerManager())
     {
         var pools = serverManager.ApplicationPools;
         var pool  = pools[poolname];
         if (pool != null)
         {
             return($"pool {poolname} exist! need no create.");
         }
         ApplicationPool newPool = serverManager.ApplicationPools.Add(poolname);
         newPool.ManagedRuntimeVersion     = runtimeVersion;
         newPool.Enable32BitAppOnWin64     = true;
         newPool.ManagedPipelineMode       = ManagedPipelineMode.Integrated;
         newPool.ProcessModel.IdentityType = type;
         newPool.AutoStart = true;
         serverManager.CommitChanges();
     }
     return($"pool {poolname} create success!");
 }
        private bool Deploy(ServerManager mgr, ITaskItem ti, ModeType mode, ActionType action, string appPoolName)
        {
            string frameworkVersion = ti.GetMetadata("DotNetFrameworkVersion");
            string pipelineModeStr  = ti.GetMetadata("PipelineMode");
            string enable32BitStr   = ti.GetMetadata("Enable32Bit");
            string identityTypeStr  = ti.GetMetadata("IdentityType");
            string userName         = ti.GetMetadata("UserName");
            string password         = ti.GetMetadata("Password");

            bool enable32Bit;

            if (!bool.TryParse(enable32BitStr, out enable32Bit))
            {
                base.Log.LogError("Invalid Enable32Bit metadata value " + enable32BitStr);
                return(false);
            }

            ManagedPipelineMode pipelineMode = ManagedPipelineMode.Integrated;

            if (!Enum.TryParse <ManagedPipelineMode>(pipelineModeStr, true, out pipelineMode))
            {
                base.Log.LogError("Invalid PipelineMode metadata value " + pipelineModeStr);
                return(false);
            }

            ProcessModelIdentityType identityType = ProcessModelIdentityType.ApplicationPoolIdentity;

            if (!Enum.TryParse <ProcessModelIdentityType>(identityTypeStr, true, out identityType))
            {
                base.Log.LogError("Invalid IdentityType metadata value " + identityTypeStr);
                return(false);
            }

            if (identityType == ProcessModelIdentityType.SpecificUser && (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)))
            {
                base.Log.LogError("IdentityType is set to SpecificUser but either the UserName or the Password is missing.");
                return(false);
            }

            return(DeployApplicationPool(mgr, action, appPoolName, identityType, userName, password, frameworkVersion, true, enable32Bit, pipelineMode));
        }
 private string ChangeAppPool(string poolname, string runtimeVersion, ProcessModelIdentityType type)
 {
     using (ServerManager serverManager = new ServerManager())
     {
         var pools = serverManager.ApplicationPools;
         var pool  = pools[poolname];
         if (pool == null)
         {
             return($"pool {poolname} not exist! can not change.");
         }
         pool.Stop();
         pool.ManagedRuntimeVersion     = runtimeVersion;
         pool.Enable32BitAppOnWin64     = true;
         pool.ManagedPipelineMode       = ManagedPipelineMode.Integrated;
         pool.ProcessModel.IdentityType = type;
         pool.AutoStart = true;
         pool.Start();
         serverManager.CommitChanges();
     }
     return($"pool {poolname} change success!");
 }
Beispiel #10
0
        private static Site CreateSite(string siteName, string framework, string path, int port, ProcessModelIdentityType identityType)
        {
            var serverManager = new ServerManager();
            if (serverManager.ApplicationPools.Any(ap => ap.Name == siteName)) {
                Debug("Removing existing AppPool {0}", siteName);
                serverManager.ApplicationPools.Remove(serverManager.ApplicationPools.Single(ap => ap.Name == siteName));
            }

            Debug("Creating new AppPool {0}, Framework={1}, IdentityType={2}", siteName, framework, identityType);

            var applicationPool = serverManager.ApplicationPools.Add(siteName);
            applicationPool.ManagedRuntimeVersion = framework;
            applicationPool.Enable32BitAppOnWin64 = true;
            applicationPool.ProcessModel.IdentityType = identityType;
            applicationPool.ProcessModel.IdleTimeout = new TimeSpan(7,0,0);

            /** Try to preserve the site so any external settings (such as log formats etc) are preserved */
            Site site;

            if (serverManager.Sites.Any(si => si.Name == siteName))
            {
                Debug("Found existing site {0}, updating port={1} and path={2}", siteName, port, path);
                site = serverManager.Sites.Single(si => si.Name == siteName);
                site.Bindings[0].BindingInformation = String.Format("*:{0}:*", port);
                site.Applications[0].VirtualDirectories["/"].PhysicalPath = path;
            }
            else
            {
                Debug("Creating new Site {0}, Path={1}, Port={2}", siteName, path, port);
                site = serverManager.Sites.Add(siteName, path, port);
            }

            site.ServerAutoStart = true;
            site.Applications[0].ApplicationPoolName = siteName;
            serverManager.CommitChanges();
            System.Threading.Thread.Sleep(500);
            Debug("Starting site");
            site.Start();
            return site;
        }
Beispiel #11
0
        /// <summary>
        /// Creates the or update application pool.
        /// </summary>
        /// <param name="applicationPool">The application pool.</param>
        /// <returns></returns>
        private void CreateOrUpdateApplicationPool(ApplicationPool applicationPool)
        {
            using (var serverManager = new ServerManager())
            {
                var existingPool = serverManager.ApplicationPools.FirstOrDefault(pool => pool.Name == applicationPool.Name) ??
                                   serverManager.ApplicationPools.Add(applicationPool.Name);

                existingPool.ManagedRuntimeVersion = applicationPool.ManagedRuntimeVersion;
                existingPool.AutoStart             = true;
                existingPool.Enable32BitAppOnWin64 = applicationPool.Enable32BitAppOnWin64;


                existingPool.ProcessModel.IdleTimeout = new TimeSpan(0, 0, applicationPool.IdleTimeout);
                ProcessModelIdentityType identityType;
                if (ProcessModelIdentityType.TryParse(applicationPool.Identity, true, out identityType))
                {
                    existingPool.ProcessModel.IdentityType = identityType;
                }

                serverManager.CommitChanges();
            }
        }
        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);
        }
Beispiel #13
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);
 }
Beispiel #14
0
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(ConsoleCtrlCheck, true);

            var    siteName          = "";
            var    port              = -1;
            var    framework         = "v4.0";
            var    showHelp          = false;
            var    stop              = false;
            var    identityType      = ProcessModelIdentityType.ApplicationPoolIdentity;
            string warmupURL         = null;
            var    waitForSiteToStop = true;

            var p = new OptionSet {
                { "n|name=", "name of the IIS site",
                  v => siteName = v },
                { "w|warmup=", "The URL to use for warmup (without host & port)",
                  v => warmupURL = v },
                { "s|stop", "stop the IIS site",
                  v => stop = true },
                { "p|port=", "port used by the iis site",
                  (int v) => port = v },
                { "f|framework=", "framework version used by the application pool: v2.0 or v4.0 (default)",
                  v => framework = v },
                { "h|help", "show this message and exit",
                  v => showHelp = true },
                { "d|debug", "output debug messages",
                  v => debug = true },
                { "x|exit", "exit without waiting for the site to stop (but after warmup",
                  v => waitForSiteToStop = false },
                { "i|identity=", "The IdentityType to use for Application pool",
                  i =>
                  {
                      if (!ProcessModelIdentityType.TryParse(i, true, out identityType))
                      {
                          Console.Error.WriteLine("Cannot parse identity: {0}", i);
                          throw new ArgumentException("identity");
                      }
                  } }
            };

            try
            {
                p.Parse(args);
            }
            catch (Exception)
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (showHelp || siteName == "")
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (stop)
            {
                StopSite(siteName);
                return;
            }

            if (port < 0)
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            string currentPath = Directory.GetCurrentDirectory();

            _newSite = CreateSite(siteName, framework, currentPath, port, identityType);
            if (warmupURL != null)
            {
                if (!Warmup(port, warmupURL))
                {
                    StopSite(siteName);
                    Environment.Exit(1);
                }
            }

            if (waitForSiteToStop)
            {
                WatchSite(_newSite);
            }
            Environment.Exit(0);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="runtimeVersion"></param>
        /// <param name="managedPipelineMode"></param>
        /// <param name="identityType"></param>
        /// <returns></returns>
        public AppPoolConfig AddAppPool(string name, string runtimeVersion, ManagedPipelineMode managedPipelineMode, ProcessModelIdentityType identityType)
        {
            var appPoolConfig = new AppPoolConfig(_mgr, _logger);

            return(appPoolConfig.AddAppPool(name, runtimeVersion, managedPipelineMode, identityType));
        }
Beispiel #16
0
        private static Site CreateSite(string siteName, string framework, string path, int port, ProcessModelIdentityType identityType)
        {
            var serverManager = new ServerManager();

            if (serverManager.ApplicationPools.Any(ap => ap.Name == siteName))
            {
                Debug("Removing existing AppPool {0}", siteName);
                serverManager.ApplicationPools.Remove(serverManager.ApplicationPools.Single(ap => ap.Name == siteName));
            }

            Debug("Creating new AppPool {0}, Framework={1}, IdentityType={2}", siteName, framework, identityType);

            var applicationPool = serverManager.ApplicationPools.Add(siteName);

            applicationPool.ManagedRuntimeVersion     = framework;
            applicationPool.Enable32BitAppOnWin64     = true;
            applicationPool.ProcessModel.IdentityType = identityType;
            applicationPool.ProcessModel.IdleTimeout  = new TimeSpan(7, 0, 0);


            /** Try to preserve the site so any external settings (such as log formats etc) are preserved */
            Site site;

            if (serverManager.Sites.Any(si => si.Name == siteName))
            {
                Debug("Found existing site {0}, updating port={1} and path={2}", siteName, port, path);
                site = serverManager.Sites.Single(si => si.Name == siteName);
                site.Bindings[0].BindingInformation = String.Format("*:{0}:*", port);
                site.Applications[0].VirtualDirectories["/"].PhysicalPath = path;
            }
            else
            {
                Debug("Creating new Site {0}, Path={1}, Port={2}", siteName, path, port);
                site = serverManager.Sites.Add(siteName, path, port);
            }

            site.ServerAutoStart = true;
            site.Applications[0].ApplicationPoolName = siteName;
            serverManager.CommitChanges();
            System.Threading.Thread.Sleep(500);
            Debug("Starting site");
            site.Start();
            return(site);
        }
Beispiel #17
0
        /// <summary>
        /// 新建网站站点
        /// </summary>
        /// <param name="siteName">站点名</param>
        /// <param name="protocol">站点协议,如:http</param>
        /// <param name="bindingInformation">绑定的相关信息 "*:&lt;port&gt;:&lt;hostname&gt;" <example>"*:80:myhost.com"</example></param>
        /// <param name="physicalPath">物理路径</param>
        /// <param name="createAppPool">是否新建应用程序池</param>
        /// <param name="appPoolName">应用程序池名称</param>
        /// <param name="queueLength">队列长度</param>
        /// <param name="identityType">进程模型标识</param>
        /// <param name="idleTimeout">闲着超时时间(秒)</param>
        /// <param name="appPoolUserName">应用程序池特殊用户的用户名</param>
        /// <param name="appPoolPassword">应用程序池特殊用户的密码</param>
        /// <param name="maxProcesses">最大工作进程数</param>
        /// <param name="appPoolPipelineMode">应用程序池托管管道模式</param>
        /// <param name="managedRuntimeVersion">.net clr版本</param>
        /// <param name="rapidFailProtectionMaxCrashes">最大故障数</param>
        /// <param name="logDirectoryPath">IIS日志目录路径</param>
        /// <param name="logFormat">日志格式</param>
        /// <param name="logExtFileFlags">日志存储的字段</param>
        /// <param name="loggingRolloverPeriod">日志的存储计划</param>
        /// <param name="logTruncateSize">日志单个文件最大大小(MB) 最小为1MB<paramref name="loggingRolloverPeriod">LoggingRolloverPeriod.MaxSize</paramref> </param>
        public static void CreateSite(string siteName, string protocol, string bindingInformation, string physicalPath, bool createAppPool, string appPoolName, long queueLength, ProcessModelIdentityType identityType, long idleTimeout, string appPoolUserName, string appPoolPassword, long maxProcesses, ManagedPipelineMode appPoolPipelineMode, string managedRuntimeVersion, long rapidFailProtectionMaxCrashes, string logDirectoryPath, LogFormat logFormat, LogExtFileFlags logExtFileFlags, LoggingRolloverPeriod loggingRolloverPeriod, long logTruncateSize)
        {
            if (logTruncateSize < 1)
            {
                throw new Exception("日志单个文件最大大小的值必须>=1MB");
            }
            using (var mgr = new ServerManager(ApplicationHostConfigurationPath))
            {
                var site = mgr.Sites[siteName];
                if (site == null)
                {
                    site = mgr.Sites.Add(siteName, protocol, bindingInformation, physicalPath);
                    site.LogFile.Enabled         = true;
                    site.ServerAutoStart         = true;
                    site.LogFile.Directory       = logDirectoryPath;
                    site.LogFile.Period          = loggingRolloverPeriod;
                    site.LogFile.LogExtFileFlags = logExtFileFlags;
                    site.LogFile.TruncateSize    = logTruncateSize * 1024 * 1024;
                    site.LogFile.LogFormat       = logFormat;

                    if (createAppPool)
                    {
                        var pool = mgr.ApplicationPools.Add(siteName);
                        pool.Name = appPoolName;
                        pool.ManagedRuntimeVersion     = managedRuntimeVersion;
                        pool.QueueLength               = queueLength;
                        pool.ProcessModel.MaxProcesses = maxProcesses;
                        if (pool.ProcessModel.IdentityType != identityType)
                        {
                            pool.ProcessModel.IdentityType = identityType;
                        }
                        pool.ProcessModel.IdleTimeout = TimeSpan.FromSeconds(idleTimeout);
                        if (!String.IsNullOrEmpty(appPoolUserName))
                        {
                            pool.ProcessModel.UserName = appPoolUserName;
                            pool.ProcessModel.Password = appPoolPassword;
                        }
                        if (pool.ManagedPipelineMode != appPoolPipelineMode)
                        {
                            pool.ManagedPipelineMode = appPoolPipelineMode;
                        }
                        pool.Failure.RapidFailProtectionMaxCrashes = rapidFailProtectionMaxCrashes;
                        mgr.Sites[siteName].Applications[0].ApplicationPoolName = pool.Name;
                    }
                    mgr.CommitChanges();
                }
                else
                {
                    throw new Exception($"the web site:{siteName} is already exist");
                }
            }
        }
        public static long SetupWebsite(bool enable32BitAppOnWin64, string webRootPath, bool forceNetFramework4, bool isClassic,
                                        IEnumerable <BindingInfo> bindings, string name)
        {
            long siteId;

            using (WebServerManager.WebServerContext context = WebServerManager.CreateContext())
            {
                ApplicationPool appPool = context.ApplicationPools.Add(ChooseAppPoolName(name, context.ApplicationPools));
                appPool.ManagedRuntimeVersion = NetFrameworkV2;
                var id = Settings.CoreInstallWebServerIdentity.Value;
                ProcessModelIdentityType type = GetIdentityType(id);
                appPool.ProcessModel.IdentityType   = type;
                appPool.ProcessModel.PingingEnabled = false;
                if (forceNetFramework4)
                {
                    appPool.SetAttributeValue("managedRuntimeVersion", "v4.0");
                }

                appPool.Enable32BitAppOnWin64 = enable32BitAppOnWin64;
                appPool.ManagedPipelineMode   = isClassic ? ManagedPipelineMode.Classic : ManagedPipelineMode.Integrated;

                if (type == ProcessModelIdentityType.SpecificUser)
                {
                    var password = Settings.CoreInstallWebServerIdentityPassword.Value;
                    appPool.ProcessModel.UserName = id;
                    appPool.ProcessModel.Password = password;
                }

                Product product = Product.Parse(ProductHelper.DetectProductFullName(webRootPath));

                if (product.Name.EqualsIgnoreCase("Sitecore CMS"))
                {
                    var ver = product.TwoVersion;
                    if (ver.StartsWith("6.0") || ver.StartsWith("6.1"))
                    {
                        appPool.Enable32BitAppOnWin64 = true;
                        appPool.ManagedPipelineMode   = ManagedPipelineMode.Classic;
                    }
                    else if (ver.StartsWith("6.2"))
                    {
                        appPool.Enable32BitAppOnWin64 = true;
                    }
                }

                Site site = null;
                foreach (BindingInfo binding in bindings)
                {
                    var bindingInformation = $"{binding.IP}:{binding.Port}:{binding.Host}";
                    if (site == null)
                    {
                        site = context.Sites.Add(name, binding.Protocol, bindingInformation, webRootPath);
                    }
                    else
                    {
                        site.Bindings.Add(bindingInformation, binding.Protocol);
                    }
                }

                Assert.IsNotNull(site, nameof(site));
                siteId = site.Id;
                site.ApplicationDefaults.ApplicationPoolName = name;
                context.CommitChanges();
            }

            return(siteId);
        }
Beispiel #19
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="name"></param>
 /// <param name="runtimeVersion"></param>
 /// <param name="managedPipelineMode"></param>
 /// <param name="identityType"></param>
 /// <param name="privateMemoryLimit"></param>
 /// <returns></returns>
 public AppPoolConfig AddAppPool(string name, string runtimeVersion, ManagedPipelineMode managedPipelineMode, ProcessModelIdentityType identityType, int privateMemoryLimit)
 {
     _privateMemoryLimit = privateMemoryLimit;
     return AddAppPool(name, runtimeVersion, managedPipelineMode, identityType);
 }
Beispiel #20
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="runtimeVersion"></param>
        /// <param name="managedPipelineMode"></param>
        /// <param name="identityType"></param>
        /// <returns></returns>
        public AppPoolConfig AddAppPool(string name, string runtimeVersion, ManagedPipelineMode managedPipelineMode, ProcessModelIdentityType identityType)
        {
            DeleteAppPool(name);
            _currentAppPoolNames.Add(name);

            ApplicationPool applicationPool = _mgr.ApplicationPools.Add(name);
            applicationPool.ManagedRuntimeVersion = runtimeVersion;
            applicationPool.ManagedPipelineMode = managedPipelineMode;
            applicationPool.ProcessModel.IdentityType = identityType;
            applicationPool.Recycling.PeriodicRestart.PrivateMemory = _privateMemoryLimit;
            _logger.Log("Added application pool " + name);

            return this;
        }
Beispiel #21
0
 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())
         {
             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 new Exception(ex.Message, ex);
     }
     return true;
 }