Inheritance: ConfigurationElement
示例#1
0
        public BindingDialog(IServiceProvider serviceProvider, Binding binding, Site site)
            : base(serviceProvider)
        {
            InitializeComponent();
            Binding = binding;
            _site   = site;
            Text    = Binding == null ? "Create Site Binding" : "Edit Site Binding";
            DialogHelper.LoadAddresses(cbAddress);
            txtPort.Text         = "80";
            cbType.SelectedIndex = 0;
            if (!site.Server.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            if (Binding == null)
            {
                txtHost.Text = site.Server.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
                return;
            }

            cbType.Text    = Binding.Protocol;
            cbType.Enabled = Binding == null;
            cbAddress.Text = Binding.EndPoint.Address.AddressToCombo();
            txtPort.Text   = Binding.EndPoint.Port.ToString();
            txtHost.Text   = Binding.Host.HostToDisplay();
            if (site.Server.SupportsSni)
            {
                cbSniRequired.Checked = Binding.GetIsSni();
            }
        }
示例#2
0
        private void CreateBinding()
        {
            using (ServerManager manager = new ServerManager())
            {
                Site site = manager.Sites[this.SiteName];

                if (site == null)
                {
                    throw new Exception("Could not add binding information because the site was not found.");
                }

                string bindingInfo = string.Format(CultureInfo.InvariantCulture, "*:{0}:{1}", this.PortNumber,
                                                   this.HostName);

                if (
                    site.Bindings.Any(
                        binding =>
                        binding.Protocol.Equals(BindingProtocol) && binding.BindingInformation.Equals(bindingInfo)))
                {
                    return;
                }

                Binding newBinding = site.Bindings.CreateElement();
                newBinding.Protocol           = BindingProtocol;
                newBinding.BindingInformation = bindingInfo;
                site.Bindings.Add(newBinding);
                manager.CommitChanges();
            }
        }
示例#3
0
        private void button1_Click(object sender, EventArgs e)
        {
            String path = String.Format(@"C:\Debug\TestSite003", siteName);
            //Get caught up with the IIS7-8.5 ServerManager so that we can start integrating that bad boy in
            ServerManager serverMgr = new ServerManager();

            if (serverMgr.Sites[siteName] != null)
            {
                OutputError(String.Format("Site {0} already exists.", siteName));
                return;
            }

            Directory.CreateDirectory(path);
            Site mySite = serverMgr.Sites.Add(siteName, path, 80);

            //Site mySite = serverMgr.Sites.Add(siteName, "http", "http:*:80:dadada.burgstaler.com", path);
            mySite.Bindings.Clear();
            Microsoft.Web.Administration.Binding binding = mySite.Bindings.CreateElement("binding");
            binding.Protocol           = "http";
            binding.BindingInformation = String.Format("*:80:{0}.burgstaler.com", siteName);
            mySite.Bindings.Add(binding);
            //mySite.Bindings.Add("http:*:80:ddd.burgstaler.com", "http");
            ApplicationPool appPool = serverMgr.ApplicationPools[siteName];

            appPool = appPool ?? serverMgr.ApplicationPools.Add(siteName);
            appPool.ManagedRuntimeVersion = "v4.0"; //v1.0, v2.0
            mySite.ApplicationDefaults.ApplicationPoolName = siteName;
            //mySite.TraceFailedRequestsLogging.Enabled = true;
            //mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
            serverMgr.CommitChanges();

            //Start will report an error "The object identifier does not represent a valid object. (Exception from
            //HRESULT: 0x800710D8)" if we don't give some time as mentioned by Sergei - http://forums.iis.net/t/1150233.aspx
            //There is a timing issue. WAS needs more time to pick new site or pool and start it, therefore (depending on your system) you could
            //see this error, it is produced by output routine. Both site and pool are succesfully created, but State field of their PS
            //representation needs runtime object that wasn't created by WAS yet.
            //He said that would be fixed soon, but apparently that did not take place yet so we will work around it.
            DateTime giveUpAfter = DateTime.Now.AddSeconds(3);

            while (true)
            {
                try
                {
                    mySite.Start();
                    break;
                }
                catch (Exception exp)
                {
                    if (DateTime.Now > giveUpAfter)
                    {
                        //throw new Exception(String.Format("Inner error: {0} Outer error: {1}", (exp.InnerException != null) ? exp.InnerException.Message : "No inner exception", exp.Message));
                        OutputError(String.Format("Inner error: {0} Outer error: {1}", (exp.InnerException != null) ? exp.InnerException.Message : "No inner exception", exp.Message));
                        break;
                    }
                }
                System.Threading.Thread.Sleep(250);
            }
        }
        public BindingConfigurer(Binding binding)
        {
            if (binding == null)
            {
                throw new ArgumentNullException("binding");
            }

            _binding = binding;

            CertificateFinder = new CertificateFinder();
        }
示例#5
0
        private IIS.Binding EnsureBinding(IIS.BindingCollection siteBindings)
        {
            if (siteBindings == null)
            {
                throw new NoHostNameFoundException();
            }

            IIS.Binding iisBinding = siteBindings.FirstOrDefault();

            if (iisBinding == null)
            {
                throw new NoHostNameFoundException();
            }

            return(iisBinding);
        }
		private void Initialize(Binding binding)
		{
			AddAttribute("Protocol",  binding.Protocol);
			AddAttribute("Port", binding.EndPoint.Port.ToString());

			string address = binding.EndPoint.Address.ToString();

			if (address == "0.0.0.0")
				address = "*";

			AddAttribute("IPAddress", address);	
			
			if (CodeGenHelpers.AreEqualCI(binding.Protocol, "https"))
			{
				AddAttribute("CertificateStoreName", binding.CertificateStoreName);
				AddAttribute("CertificateThumbprint", "the thumbprint of the cert you want to use");
			}

		}
示例#7
0
        private bool IPEndPointIsValid(out IPAddress address, out int port, bool showDialog = true)
        {
            try
            {
                address = cbAddress.Text.ComboToAddress();
            }
            catch (Exception)
            {
                if (showDialog)
                {
                    MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                address = null;
                port    = 0;
                return(false);
            }

            return(Binding.PortIsValid(txtPort.Text, out port, Text, showDialog));
        }
示例#8
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());
        }
示例#9
0
 private static bool EqualHosts(Binding binding, Uri uri)
 {
     return binding.Host == uri.Host || (binding.Host == "" && uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase));
 }
        private async void BtnOkClick(object sender, EventArgs e)
        {
            foreach (var ch in SiteCollection.InvalidSiteNameCharacters())
            {
                if (txtName.Text.Contains(ch))
                {
                    MessageBox.Show("The site name cannot contain the following characters: '\\, /, ?, ;, :, @, &, =, +, $, ,, |, \", <, >'.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
            {
                if (txtName.Text.Contains(ch) || txtName.Text.StartsWith("~"))
                {
                    MessageBox.Show("The site name cannot contain the following characters: '~,  '.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            if (!await _collection.Parent.VerifyAsync(txtPath.Text))
            {
                MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            IPAddress address;

            try
            {
                address = cbAddress.Text.ComboToAddress();
            }
            catch (Exception)
            {
                MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int port;

            try
            {
                port = int.Parse(txtPort.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (port < 1 || port > 65535)
            {
                MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();

            foreach (var ch in invalid)
            {
                if (txtHost.Text.Contains(ch))
                {
                    MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            if (_collection.Parent.Mode == WorkingMode.IisExpress)
            {
                if (txtHost.Text != "localhost")
                {
                    MessageBox.Show(
                        "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                        Text,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
                }
            }

            long largestId = 0;

            foreach (Site site in _collection)
            {
                if (site.Id > largestId)
                {
                    largestId = site.Id;
                }
            }

            largestId++;

            NewSite = new Site(_collection)
            {
                Name = txtName.Text, Id = largestId
            };
            var host    = txtHost.Text.DisplayToHost();
            var info    = cbType.Text == "https" ? (CertificateInfo)cbCertificates.SelectedItem : null;
            var binding = new Binding(
                cbType.Text,
                string.Format("{0}:{1}:{2}", address.AddressToDisplay(), port, host.HostToDisplay()),
                info?.Certificate.GetCertHash() ?? new byte[0],
                info?.Store,
                cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                NewSite.Bindings);

            if (_collection.FindDuplicate(binding, null, null) != false)
            {
                var result = MessageBox.Show(string.Format("The binding '{0}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?", binding), Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result != DialogResult.Yes)
                {
                    return;
                }
            }

            if (_collection.Parent.Mode == WorkingMode.IisExpress)
            {
                var result = binding.FixCertificateMapping(info?.Certificate);
                if (!string.IsNullOrEmpty(result))
                {
                    MessageBox.Show(string.Format("The binding '{0}' is invalid: {1}", binding, result), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            var app = new Application(NewSite.Applications)
            {
                Path = Application.RootPath,
                Name = string.Empty,
                ApplicationPoolName = txtPool.Text
            };

            app.Load(VirtualDirectory.RootPath, txtPath.Text);
            NewSite.Applications.Add(app);
            NewSite.Bindings.Add(binding);
            DialogResult = DialogResult.OK;
        }
 public void AddAdded(Binding binding)
 {
     _added.Add(binding);
 }
示例#12
0
		public IPBindingDesiredState(Binding binding)
		{
			Initialize(binding);
		}
示例#13
0
        private void BtnOkClick(object sender, EventArgs e)
        {
            IPAddress address;

            try
            {
                address = cbAddress.Text.ComboToAddress();
            }
            catch (Exception)
            {
                MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int port;

            try
            {
                port = int.Parse(txtPort.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (port < 1 || port > 65535)
            {
                MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();

            foreach (var ch in invalid)
            {
                if (txtHost.Text.Contains(ch))
                {
                    MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            if (_site.Server.Mode == WorkingMode.IisExpress)
            {
                if (txtHost.Text != "localhost")
                {
                    MessageBox.Show(
                        "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                        Text,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
                }
            }

            var certificate = cbCertificates.SelectedItem as CertificateInfo;
            var host        = txtHost.Text.DisplayToHost();
            var binding     = new Binding(
                cbType.Text,
                $"{address.AddressToDisplay()}:{port}:{host.HostToDisplay()}",
                cbType.Text == "https" ? certificate?.Certificate.GetCertHash() : new byte[0],
                cbType.Text == "https" ? certificate?.Store : null,
                cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                _site.Bindings);
            var matched = _site.Parent.FindDuplicate(binding, _site, Binding);

            if (matched == true)
            {
                var result = ShowMessage(
                    $"The binding '{Binding}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button1);
                if (result != DialogResult.Yes)
                {
                    return;
                }
            }

            if (matched == null)
            {
                ShowMessage(
                    "The specific port is being used by a different binding.",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button1);
                return;
            }

            if (Binding == null)
            {
                Binding = binding;
            }
            else
            {
                Binding.Reinitialize(binding);
            }

            if (_site.Server.Mode == WorkingMode.IisExpress)
            {
                var result = Binding.FixCertificateMapping(certificate?.Certificate);
                if (!string.IsNullOrEmpty(result))
                {
                    MessageBox.Show($"The binding '{Binding}' is invalid: {result}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            DialogResult = DialogResult.OK;
        }
 public void AddRemoved(Binding binding)
 {
     _removed.Add(binding);
 }
        public BindingDialog(IServiceProvider serviceProvider, Binding binding1, Site site)
            : base(serviceProvider)
        {
            InitializeComponent();
            Binding = binding1;
            Text    = Binding == null ? "Create Site Binding" : "Edit Site Binding";
            DialogHelper.LoadAddresses(cbAddress);
            txtPort.Text         = "80";
            cbType.SelectedIndex = 0;
            if (!site.Server.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            if (Binding == null)
            {
                txtHost.Text = site.Server.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            }
            else
            {
                cbType.Text    = Binding.Protocol;
                cbType.Enabled = Binding == null;
                cbAddress.Text = Binding.EndPoint.Address.AddressToCombo();
                txtPort.Text   = Binding.EndPoint.Port.ToString();
                txtHost.Text   = Binding.Host.HostToDisplay();
                if (site.Server.SupportsSni)
                {
                    cbSniRequired.Checked = Binding.GetIsSni();
                }
            }

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                IPAddress address;
                try
                {
                    address = cbAddress.Text.ComboToAddress();
                }
                catch (Exception)
                {
                    MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                int port;
                try
                {
                    port = int.Parse(txtPort.Text);
                }
                catch (Exception)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (port < 1 || port > 65535)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();
                foreach (var ch in invalid)
                {
                    if (txtHost.Text.Contains(ch))
                    {
                        MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    if (txtHost.Text != "localhost")
                    {
                        MessageBox.Show(
                            "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                            Text,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }

                var certificate = cbCertificates.SelectedItem as CertificateInfo;
                var host        = txtHost.Text.DisplayToHost();
                var binding     = new Binding(
                    cbType.Text,
                    $"{address.AddressToDisplay()}:{port}:{host.HostToDisplay()}",
                    cbType.Text == "https" ? certificate?.Certificate.GetCertHash() : new byte[0],
                    cbType.Text == "https" ? certificate?.Store : null,
                    cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                    site.Bindings);
                var matched = site.Parent.FindDuplicate(binding, site, Binding);
                if (matched == true)
                {
                    var result = ShowMessage(
                        $"The binding '{binding}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (matched == null)
                {
                    ShowMessage(
                        "The specific port is being used by a different binding.",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                var conflicts = binding.DetectConflicts();
                if (conflicts)
                {
                    var result = ShowMessage(
                        $"This binding is already being used. If you continue you might overwrite the existing certificate for this IP Address:Port or Host Name:Port combination. Do you want to use this binding anyway?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (Binding == null)
                {
                    Binding = binding;
                }
                else
                {
                    Binding.Reinitialize(binding);
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    var result = Binding.FixCertificateMapping(certificate?.Certificate);
                    if (!string.IsNullOrEmpty(result))
                    {
                        MessageBox.Show($"The binding '{Binding}' is invalid: {result}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbType, "SelectedIndexChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(this, "Load"))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtPort.Text            = cbType.Text == "http" ? "80" : "443";
                txtCertificates.Visible = cbType.SelectedIndex == 1;
                cbSniRequired.Visible   = cbType.SelectedIndex == 1;
                cbCertificates.Visible  = cbType.SelectedIndex == 1;
                btnSelect.Visible       = cbType.SelectedIndex == 1;
                btnView.Visible         = cbType.SelectedIndex == 1;
            }));

            var certificatesSelected = Observable.FromEventPattern <EventArgs>(cbCertificates, "SelectedIndexChanged");

            container.Add(
                certificatesSelected
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnView.Enabled = cbCertificates.SelectedIndex > 0;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbAddress, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPort, "TextChanged"))
                .Merge(certificatesSelected)
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Helper.IsRunningOnMono())
                {
                    return;
                }

                var toElevate = BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo);
                btnOK.Enabled = toElevate != null;
                if (!toElevate.HasValue || !toElevate.Value)
                {
                    JexusManager.NativeMethods.RemoveShieldFromButton(btnOK);
                }
                else
                {
                    JexusManager.NativeMethods.TryAddShieldToButton(btnOK);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnView, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.DisplayCertificate(((CertificateInfo)cbCertificates.SelectedItem).Certificate, Handle);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSelect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                // TODO:
            }));
        }
示例#16
0
        public Site CreateSite(string applicationName)
        {
            var iis = new IIS.ServerManager();

            try
            {
                // Determine the host header values
                List <string> siteBindings        = GetDefaultBindings(applicationName, _settingsResolver.SitesBaseUrl);
                List <string> serviceSiteBindings = GetDefaultBindings(applicationName, _settingsResolver.ServiceSitesBaseUrl);

                // Create the service site for this site
                string serviceSiteName = GetServiceSite(applicationName);
                var    serviceSite     = CreateSite(iis, applicationName, serviceSiteName, _pathResolver.ServiceSitePath, serviceSiteBindings);

                IIS.Binding serviceSiteBinding = EnsureBinding(serviceSite.Bindings);
                int         serviceSitePort    = serviceSiteBinding.EndPoint.Port;

                // Create the main site
                string siteName = GetLiveSite(applicationName);
                string siteRoot = _pathResolver.GetLiveSitePath(applicationName);
                string webRoot  = Path.Combine(siteRoot, Constants.WebRoot);

                FileSystemHelpers.EnsureDirectory(webRoot);
                File.WriteAllText(Path.Combine(webRoot, "index.html"), @"<html> 
<head>
<title>The web site is under construction</title>
<style type=""text/css"">
 BODY { color: #444444; background-color: #E5F2FF; font-family: verdana; margin: 0px; text-align: center; margin-top: 100px; }
 H1 { font-size: 16pt; margin-bottom: 4px; }
</style>
</head>
<body>
<h1>The web site is under construction</h1><br/>
</body> 
</html>");

                var site = CreateSite(iis, applicationName, siteName, webRoot, siteBindings);

                IIS.Binding iisBinding = EnsureBinding(site.Bindings);
                int         sitePort   = iisBinding.EndPoint.Port;

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

                // Commit the changes to iis
                iis.CommitChanges();

                // Give IIS some time to create the site and map the path
                // REVIEW: Should we poll the site's state?
                Thread.Sleep(1000);

                var siteUrls = new List <string>();
                foreach (var url in site.Bindings)
                {
                    siteUrls.Add(String.Format("http://{0}:{1}/", String.IsNullOrEmpty(url.Host) ? "localhost" : url.Host, url.EndPoint.Port));
                }

                return(new Site
                {
                    ServiceUrl = String.Format("http://localhost:{0}/", serviceSitePort),
                    SiteUrls = siteUrls
                });
            }
            catch
            {
                DeleteSite(applicationName);
                throw;
            }
        }
        /// <summary>
        /// Overrides the install method
        /// </summary>
        /// <param name="stateSaver"></param>
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            SelectProviders selProviders = new SelectProviders();

            selProviders.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            selProviders.TopMost       = true;
            selProviders.ShowDialog();

            if (InstallationData.InstallationCanceled)
            {
                throw new InstallException("Installation cancelled by user.");
            }

            /************************************************************************************************
             * This code constructs and writes config settings for the <Providers> section of
             * <SocialAuthConfiguration> based on the input provided by the user.
             *************************************************************************************************/
            StringBuilder sbSettings = new StringBuilder("<SocialAuthConfiguration><Providers>");

            foreach (Provider prov in InstallationData.Providers)
            {
                CreateConfigSection(sbSettings, prov);
            }

            sbSettings.Append("</Providers></SocialAuthConfiguration>");


            string filePath = (Directory.GetParent(Context.Parameters["assemblypath"]).FullName) +
                              @"\Web.config";
            FileStream   stmPhysical = new FileStream(filePath, FileMode.Open);
            StreamReader srConfig    = new StreamReader(stmPhysical);

            string strConfig = srConfig.ReadToEnd();

            strConfig = strConfig.Replace("<SocialAuthConfiguration></SocialAuthConfiguration>", sbSettings.ToString());
            stmPhysical.Close();
            srConfig.Close();
            StreamWriter swConfig = new StreamWriter(filePath);

            swConfig.Write(strConfig);
            swConfig.Close();

            /************************************************************************************************
             *************************************************************************************************/

            /************************************************************************************************
             * This code makes an entry to the host file for: 127.0.0.1 opensource.brickred.com
             *************************************************************************************************/
            try
            {
                if (InstallationData.DefaultProviders)
                {
                    bool   writeToHostFile = false;
                    string hostFilePath    = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts");
                    if (!File.Exists(hostFilePath))
                    {
                        MessageBox.Show("The installer could not access host file.");
                    }

                    using (StreamReader r = new StreamReader(hostFilePath))
                    {
                        if (!r.ReadToEnd().Contains("opensource.brickred.com"))
                        {
                            writeToHostFile = true;
                        }
                    }
                    if (writeToHostFile)
                    {
                        string ip       = "127.0.0.1";
                        string sitename = Context.Parameters["targetsite"].ToString();
                        int    siteId   = Int32.Parse(sitename.Substring(sitename.LastIndexOf("/") + 1));
                        using (ServerManager serverManager = new ServerManager())
                        {
                            Site site = serverManager.Sites.FirstOrDefault(s => s.Id == siteId);
                            if (site != null)
                            {
                                Microsoft.Web.Administration.Binding binding = site.Bindings
                                                                               .Where(b => b.Protocol == "http")
                                                                               .FirstOrDefault();

                                ip = binding.BindingInformation.Substring(0, binding.BindingInformation.IndexOf(":"));
                            }
                        }

                        using (StreamWriter w = File.AppendText(hostFilePath))
                        {
                            w.WriteLine(w.NewLine + (ip == "*" ? "127.0.0.1" : ip) + " opensource.brickred.com");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not write to the host file. This entry would have to be made manually if required.");
            }

            /************************************************************************************************
             *************************************************************************************************/
        }
 public void AddUpdated(Binding binding)
 {
     _updated.Add(binding);
 }
 public void AddException(Binding binding, BindingAction action, Exception ex)
 {
     string message = string.Format("Error while {0} binding \"{1}\" to website \"{2}\"", action, binding.Host, "[TODO: website]");
     var newEx = new Exception(message, ex);
     _exceptions.Add(newEx);
 }
示例#20
0
        public NewSiteDialog(IServiceProvider serviceProvider, SiteCollection collection)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbType.SelectedIndex = 0;
            if (collection == null)
            {
                throw new InvalidOperationException("null collection");
            }

            if (collection.Parent == null)
            {
                throw new InvalidOperationException("null server for site collection");
            }

            btnBrowse.Visible = collection.Parent.IsLocalhost;
            txtPool.Text      = collection.Parent.ApplicationDefaults.ApplicationPoolName;
            btnChoose.Enabled = collection.Parent.Mode != WorkingMode.Jexus;
            txtHost.Text      = collection.Parent.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            DialogHelper.LoadAddresses(cbAddress);
            if (!collection.Parent.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbType, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtPort.Text            = cbType.Text == "http" ? "80" : "443";
                txtCertificates.Visible = cbType.SelectedIndex == 1;
                cbSniRequired.Visible   = cbType.SelectedIndex == 1;
                cbCertificates.Visible  = cbType.SelectedIndex == 1;
                btnSelect.Visible       = cbType.SelectedIndex == 1;
                btnView.Visible         = cbType.SelectedIndex == 1;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowBrowseDialog(txtPath);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in SiteCollection.InvalidSiteNameCharacters())
                {
                    if (txtName.Text.Contains(ch))
                    {
                        MessageBox.Show("The site name cannot contain the following characters: '\\, /, ?, ;, :, @, &, =, +, $, ,, |, \", <, >'.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
                {
                    if (txtName.Text.Contains(ch) || txtName.Text.StartsWith("~"))
                    {
                        MessageBox.Show("The site name cannot contain the following characters: '~,  '.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (!collection.Parent.Verify(txtPath.Text))
                {
                    MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (!IPEndPointIsValid(out IPAddress address, out int port))
                {
                    return;
                }

                var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();
                foreach (var ch in invalid)
                {
                    if (txtHost.Text.Contains(ch))
                    {
                        MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (collection.Parent.Mode == WorkingMode.IisExpress)
                {
                    if (txtHost.Text != "localhost")
                    {
                        MessageBox.Show(
                            "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                            Text,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }

                long largestId = 0;
                foreach (Site site in collection)
                {
                    if (site.Id > largestId)
                    {
                        largestId = site.Id;
                    }
                }

                largestId++;

                NewSite = new Site(collection)
                {
                    Name = txtName.Text, Id = largestId
                };
                var host    = txtHost.Text.DisplayToHost();
                var info    = cbType.Text == "https" ? (CertificateInfo)cbCertificates.SelectedItem : null;
                var binding = new Binding(
                    cbType.Text,
                    string.Format("{0}:{1}:{2}", address.AddressToDisplay(), port, host.HostToDisplay()),
                    info?.Certificate.GetCertHash() ?? new byte[0],
                    info?.Store,
                    cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                    NewSite.Bindings);
                if (collection.FindDuplicate(binding, null, null) != false)
                {
                    var result = MessageBox.Show(string.Format("The binding '{0}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?", binding), Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result != DialogResult.Yes)
                    {
                        collection.Remove(NewSite);
                        return;
                    }
                }

                if (collection.Parent.Mode == WorkingMode.IisExpress)
                {
                    var result = binding.FixCertificateMapping(info?.Certificate);
                    if (!string.IsNullOrEmpty(result))
                    {
                        collection.Remove(NewSite);
                        MessageBox.Show(string.Format("The binding '{0}' is invalid: {1}", binding, result), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                var app  = NewSite.Applications.Add(Application.RootPath, txtPath.Text);
                app.Name = string.Empty;
                app.ApplicationPoolName = txtPool.Text;
                NewSite.Bindings.Add(binding);
                DialogResult = DialogResult.OK;
            }));

            var certificatesSelected = Observable.FromEventPattern <EventArgs>(cbCertificates, "SelectedIndexChanged");

            container.Add(
                certificatesSelected
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnView.Enabled = cbCertificates.SelectedIndex > 0;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPath, "TextChanged"))
                .Merge(Observable.FromEventPattern <EventArgs>(txtPort, "TextChanged"))
                .Merge(Observable.FromEventPattern <EventArgs>(cbAddress, "TextChanged"))
                .Merge(certificatesSelected)
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Helper.IsRunningOnMono())
                {
                    return;
                }

                var toElevate = IPEndPointIsValid(out IPAddress address, out int port, false) ? BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo) : false;
                btnOK.Enabled = toElevate != null && !string.IsNullOrWhiteSpace(txtName.Text) &&
                                !string.IsNullOrWhiteSpace(txtPath.Text);
                if (!toElevate.HasValue || !toElevate.Value)
                {
                    NativeMethods.RemoveShieldFromButton(btnOK);
                }
                else
                {
                    NativeMethods.TryAddShieldToButton(btnOK);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnView, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var info = (CertificateInfo)cbCertificates.SelectedItem;
                DialogHelper.DisplayCertificate(info.Certificate, this.Handle);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnChoose, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var dialog = new SelectPoolDialog(txtPool.Text, collection.Parent);
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                txtPool.Text = dialog.Selected.Name;
            }));
        }
        public async Task<long> LoadAsync(Site site, long count, string file, string siteFolder)
        {
            SortedDictionary<string, List<string>> siteVariables = null;
            if (Credentials == null)
            {
                var rows = File.ReadAllLines(file);
                siteVariables = new SortedDictionary<string, List<string>>();
                foreach (var line in rows)
                {
                    var index = line.IndexOf('#');
                    var content = index == -1 ? line : line.Substring(0, index);
                    var parts = content.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length != 2)
                    {
                        continue;
                    }

                    var key = parts[0].Trim().ToLowerInvariant();
                    var value = parts[1].Trim();
                    if (siteVariables.ContainsKey(key))
                    {
                        siteVariables[key].Add(value);
                        continue;
                    }

                    siteVariables.Add(key, new List<string> { value });
                }
            }
            else
            {
                using (var client = GetClient())
                {
                    HttpResponseMessage response = await client.GetAsync(string.Format("api/site/{0}", file));
                    if (response.IsSuccessStatusCode)
                    {
                        siteVariables = (SortedDictionary<string, List<string>>)await response.Content.ReadAsAsync(typeof(SortedDictionary<string, List<string>>));
                    }
                }
            }

            count++;
            var useHttps = bool.Parse(siteVariables.Load(new List<string> { "false" }, "usehttps")[0]);
            var host = siteVariables.Load(new List<string> { "*" }, "hosts", "host")[0];
            var endPoint =
                new IPEndPoint(
                    IPAddress.Parse(
                        siteVariables.Load(new List<string> { IPAddress.Any.ToString() }, "addr", "address")[0]),
                    int.Parse(siteVariables.Load(new List<string> { "80" }, "port")[0]));
            var binding = new Binding(useHttps ? "https" : "http", endPoint + ":" + host, null, null, SslFlags.None, site.Bindings);

            if (useHttps)
            {
                var cert = await GetCertificateAsync();
                binding.CertificateHash = cert.GetCertHash();
            }
            else
            {
                binding.CertificateHash = new byte[0];
            }

            site.Bindings.Add(binding);
            var app = new Application(site.Applications);
            app.Path = Application.RootPath;
            app.Name = string.Empty;
            app.ApplicationPoolName = "DefaultAppPool";
            site.Applications.Add(app);
            await LoadAsync(app, null, null, siteVariables);

            IEnumerable<string> appNames = null;
            if (Credentials == null)
            {
                appNames = Directory.GetFiles(siteFolder);
                appNames = appNames.Where(name => name.StartsWith(file + "_", StringComparison.Ordinal));
            }
            else
            {
                using (var client = GetClient())
                {
                    HttpResponseMessage response = await client.GetAsync(string.Format("api/app/{0}", site.Name));
                    if (response.IsSuccessStatusCode)
                    {
                        appNames = (IEnumerable<string>)await response.Content.ReadAsAsync(typeof(IEnumerable<string>));
                    }
                }
            }

            Debug.Assert(appNames != null, "appNames != null");

            foreach (var appName in appNames)
            {
                var application = new Application(site.Applications);
                application.ApplicationPoolName = "DefaultAppPool";
                string applicationName;
                application.Path = appName.ToPath(out applicationName);
                application.Name = applicationName;
                site.Applications.Add(application);
                await LoadAsync(application, file, appName, null);
            }

            return count;
        }