Inheritance: ConfigurationElement
        internal override async Task<bool> GetSiteStateAsync(Site site)
        {
#if !__MonoCS__
                using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
                    PowerShellInstance.AddScript("param($param1) [Reflection.Assembly]::LoadFrom('C:\\Windows\\system32\\inetsrv\\Microsoft.Web.Administration.dll'); Get-IISsite -Name \"$param1\"");

                    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
                    PowerShellInstance.AddParameter("param1", site.Name);

                    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                    // check the other output streams (for example, the error stream)
                    if (PowerShellInstance.Streams.Error.Count > 0)
                    {
                        // error records were written to the error stream.
                        // do something with the items found.
                        return false;
                    }

                    dynamic site1 = PSOutput[1];
                    return site1.State?.ToString() == "Started";
                }
#else
                return false;
#endif
        }
Esempio n. 2
0
        public bool TryCreateDeveloperSite(string applicationName, out string siteUrl)
        {
            var iis = new IIS.ServerManager();

            string devSiteName = GetDevSite(applicationName);

            IIS.Site site = iis.Sites[devSiteName];
            if (site == null)
            {
                // Get the path to the dev site
                string siteRoot = _pathResolver.GetDeveloperApplicationPath(applicationName);
                string webRoot  = Path.Combine(siteRoot, Constants.WebRoot);
                int    sitePort = CreateSite(iis, applicationName, devSiteName, webRoot);

                // Ensure the directory is created
                FileSystemHelpers.EnsureDirectory(webRoot);

                // Map a path called app to the site root under the service site
                MapServiceSitePath(iis, applicationName, Constants.MappedDevSite, siteRoot);

                iis.CommitChanges();


                siteUrl = String.Format("http://localhost:{0}/", sitePort);
                return(true);
            }

            siteUrl = String.Format("http://localhost:{0}/", site.Bindings[0].EndPoint.Port);
            return(false);
        }
Esempio n. 3
0
        private bool SiteUpToDate(Site site)
        {
            if (site != null) {
                if (site.Applications[0].VirtualDirectories[0].PhysicalPath != Directory.Value) {
                    return false;
                }

                if (site.ApplicationDefaults.ApplicationPoolName != ApplicationPoolNameIfSet) {
                    return false;
                }

                if (Bindings == null) {
                    var expectedBindingInformation = String.Format("*:{0}:", Port.Value);
                    if (site.Bindings.Any(b => b.BindingInformation != expectedBindingInformation)) {
                        return false;
                    }
                }
                else {
                    if (site.Bindings.Any(b => Bindings.Value.Any(e => e.Information.Value != b.BindingInformation || e.Protocol.Value != b.Protocol))) {
                        return false;
                    }
                }

                return true;
            }

            return false;
        }
 public override void ConfigureInstalledSite(Site site, InstallationConfiguration configuration)
 {
     foreach (var directory in configuration.AdditionalDirectories)
     {
         _directory.CreateDirectory(directory);
     }
 }
 internal override async Task<bool> GetSiteStateAsync(Site site)
 {
     var items = Process.GetProcessesByName("iisexpress");
     var found = items.Where(item =>
         item.GetCommandLine().EndsWith(site.CommandLine, StringComparison.Ordinal));
     return found.Any();
 }
Esempio n. 6
0
		public SiteDesiredState(Site iisSiteObject
								, IEnumerable<WebConfigPropertyDesiredState> authDesiredStateList
								, IISCodeGenerator.IisPoolAndSitesOptions iisOptions)
		{
			var rootApp = iisSiteObject.Applications[0];

			this.Key = GetSiteKey(iisSiteObject.Name);

			this.AddAttribute("Name", iisSiteObject.Name);
			this.AddAttribute("Ensure", "Present");
			this.AddAttribute("State", iisSiteObject.State.ToString());

			this.ApplicationPool = rootApp.ApplicationPoolName;
			this.AddAttribute("ApplicationPool", this.ApplicationPool);

			this.AddAttributeWithComment("PhysicalPath", rootApp.VirtualDirectories[0].PhysicalPath, "This folder must already exist");

			if (iisOptions.StandardizeLogFileLocation)
			{
				this.AddAttributeWithOverrideValue("LogFileDirectory", @"D:\IISLogs", iisSiteObject.LogFile.Directory); 
			}
			else
			{
				this.AddAttribute("LogFileDirectory", iisSiteObject.LogFile.Directory);
			}
			
			this.AddAttribute("DependsOn", "[cAppPool]" + PoolDesiredState.GetPoolVariableName(this.ApplicationPool));

			this.Bindings = GetBindings(iisSiteObject.Bindings);
			this.Applications = GetApplications(iisSiteObject.Applications, this.Key, this.Name);
			this.AuthDesiredStateList.AddRange(authDesiredStateList);
		}
Esempio n. 7
0
        internal static string GetVirtualPath(Site site, string protocol, string hostName)
        {
            Binding binding;
            var bindings = site.Bindings.Where(b => b.Protocol == protocol);
            var enumerable = bindings as IList<Binding> ?? bindings.ToList();
            if (enumerable.Any())
            {
                binding = enumerable.Single();
            }
            else
            {
                throw new Exception(string.Format("Binding for protocol '{0}' is not defined for the website '{1}'.", protocol, site.Name));
            }

            var host = "localhost";
            if (!string.IsNullOrEmpty(hostName))
            {
                host = hostName;
            } else if (!string.IsNullOrEmpty(binding.Host))
            {
                host = binding.Host;
            }

            return binding.EndPoint.Port == 80 
                ? string.Format("{0}://{1}", protocol, host) 
                : string.Format("{0}://{1}:{2}", protocol, host, binding.EndPoint.Port);
        }
Esempio n. 8
0
        private static IisSite ParseSite(Microsoft.Web.Administration.Site site, bool excludeAppPools = false, List <Microsoft.Web.Administration.ApplicationPool> applicationPools = null)
        {
            if (site == null)
            {
                return(null);
            }

            var servantSite = new IisSite
            {
                IisId            = (int)site.Id,
                Name             = site.Name,
                ApplicationPool  = site.Applications[0].ApplicationPoolName,
                SitePath         = site.Applications[0].VirtualDirectories[0].PhysicalPath,
                SiteState        = site.State,
                LogFileDirectory = site.LogFile.Directory,
                Bindings         = GetBindings(site).ToList(),
                Applications     = new List <UnionSoftSiteApplication>()
            };

            if (!excludeAppPools)
            {
                if (applicationPools == null)
                {
                    using (var manager = new ServerManager())
                    {
                        applicationPools = manager.ApplicationPools.ToList();
                    }
                }

                ObjectState applicationPoolState = applicationPools.Single(x => x.Name == site.Applications[0].ApplicationPoolName).State;
                //servantSite.ApplicationPoolState = (InstanceState)Enum.Parse(typeof(InstanceState), applicationPoolState.ToString());
            }

            foreach (var directory in site.Applications[0].VirtualDirectories.Skip(1))
            {
                servantSite.Applications.Add(new UnionSoftSiteApplication
                {
                    ApplicationPool = "",
                    Path            = directory.Path,
                    DiskPath        = directory.PhysicalPath,
                    IsApplication   = false
                });
            }

            if (site.Applications.Count > 1)
            {
                foreach (var application in site.Applications.Skip(1))
                {
                    servantSite.Applications.Add(new UnionSoftSiteApplication
                    {
                        ApplicationPool = application.ApplicationPoolName,
                        Path            = application.Path,
                        DiskPath        = application.VirtualDirectories[0].PhysicalPath,
                        IsApplication   = true
                    });
                }
            }

            return(servantSite);
        }
        private void ConfigureBindings(Site site, byte[] certificateHash, string certificateStoreName, string binding, string domain)
        {
            Binding[] httpsBindings;
            if (binding != null)
            {
                httpsBindings = site.Bindings.Where(b => b.BindingInformation == binding).ToArray();
            }
            else
            {
                httpsBindings = site.Bindings
                    .Where(
                        b =>
                            string.Equals(domain, b.Host, StringComparison.OrdinalIgnoreCase) &&
                            "https".Equals(b.Protocol, StringComparison.OrdinalIgnoreCase))
                    .ToArray();
            }

            if (!httpsBindings.Any())
            {
                AddNewHttpsBinding(certificateHash, certificateStoreName, site, domain);
            }
            else
            {
                UpdateExistingBindings(certificateHash, certificateStoreName, site, httpsBindings);
            }
        }
Esempio n. 10
0
 private Application createApp(Website website, Site site)
 {
     LogWriter.Current.Highlight("Trying to create a new virtual directory at " +
                         website.VDirPhysicalPath.ToFullPath());
     var app = site.CreateApplication(website.VDir, website.VDirPhysicalPath.ToFullPath(), website.ForceApp);
     app.ApplicationPoolName = website.AppPool;
     return app;
 }
        protected override void When(ServerManagerWrapper manager)
        {
            var createSite = new CreateSite(manager);
            _site = createSite.Install(InstallationConfiguration);

            var bindings = new ConfigureBindings(manager);
            bindings.ConfigureInstalledSite(_site, InstallationConfiguration);
        }
        protected override void When(ServerManagerWrapper manager)
        {
            var createSite = new CreateSite(manager);
            _site = createSite.Install(InstallationConfiguration);

            var logging = new ConfigureLogging(manager, _directoryMock.Object);
            logging.ConfigureInstalledSite(_site, InstallationConfiguration);
        }
Esempio n. 13
0
 private IList <KuduBinding> GetSiteUrls(IIS.Site site)
 {
     if (site == null)
     {
         return(null);
     }
     return(site.Bindings.Select(MapBinding).ToList());
 }
Esempio n. 14
0
        private Application createApp(Website website, Site site)
        {
            LogWriter.Current.Highlight("Trying to create a new virtual directory '{0}' at '{1}'".ToFormat(website.VDir, website.VDirPhysicalPath.ToFullPath()));

            new FileSystem().CreateDirectory(website.VDirPhysicalPath.ToFullPath());
            var app = site.CreateApplication(website.VDir, website.VDirPhysicalPath.ToFullPath(), website.ForceApp);
            app.ApplicationPoolName = website.AppPool;
            return app;
        }
        public WebsiteConfigurer(Site website)
        {
            if (website == null)
            {
                throw new ArgumentNullException("website");
            }

            _website = website;
        }
Esempio n. 16
0
        bool CheckState(Microsoft.Web.Administration.Site site, ObjectState state, int waitSecond)
        {
            int waitNum = waitSecond * 10;

            while (site.State != state && waitNum > 0)
            {
                waitNum--;
                Thread.Sleep(100);
            }
            return(site.State == state);
        }
 private static bool TryFindIis7Website(string websiteName, out Site site)
 {
     try
     {
         site = FindIis7Website(websiteName);
         return true;
     } catch
     {
         site = null;
         return false;
     }
 }
        internal override async Task StartAsync(Site site)
        {
            var name = site.Applications[0].ApplicationPoolName;
            var pool = ApplicationPools.FirstOrDefault(item => item.Name == name);
            var fileName =
                Path.Combine(
                    Environment.GetFolderPath(
                        pool != null && pool.Enable32BitAppOnWin64
                            ? Environment.SpecialFolder.ProgramFilesX86
                            : Environment.SpecialFolder.ProgramFiles),
                    "IIS Express",
                    "iisexpress.exe");
            if (!File.Exists(fileName))
            {
                fileName = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                    "IIS Express",
                    "iisexpress.exe");
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = site.CommandLine,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true
                }
            };
            try
            {
                process.Start();
                process.WaitForExit(5000);
                if (process.HasExited)
                {
                    throw new InvalidOperationException("process terminated");
                }

                site.State = ObjectState.Started;
            }
            catch (Exception ex)
            {
                throw new COMException(
                    string.Format("cannot start site: {0}, {1}", ex.Message, process.StandardOutput.ReadToEnd()));
            }
            finally
            {
                site.State = process.HasExited ? ObjectState.Stopped : ObjectState.Started;
            }
        }
Esempio n. 19
0
        public bool DoesVirtualDirectoryExist(Site site)
        {
            foreach (var app in site.Applications)
            {
                if (app.Path.Equals("/" + VdirPath))
                {
                    return true;
                }
            }

            return false;
        }
Esempio n. 20
0
        private string GetSiteUrl(IIS.Site site)
        {
            var urls = GetSiteUrls(site);

            if (urls == null)
            {
                return(null);
            }
            else
            {
                return(urls.FirstOrDefault());
            }
        }
Esempio n. 21
0
 protected void CreateSite()
 {
     using (var iis = ServerManager.OpenRemote(WebServerName))
     {
         Site = iis.Sites[SiteName];
         if (Site == null)
         {
             Site = iis.Sites.Add(SiteName, @"C:\Temp", 16000);
             iis.CommitChanges();
             WaitForIis();
         }
     }
 }
Esempio n. 22
0
        private static List <string> GetSiteUrls(IIS.Site site)
        {
            if (site == null)
            {
                return(null);
            }

            return(site.Bindings.Select(binding => new UriBuilder
            {
                Host = string.IsNullOrEmpty(binding.Host) ? "localhost" : binding.Host,
                Scheme = binding.Protocol,
                Port = binding.EndPoint.Port == 80 ? -1 : binding.EndPoint.Port
            }).Select(builder => builder.ToString()).ToList());
        }
Esempio n. 23
0
        private static void MapServiceSitePath(ServerManager iis, string applicationName, string path, string siteRoot)
        {
            string serviceSiteName = GetServiceSite(applicationName);

            // Get the service site
            IIS.Site site = iis.Sites[serviceSiteName];
            if (site == null)
            {
                throw new InvalidOperationException("Could not retrieve service site");
            }

            // Map the path to the live site in the service site
            site.Applications.Add(path, siteRoot);
        }
        public static void AddAppPool(Site siteobj, string Path)
        {
            ServerManager serverManager = new ServerManager();
            Site          site          = serverManager.Sites[siteobj.Name];

            site.Name = siteobj.Name;
            site.Applications[0].VirtualDirectories[0].PhysicalPath = Path;
            serverManager.ApplicationPools.Add(siteobj.Name.Replace(" ", "") + "- ApplicationPool");
            serverManager.Sites[siteobj.Name].Applications[0].ApplicationPoolName = siteobj.Name.Replace(" ", "") + "- ApplicationPool";
            ApplicationPool apppool = serverManager.ApplicationPools[siteobj.Name.Replace(" ", "") + "- ApplicationPool"];

            apppool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
            serverManager.CommitChanges();
        }
Esempio n. 25
0
        /// <summary>
        /// Physicals the path.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <returns>The physical path of the site.</returns>
        /// <exception cref="System.ArgumentNullException">site was null</exception>
        public static string PhysicalPath(this Microsoft.Web.Administration.Site site)
        {
            if (site == null)
            {
                throw new ArgumentNullException("site");
            }

            var root        = site.Applications.Where(a => a.Path == "/").Single();
            var virtualRoot = root.VirtualDirectories.Where(v => v.Path == "/")
                              .Single();

            // Can get environment variables, so need to expand them
            return(Environment.ExpandEnvironmentVariables(virtualRoot.PhysicalPath));
        }
        public static string CreateSite(string siteName, string protocol, string binding, string path)
        {
            if (CheckIfSiteExists(siteName))
            {
                return("Site Exsits");
            }
            ConfirmDir(path);
            var  iisManager = new ServerManager();
            Site site       = iisManager.Sites.Add(siteName, protocol, binding, path);

            iisManager.CommitChanges();
            AddAppPool(site, path);
            return("Created Site");
        }
        public WebsiteConfigurer(ILogger logger, Site website)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (website == null)
            {
                throw new ArgumentNullException("website");
            }

            Logger = logger;
            _website = website;
        }
Esempio n. 28
0
        public bool AddSiteBinding(string applicationName, KuduBinding binding)
        {
            try
            {
                using (ServerManager iis = GetServerManager())
                {
                    if (!IsAvailable(binding.Host, binding.Port, iis))
                    {
                        return(false);
                    }

                    IIS.Site site = binding.SiteType == SiteType.Live
                        ? iis.Sites[GetLiveSite(applicationName)]
                        : iis.Sites[GetServiceSite(applicationName)];

                    if (site == null)
                    {
                        return(true);
                    }

                    string bindingInformation = string.Format("{0}:{1}:{2}", binding.Ip, binding.Port, binding.Host);
                    switch (binding.Schema)
                    {
                    case UriScheme.Http:
                        site.Bindings.Add(bindingInformation, "http");
                        break;

                    case UriScheme.Https:
                        Certificate cert = _certificateSearcher.Lookup(binding.Certificate).ByThumbprint();
                        Binding     bind = site.Bindings.Add(bindingInformation, cert.GetCertHash(), cert.StoreName);
                        if (binding.Sni)
                        {
                            bind.SetAttributeValue("sslFlags", SslFlags.Sni);
                        }

                        break;
                    }
                    iis.CommitChanges();
                    Thread.Sleep(1000);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(false);
            }
        }
        internal static IDictionary<string, List<string>> GetProtocolBindingTable(Site site)
        {
            IDictionary<string, List<string>> bindingList = new Dictionary<string, List<string>>();
            foreach (Binding binding in site.Bindings)
            {
                string protocol = binding.Protocol.ToLowerInvariant();
                string bindingInformation = binding.BindingInformation;

                if (!bindingList.ContainsKey(protocol))
                {
                    bindingList.Add(protocol, new List<string>());
                }
                bindingList[protocol].Add(bindingInformation);
            }
            return bindingList;
        }
        private IList<Application> GetAllApplications(string appPoolName, Site site)
        {
            IList<Application> applications = new List<Application>();
            if (string.IsNullOrWhiteSpace(appPoolName)) return applications;
            if (site == null) return applications;

            foreach (Application application in site.Applications)
            {
                if (application.ApplicationPoolName.Equals(appPoolName))
                {
                    applications.Add(application);
                }
            }

            return applications;
        }
Esempio n. 31
0
        Site BindSite(Microsoft.Web.Administration.Site iissite, ServerManager sm)
        {
            if (iissite == null)
            {
                return(null);
            }
            var defaultApp    = iissite.Applications[SITE_KEY];
            var defaultVirDir = defaultApp.VirtualDirectories[SITE_KEY];
            int state;

            try
            {
                state = (int)iissite.State;
            }
            catch
            {
                // 注意:ftp站点会抛异常,ftp状态要用 iissite.GetChildElement("ftpServer")["state"]
                state = -1;
            }
            var site = new Site()
            {
                Id                = iissite.Id,
                Name              = iissite.Name,
                State             = state,
                Dir               = defaultVirDir.PhysicalPath,
                Bindings          = GetBinding(iissite.Bindings, out var isHttp),
                PoolName          = defaultApp.ApplicationPoolName,
                ConnectionTimeOut = (int)iissite.Limits.ConnectionTimeout.TotalSeconds,
            };

            site.LogDir = iissite.LogFile.Enabled ? iissite.LogFile.Directory + "\\W3SVC" + site.Id.ToString() : "";
            site.IsHttp = isHttp;
            try
            {
                // 读取是否启用预加载
                site.Preload = (bool)defaultApp.GetAttributeValue("preloadEnabled");
            }
            catch
            {
                site.Preload = false;
            }
            var pool = sm.ApplicationPools[site.PoolName];

            site.GcTimeStr = GetSchedule(pool);

            return(site);
        }
Esempio n. 32
0
        private void ConfigureSite(ref Site site, string name, string httpBindingInfo, string httpsBindingInfo, Repository repository, string projectDir, ComboBox uiAppPool)
        {
            string physicalPath = Path.Combine(repository.LocalLocation, "core", projectDir);

            if (site == null)
            {
                site = _serverManager.Sites.Add(name, "http", httpBindingInfo, physicalPath);
            }
            else
            {
                site.Bindings.Add(httpBindingInfo, "http");
                site.Applications.First(a => a.Path == "/").VirtualDirectories.First(a => a.Path == "/").PhysicalPath = physicalPath;
            }

            site.Applications.First().ApplicationPoolName = ((AppPool)uiAppPool.SelectedItem).Name;
            site.Bindings.Add(httpsBindingInfo, ((Cert)_uiCerts.SelectedItem).Bytes, _x509Store.Name);
        }
        private static CounterDescriptor CreateDescriptor(Site iisSite)
        {
            var pc = new PerformanceCounter("Web Service", "Total Method Requests/sec", iisSite.Name, true);
            pc.NextValue();

            var pcd = new TrafficPerformanceCounterDescriptor
            {
                Name=iisSite.Name,
                SystemCounter=pc,
                Unit = "Count/Second",
                MetricName="Method Requests"
            };

            pcd.Dimensions.Add("SiteName",iisSite.Name);

            return pcd;
        }
Esempio n. 34
0
        private bool SiteUpToDate(Site site)
        {
            if (site != null) {
                if (site.Applications[0].VirtualDirectories[0].PhysicalPath != Directory.Value) {
                    return false;
                }

                var expectedBindingInformation = String.Format("*:{0}:", Port.Value);
                if (site.Bindings.All(b => b.BindingInformation != expectedBindingInformation)) {
                    return false;
                }

                return true;
            } else {
                return false;
            }
        }
        public override void ConfigureInstalledSite(Site site, InstallationConfiguration configuration)
        {
            if (!configuration.Bindings.Any())
            {
                return;
            }

            site.Bindings.Clear();

            foreach (var binding in configuration.Bindings)
            {
                var b = site.Bindings.CreateElement();
                b.Protocol = binding.Protocol;
                b.BindingInformation = string.Format("{0}:{1}:{2}", binding.IPAddress, binding.Port, binding.Host);
                site.Bindings.Add(b);
            }
        }
        public override void ConfigureInstalledSite(Site site, InstallationConfiguration configuration)
        {
            site.LogFile.Directory = NewOrOriginal(configuration.LogFileDirectory, site.LogFile.Directory);

            if (!configuration.LogFileCreateDirectoryWithElevatedPermissions)
            {
                return;
            }

            if (!_directory.Exists(site.LogFile.Directory))
            {
                _directory.CreateDirectory(site.LogFile.Directory);
            }
            else
            {
                _directory.ElevatePermissions(site.LogFile.Directory);
            }
        }
Esempio n. 37
0
        public void SetSiteWebRoot(string applicationName, string siteRoot)
        {
            var    iis      = new IIS.ServerManager();
            string siteName = GetDevSite(applicationName);

            IIS.Site site = iis.Sites[siteName];
            if (site != null)
            {
                string sitePath = _pathResolver.GetLiveSitePath(applicationName);
                string webRoot  = Path.Combine(sitePath, Constants.WebRoot, siteRoot);

                // Change the web root
                site.Applications[0].VirtualDirectories[0].PhysicalPath = webRoot;

                iis.CommitChanges();

                Thread.Sleep(1000);
            }
        }
Esempio n. 38
0
        //private static Microsoft.Web.Administration.ApplicationPool UpdateIisApplicationPoolFromServant(this Microsoft.Web.Administration.ApplicationPool iisApplicationPool, ApplicationPool servantApplicationPool)
        //{
        //    ManagedPipelineMode pipelineMode;
        //    Enum.TryParse(servantApplicationPool.PipelineMode, true, out pipelineMode);
        //    LoadBalancerCapabilities loadBalancerCapabilities;
        //    Enum.TryParse(servantApplicationPool.ServiceUnavailableResponseType, true, out loadBalancerCapabilities);

        //    iisApplicationPool.Name = servantApplicationPool.Name;
        //    iisApplicationPool.AutoStart = servantApplicationPool.AutoStart;
        //    iisApplicationPool.ManagedRuntimeVersion = servantApplicationPool.ClrVersion;
        //    iisApplicationPool.ManagedPipelineMode = pipelineMode;
        //    iisApplicationPool.Recycling.DisallowOverlappingRotation = servantApplicationPool.DisallowOverlappingRotation;
        //    iisApplicationPool.Recycling.DisallowRotationOnConfigChange = servantApplicationPool.DisallowRotationOnConfigChange;
        //    iisApplicationPool.Recycling.PeriodicRestart.Time = servantApplicationPool.RecycleInterval;
        //    iisApplicationPool.Recycling.PeriodicRestart.PrivateMemory = servantApplicationPool.RecyclePrivateMemoryLimit;
        //    iisApplicationPool.Recycling.PeriodicRestart.Memory = servantApplicationPool.RecycleVirtualMemoryLimit;
        //    iisApplicationPool.Recycling.PeriodicRestart.Requests = servantApplicationPool.RecycleRequestsLimit;
        //    iisApplicationPool.ProcessModel.IdleTimeout = servantApplicationPool.IdleTimeout;
        //    iisApplicationPool.ProcessModel.MaxProcesses = servantApplicationPool.MaximumWorkerProcesses;
        //    iisApplicationPool.ProcessModel.PingingEnabled = servantApplicationPool.PingingEnabled;
        //    iisApplicationPool.ProcessModel.PingResponseTime = servantApplicationPool.PingMaximumResponseTime;
        //    iisApplicationPool.Failure.LoadBalancerCapabilities = loadBalancerCapabilities;
        //    iisApplicationPool.Failure.RapidFailProtection = servantApplicationPool.RapidFailProtectionEnabled;
        //    iisApplicationPool.Failure.RapidFailProtectionInterval = servantApplicationPool.RapidFailProtectionInterval;
        //    iisApplicationPool.Failure.RapidFailProtectionMaxCrashes = servantApplicationPool.RapidFailProtectionMaxCrashes;
        //    // Husk at opdatere GetDefaultApplicationPool

        //    return iisApplicationPool;
        //}

        private static IEnumerable <UnionSoftBinding> GetBindings(Microsoft.Web.Administration.Site site)
        {
            var allowedProtocols = new[] { "http", "https" };
            var certificates     = GetCertificates();

            foreach (var binding in site.Bindings.Where(x => allowedProtocols.Contains(x.Protocol)))
            {
                var unionSoftBinding = new UnionSoftBinding();

                if (binding.Protocol == "https")
                {
                    if (binding.CertificateHash == null)
                    {
                        continue;
                    }

                    var certificate = certificates.SingleOrDefault(cert => cert.Hash.SequenceEqual(binding.CertificateHash));
                    if (certificate != null)
                    {
                        unionSoftBinding.CertificateName       = certificate.Name;
                        unionSoftBinding.CertificateThumbprint = certificate.Thumbprint;
                    }
                    else
                    {
                        continue;
                    }
                }
                unionSoftBinding.Protocol = binding.Protocol;
                unionSoftBinding.Hostname = binding.Host;
                unionSoftBinding.Port     = binding.EndPoint.Port;
                var endPointAddress = binding.EndPoint.Address.ToString();
                unionSoftBinding.IpAddress = endPointAddress == "*" || endPointAddress == "0.0.0.0" ?  IisIP : endPointAddress;
                if (!unionSoftBinding.Hostname.Equals(string.Empty))
                {
                    unionSoftBinding.ClickLink = unionSoftBinding.Protocol + "://" + unionSoftBinding.Hostname + ":" + unionSoftBinding.Port;
                }
                else
                {
                    unionSoftBinding.ClickLink = unionSoftBinding.Protocol + "://" + unionSoftBinding.IpAddress + ":" + unionSoftBinding.Port;
                }
                yield return(unionSoftBinding);
            }
        }
        public override void ConfigureInstalledSite(Site site, InstallationConfiguration configuration)
        {
            if (string.IsNullOrEmpty(configuration.AppPoolName))
            {
                return;
            }

            if (configuration.AppPoolDeleteExisting)
            {
                var existingAppPool = ServerManager.ApplicationPools.SingleOrDefault(x => x.Name.Equals(configuration.AppPoolName, StringComparison.InvariantCultureIgnoreCase));

                if(existingAppPool != null)
                {
                    ServerManager.ApplicationPools.Remove(existingAppPool);
                }
            }

            site.ApplicationDefaults.ApplicationPoolName = configuration.AppPoolName;

            ConfigureAppPoolIfNotExists(configuration);
        }
Esempio n. 40
0
        private string GetSiteUrl(IIS.Site site)
        {
            if (site == null)
            {
                return(null);
            }

            IIS.Binding binding = site.Bindings.Last();
            var         builder = new UriBuilder
            {
                Host   = String.IsNullOrEmpty(binding.Host) ? "localhost" : binding.Host,
                Scheme = binding.Protocol,
                Port   = binding.EndPoint.Port
            };

            if (builder.Port == 80)
            {
                builder.Port = -1;
            }

            return(builder.ToString());
        }
Esempio n. 41
0
        public bool RemoveSiteBinding(string applicationName, string siteBinding, SiteType siteType)
        {
            try
            {
                using (ServerManager iis = GetServerManager())
                {
                    IIS.Site site = siteType == SiteType.Live
                        ? iis.Sites[GetLiveSite(applicationName)]
                        : iis.Sites[GetServiceSite(applicationName)];

                    if (site == null)
                    {
                        return(true);
                    }

                    Uri     uri     = new Uri(siteBinding);
                    Binding binding = site.Bindings
                                      .FirstOrDefault(x => x.Host.Equals(uri.Host) &&
                                                      x.EndPoint.Port.Equals(uri.Port) &&
                                                      x.Protocol.Equals(uri.Scheme));

                    if (binding == null)
                    {
                        return(true);
                    }

                    site.Bindings.Remove(binding);
                    iis.CommitChanges();
                    Thread.Sleep(1000);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(false);
            }
        }
Esempio n. 42
0
        public bool RemoveSiteBinding(string applicationName, KuduBinding siteBinding, SiteType siteType)
        {
            try
            {
                using (ServerManager iis = GetServerManager())
                {
                    IIS.Site site = siteType == SiteType.Live
                        ? iis.Sites[GetLiveSite(applicationName)]
                        : iis.Sites[GetServiceSite(applicationName)];

                    if (site == null)
                    {
                        return(true);
                    }

                    Binding binding = site.Bindings
                                      .FirstOrDefault(x => x.Host.Equals(siteBinding.Host) &&
                                                      x.EndPoint.Port.Equals(siteBinding.Port) &&
                                                      x.EndPoint.Address.ToString() == siteBinding.Ip &&
                                                      x.Protocol.Equals(siteBinding.Scheme.ToString(), StringComparison.OrdinalIgnoreCase));

                    if (binding == null)
                    {
                        return(true);
                    }

                    site.Bindings.Remove(binding);
                    iis.CommitChanges();
                    Thread.Sleep(1000);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(false);
            }
        }
        public static void RemoveIISWebsite(string sitename, bool RemoveSite, int SiteId = 0)
        {
            ServerManager iisManager = new ServerManager();
            Site          site       = null;

            if (SiteId > 0)
            {
                site = iisManager.Sites[SiteId];
            }
            else
            {
                site = iisManager.Sites[sitename];
            }
            bool isActive = false;

            isActive = iisManager.Sites[sitename] == null ? false : true;
            if (isActive)
            {
                iisManager.Sites.Remove(site);
                iisManager.CommitChanges();
                DeleteApplicationPool((sitename.Replace(" ", "") + "- ApplicationPool").ToString(), RemoveSite);
            }
        }
Esempio n. 44
0
        private static List <Uri> GetSiteUrls(IIS.Site site)
        {
            var urls = new List <Uri>();

            if (site == null)
            {
                return(null);
            }

            foreach (IIS.Binding binding in site.Bindings)
            {
                var builder = new UriBuilder
                {
                    Host   = String.IsNullOrEmpty(binding.Host) ? "localhost" : binding.Host,
                    Scheme = binding.Protocol,
                    Port   = binding.EndPoint.Port == 80 ? -1 : binding.EndPoint.Port
                };

                urls.Add(builder.Uri);
            }

            return(urls);
        }
        public static string RemoveBinding(string hostname, string sitename)
        {
            ServerManager serverManager = new ServerManager();
            Site          site          = serverManager.Sites[sitename];

            if (site.Bindings.Count > 1)
            {
                for (int i = 0; i < site.Bindings.Count; i++)
                {
                    if (site.Bindings[i].Host.ToLower() == hostname.Trim())
                    {
                        site.Bindings.RemoveAt(i);
                        serverManager.CommitChanges();
                        break;
                    }
                }
            }
            else
            {
                return("Cannot Delete Binding as it is the last one");
            }
            return($"Deleted Binding : {hostname}");
        }
Esempio n. 46
0
        public Site GetSite(string applicationName)
        {
            using (var iis = GetServerManager())
            {
                var mainSiteName    = GetLiveSite(applicationName);
                var serviceSiteName = GetServiceSite(applicationName);

                IIS.Site mainSite = iis.Sites[mainSiteName];

                if (mainSite == null)
                {
                    return(null);
                }

                IIS.Site serviceSite = iis.Sites[serviceSiteName];
                // IIS.Site devSite = iis.Sites[devSiteName];

                var site = new Site();
                site.ServiceUrls = GetSiteUrls(serviceSite);
                site.SiteUrls    = GetSiteUrls(mainSite);
                return(site);
            }
        }
Esempio n. 47
0
        private static IEnumerable <Binding> GetBindings(Microsoft.Web.Administration.Site site)
        {
            var allowedProtocols = new[] { "http", "https" };
            var certificates     = GetCertificates();

            foreach (var binding in site.Bindings.Where(x => allowedProtocols.Contains(x.Protocol)))
            {
                var servantBinding = new Binding();

                if (binding.Protocol == "https")
                {
                    if (binding.CertificateHash == null)
                    {
                        continue;
                    }

                    var certificate = certificates.SingleOrDefault(cert => cert.Hash.SequenceEqual(binding.CertificateHash));
                    if (certificate != null)
                    {
                        servantBinding.CertificateName       = certificate.Name;
                        servantBinding.CertificateThumbprint = certificate.Thumbprint;
                    }
                    else
                    {
                        continue;
                    }
                }
                servantBinding.Protocol = (Protocol)Enum.Parse(typeof(Protocol), binding.Protocol);
                servantBinding.Hostname = binding.Host;
                servantBinding.Port     = binding.EndPoint.Port;
                var endPointAddress = binding.EndPoint.Address.ToString();
                servantBinding.IpAddress = endPointAddress == "0.0.0.0" ? "*" : endPointAddress;

                yield return(servantBinding);
            }
        }
Esempio n. 48
0
        public static void StartAndWait(this IIS.Site site)
        {
            var wait = new PollingWait(() => site.Start(), () => site.State == IIS.ObjectState.Started);

            wait.Invoke();
        }
Esempio n. 49
0
 private static IISSiteStatus GetStatus(Site site)
 {
     try
     {
         return GetStatus(site.State);
     }
     catch (Exception)
     {
         return IISSiteStatus.Unkown;
     }
 }
Esempio n. 50
0
 internal override void Start(Site site)
 {
     StartInner(site, false);
 }
Esempio n. 51
0
 internal override void Restart(Site site)
 {
     StartInner(site, true);
 }
Esempio n. 52
0
        private void StartInner(Site site, bool restart)
        {
            var name     = site.Applications[0].ApplicationPoolName;
            var pool     = ApplicationPools.FirstOrDefault(item => item.Name == name);
            var fileName =
                Path.Combine(
                    Environment.GetFolderPath(
                        pool != null && pool.Enable32BitAppOnWin64
                            ? Environment.SpecialFolder.ProgramFilesX86
                            : Environment.SpecialFolder.ProgramFiles),
                    "IIS Express",
                    "iisexpress.exe");

            if (!File.Exists(fileName))
            {
                fileName = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                    "IIS Express",
                    "iisexpress.exe");
            }

            var temp = Path.GetTempFileName();

            using (var process = new Process())
            {
                var start = process.StartInfo;
                start.Verb = site.Bindings.ElevationRequired && !PublicNativeMethods.IsProcessElevated
                    ? "runas"
                    : null;
                start.FileName = "cmd";
                var extra = restart ? "/r" : string.Empty;
                start.Arguments =
                    $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /launcher:\"{fileName}\" /config:\"{site.FileContext.FileName}\" /siteId:{site.Id} /resultFile:\"{temp}\"\" {extra}";
                start.CreateNoWindow = true;
                start.WindowStyle    = ProcessWindowStyle.Hidden;
                InjectEnvironmentVariables(site, start);

                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode == 0)
                    {
                        site.State = ObjectState.Started;
                    }
                    else if (process.ExitCode == 1)
                    {
                        throw new InvalidOperationException("The process has terminated");
                    }
                }
                catch (Exception ex)
                {
                    throw new COMException(
                              $"cannot start site: {ex.Message}, {File.ReadAllText(temp)}");
                }
                finally
                {
                    site.State = process.ExitCode == 0 ? ObjectState.Started : ObjectState.Stopped;
                }
            }
        }
Esempio n. 53
0
 public static async Task WaitForState(this IIS.Site site, IIS.ObjectState state)
 {
     await WaitForState(() => site.State, state);
 }
Esempio n. 54
0
        void BuildVirtualDirectory(Site site, ServerManager mgr, DeploymentResult result)
        {
            Magnum.Guard.AgainstNull(site, "The site argument is null and should not be");
            var appPath = "/" + VirtualDirectoryPath;

            //this didn't find the application if there is a difference in letter casing like '/MyApplication' and '/Myapplication'. But threw an exception when tried to add it.
               //var application = site.Applications.FirstOrDefault(x => x.Path == appPath);
            var application = site.Applications.FirstOrDefault(x => x.Path.Equals(appPath, StringComparison.OrdinalIgnoreCase));

            if (application == null)
            {
                result.AddAlert("'{0}' doesn't exist. creating.", VirtualDirectoryPath);
                application = site.Applications.Add(appPath, PathOnServer);
                LogFineGrain("[iis7] Created application '{0}'", VirtualDirectoryPath);
            }
            else
            {
                result.AddNote("'{0}' already exists. Updating settings.", VirtualDirectoryPath);
            }

            if (application.ApplicationPoolName != AppPoolName)
            {
                application.ApplicationPoolName = AppPoolName;
                LogFineGrain("[iis7] Set the ApplicationPool for '{0}' to '{1}'", VirtualDirectoryPath, AppPoolName);
            }

            var vdir = application.VirtualDirectories["/"];
            if (vdir.PhysicalPath != PathOnServer)
            {
                vdir.PhysicalPath = PathOnServer;
                LogFineGrain("[iis7] Updated physical path for '{0}' to '{1}'", VirtualDirectoryPath, PathOnServer);
            }

             ConfigureAuthentication(mgr, result, true);
            //result.AddGood("'{0}' was created/updated successfully", VirtualDirectoryPath);
        }
 private bool SiteExists()
 {
     this.website = this.iisServerManager.Sites[this.Website];
     return this.website != null;
 }
Esempio n. 56
0
 public static async Task StopAndWait(this IIS.Site site)
 {
     site.Stop();
     await WaitForState(() => site.State, IIS.ObjectState.Stopped);
 }
Esempio n. 57
0
        public static string GetSitename(Site site)
        {
            if(site == null)
                return "Unknown";

            return site.Name;
        }
Esempio n. 58
0
 public static void WaitForState(this IIS.Site site, IIS.ObjectState state)
 {
     new PollingWait(() => { }, () => site.State == state).Invoke();
 }
Esempio n. 59
0
        static void AddApplication(Site site, NippsModule nippsModule)
        {
            string physicalPath = NippsConfig.Environment.IISwwwroot;

            if (ServiceOnlyInstall)
                if (!Match(nippsModule.ApplicationName) && !nippsModule.ApplicationName.StartsWith("Netas.Nipps.DeployManager.Service"))
                    return;

            if (physicalPath.EndsWith("\\"))
                physicalPath += nippsModule.ApplicationName;
            else
                physicalPath += "\\" + nippsModule.ApplicationName;

            nippsModule.ApplicationName = "/" + nippsModule.ApplicationName;

            Console.WriteLine("adding " + nippsModule.ApplicationName + " from path " + physicalPath);
            Application application = site.Applications.Add(nippsModule.ApplicationName, physicalPath);
            application.ApplicationPoolName = string.IsNullOrEmpty(NippsConfig.Environment.IISApplicationPoolName) ? nippsModule.ApplicationPoolName : NippsConfig.Environment.IISApplicationPoolName;
        }
 public abstract void ConfigureInstalledSite(Site site, InstallationConfiguration configuration);