Inheritance: ConfigurationElement
        internal static void Deploy(Application application, string sourceDir, IFileSystem fileSystem, string relativePathUnderVDir = "")
        {
            if (!fileSystem.DirectoryExists(sourceDir))
            {
                throw new Exception(string.Format("Failed to deploy files to application, source directory does not exist: '{0}'.", sourceDir));
            }

            if (application.VirtualDirectories.Count <= 0)
            {
                throw new Exception(string.Format("Application '{0}' does not have a virtual directory.", application.Path));
            }

            var physicalPath = application.VirtualDirectories[0].PhysicalPath;
            if (!fileSystem.DirectoryExists(physicalPath))
            {
                fileSystem.DirectoryCreate(physicalPath);
            }

            var relativeDirectoryPath = Path.Combine(physicalPath, relativePathUnderVDir);
            if (!fileSystem.DirectoryExists(relativeDirectoryPath))
            {
                fileSystem.DirectoryCreate(relativeDirectoryPath);
            }

            fileSystem.DirectoryCopy(sourceDir, relativeDirectoryPath);
            if (string.IsNullOrEmpty(relativeDirectoryPath))
            {
                fileSystem.DirectorySetAttribute(relativeDirectoryPath, FileAttributes.Normal);
            }
        }
 public void SetupApplication()
 {
     VirtualDirectoryName = new DirectoryInfo(_startParameters.ApplicationPath).Parent.Name;
     _applicationPool = CreateAppPool(VirtualDirectoryName);
     _application = Website.Applications.Add("/" + VirtualDirectoryName, _startParameters.ApplicationPath);
     _application.ApplicationPoolName = _applicationPool.Name;
     _serverManager.CommitChanges();
 }
 public void StopAndDeleteAppPool()
 {
     _logger.LogInformation("Stopping application pool '{name}' and deleting application.", _applicationPool.Name);
     _applicationPool.Stop();
     // Remove the application from website.
     _application = Website.Applications.Where(a => a.Path == _application.Path).FirstOrDefault();
     Website.Applications.Remove(_application);
     _serverManager.ApplicationPools.Remove(_serverManager.ApplicationPools[_applicationPool.Name]);
     _serverManager.CommitChanges();
     _logger.LogInformation("Successfully stopped application pool '{name}' and deleted application from IIS.", _applicationPool.Name);
 }
Exemple #4
0
 public string Deploy(string applicationName, KatanaWebConfiguration webConfig)
 {
     this.WebServer = WebServer.Create(GetWebServerType());
     string uniqueAppName = this.WebServer.DefaultWebSite.GetUniqueApplicaionName(applicationName);
     string appPhysicalPath = Path.Combine(this.WebServer.RootPhysicalPath, uniqueAppName);
     this.Application = this.WebServer.DefaultWebSite.Applications.Add("/" + uniqueAppName, appPhysicalPath);
     this.Application.Deploy(GetAssembliesInCurrentDirectory(), "bin");
     this.Application.Deploy("web.config", webConfig.GetWebConfigurationContent());
     this.WebServer.ServerManager.CommitChanges();
     return this.WebServer.DefaultWebSite.GetHttpVirtualPath() + this.Application.Path;
 }
 protected void LoadVirtualDirectory()
 {
     using (var iis = ServerManager.OpenRemote("localhost"))
     {
         var site = iis.Sites[WebSiteName];
         var appPath = "/" + VirtualDirectory;
         application = site.Applications[appPath];
         vDir = application.VirtualDirectories["/"];
         applicationPool = iis.ApplicationPools[application.ApplicationPoolName];
     }
 }
Exemple #6
0
        public SampleTest()
        {
            if (Server == null)
            {
                Server = CreateWebServer();

                Application = Server.CreateWebApplication(WebSiteName);
                Application.Deploy(WebSiteName);

                VirtualPath = Server.GetApplicationVirtualPath(Application);
            }
        }
        public DashboardServer(string deployPath)
        {
            if (string.IsNullOrWhiteSpace(deployPath))
            {
                throw new ArgumentNullException(deployPath);
            }

            _server = WebServer.Create(WebServerType.IISExpress);
            _application = _server.CreateWebApplication(ApplicationName);
            _application.Deploy(deployPath);

            _webConfigFilePath = Path.Combine(_server.RootPhysicalPath, ApplicationName, "web.config");
            _virtualPath = _server.GetApplicationVirtualPath(_application, TestEasyConfig.Instance.Client.Remote);
        }
		private void Initialize(Application application, string siteKey, string siteName)
		{
			this.Key = GetApplicationVariableName(siteKey, application.Path);
			this.IsRootApplication = (application.Path == "/");

			AddAttribute("Name", application.Path);
			AddAttribute("Ensure", "Present");
			AddAttribute("Website", siteName);
			AddAttribute("PhysicalPath", application.VirtualDirectories[0].PhysicalPath);

			this.ApplicationPool =application.ApplicationPoolName;
			AddAttribute("WebAppPool", this.ApplicationPool);
			
			AddAttribute("DependsOn", "[cAppPool]" + PoolDesiredState.GetPoolVariableName(application.ApplicationPoolName));

			this.VirtualDirectories = GetVirtualDirectories(application.VirtualDirectories, siteName, application.Path);
		}
        internal Site(ConfigurationElement element, SiteCollection parent)
            : base(element, "site", null, parent, null, null)
        {
            ApplicationDefaults = ChildElements["applicationDefaults"] == null
                ? new ApplicationDefaults(parent.ChildElements["applicationDefaults"], this)
                : new ApplicationDefaults(ChildElements["applicationDefaults"], this);
            Parent = parent;
            if (element == null)
            {
                return;
            }

            foreach (ConfigurationElement node in (ConfigurationElementCollection)element)
            {
                var app = new Application(node, Applications);
                Applications.InternalAdd(app);
            }
        }
Exemple #10
0
        public static void CreateIISApplication(string appName, string physicalPath, string appPool)
        {
            ServerManager iisManager  = new ServerManager();
            Site          defaultSite = iisManager.Sites["Default Web Site"];

            Microsoft.Web.Administration.Application app = defaultSite.Applications[String.Format("/{0}", appName)];

            //Remove application if it already exists
            if (app != null)
            {
                defaultSite.Applications.Remove(app);
                iisManager.CommitChanges();
            }

            defaultSite.Applications.Add(String.Format("/{0}", appName), physicalPath);
            SetApplicationPool(appName, appPool);
            iisManager.CommitChanges();
            iisManager.Dispose();
        }
Exemple #11
0
        private void DeleteWebsite(Site site, bool checkBoxOnDeleteAlsoDeleteDb, bool checkBoxIncludeFiles)
        {
            string           sitename    = site.Name;
            Application      application = site.Applications[0];
            VirtualDirectory directory   = application.VirtualDirectories[0];

            string websitePath = directory.PhysicalPath;

            DirectoryInfo di = new DirectoryInfo(websitePath);

            Trace.WriteLine(string.Format("DeleteWebsite IIS: {0}", sitename));

            string appplicationPoolName = application.ApplicationPoolName;

            site.Delete();

            foreach (ApplicationPool pool in iisManager.ApplicationPools)
            {
                if (pool.State == ObjectState.Started)
                {
                    pool.Stop();
                }
                if (pool.Name == appplicationPoolName)
                {
                    pool.Delete();
                }
            }

            Util.DeleteDatabase(sitename);

            try
            {
                di.Parent.Delete(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Could not delete: {0}", di.Parent.FullName));
            }
            finally
            {
            }
        }
Exemple #12
0
        public NewVirtualDirectoryDialog(IServiceProvider serviceProvider, VirtualDirectory existing, string pathToSite, Application application)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = application.Site.Name;
            txtPath.Text      = pathToSite;
            btnBrowse.Visible = application.Server.IsLocalhost;
            _application      = application;
            VirtualDirectory  = existing;
            Text = VirtualDirectory == null ? "Add Virtual Directory" : "Edit Virtual Directory";
            txtAlias.ReadOnly = VirtualDirectory != null;
            if (VirtualDirectory == null)
            {
                // TODO: test if IIS does this
                return;
            }

            txtAlias.Text        = VirtualDirectory.Path.PathToName();
            txtPhysicalPath.Text = VirtualDirectory.PhysicalPath;
        }
        public override void LoadPanels(MainForm mainForm, ServiceContainer serviceContainer, List <ModuleProvider> moduleProviders)
        {
            serviceContainer.RemoveService(typeof(IConfigurationService));
            serviceContainer.RemoveService(typeof(IControlPanel));
            var panel = new ApplicationPage(Application, mainForm);
            var scope = ManagementScope.Application;

            serviceContainer.AddService(typeof(IControlPanel), new ControlPanel());
            serviceContainer.AddService(typeof(IConfigurationService),
                                        new ConfigurationService(mainForm, Application.GetWebConfiguration(), scope, null, Application.Site,
                                                                 Application, null, null, this.Application.Location));
            foreach (var provider in moduleProviders)
            {
                if (!provider.SupportsScope(scope))
                {
                    continue;
                }

                var definition = provider.GetModuleDefinition(null);
                var type       = Type.GetType(definition.ClientModuleTypeName);
                if (type == null)
                {
                    continue;
                }

                if (!typeof(Module).IsAssignableFrom(type))
                {
                    continue;
                }

                var module = (Module)Activator.CreateInstance(type);
                module.Initialize(serviceContainer, null);
            }

            IModulePage page       = panel;
            var         mainModule = new MainModule();

            mainModule.Initialize(serviceContainer, null);
            page.Initialize(mainModule, null, null);
            mainForm.LoadPage(page);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="IisWebApplication"/> class.
        /// </summary>
        /// <param name="appName">
        /// The app name.
        /// </param>
        /// <param name="physicalPath">
        /// The physical Path.
        /// </param>
        /// <param name="site">
        /// The site.
        /// </param>
        /// <param name="pool">
        /// The pool.
        /// </param>
        public IisWebApplication(string appName, string physicalPath, IisWebSite site, IisApplicationPool pool)
        {
            try
            {
                this.Name = appName;
                this.IisPath = site.Name + this.Name;
                this.currentPool = pool;
                this.iisSite = site;

                this.serverManager = new ServerManager();
                string relativePath = Path.Combine(Environment.CurrentDirectory, physicalPath);
                string absolutePath = Path.GetFullPath(relativePath);

                Site targetSite = this.serverManager.Sites[site.Name];
                if (targetSite != null)
                {
                    if (targetSite.Applications[this.Name] != null)
                    {
                        // removing if application already exists - because it can exists with the wrong physical path.
                        this.Remove();

                        // refreshing target site.
                        targetSite = this.serverManager.Sites[site.Name];
                    }

                    this.app = targetSite.Applications.Add(this.Name, absolutePath);
                    this.app.ApplicationPoolName = pool.Name;
                }

                this.serverManager.CommitChanges();

                Trace.TraceInformation(
               "IISWebApplication {0} created successfully.", appName);
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception occured while creating application: {0}. The exception thrown was {1}", this.iisSite.Name, ex.Message);
            }
        }
        public NewApplicationDialog(IServiceProvider serviceProvider, Site site, string parentPath, string pool, Application existing)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = site.Name;
            txtPath.Text      = parentPath;
            btnBrowse.Visible = site.Server.IsLocalhost;
            btnSelect.Enabled = site.Server.Mode != WorkingMode.Jexus;
            _site             = site;
            _parentPath       = parentPath;
            Application       = existing;
            Text = Application == null ? "Add Application" : "Edit Application";
            txtAlias.ReadOnly = Application != null;
            if (Application == null)
            {
                // TODO: test if IIS does this
                txtPool.Text = pool;
                return;
            }

            txtAlias.Text = Application.Name ?? Application.Path.PathToName();
            txtPool.Text  = Application.ApplicationPoolName;
            foreach (VirtualDirectory directory in Application.VirtualDirectories)
            {
                if (directory.Path == Application.Path)
                {
                    txtPhysicalPath.Text = directory.PhysicalPath;
                }
            }
        }
        internal static bool IsJexus(ServerManager server, Application application)
        {
            if (server != null)
            {
                return server.Mode == WorkingMode.Jexus;
            }

            if (application == null)
            {
                throw new ArgumentException("both server and applicatioin null");
            }

            return application.Server.Mode == WorkingMode.Jexus;
        }
        private string GetVersion(Application application)
        {
            
            string fileName = application.VirtualDirectories[0].PhysicalPath + @"\bin\" + application.Path.Replace(@"/", "") + ".dll";

            if (File.Exists(fileName))
                return FileVersionInfo.GetVersionInfo(fileName).FileVersion;
            else
                return "";
        }
        public NewVirtualDirectoryDialog(IServiceProvider serviceProvider, VirtualDirectory existing, string pathToSite, Application application)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = application.Site.Name;
            txtPath.Text      = pathToSite;
            btnBrowse.Visible = application.Server.IsLocalhost;
            VirtualDirectory  = existing;
            Text = VirtualDirectory == null ? "Add Virtual Directory" : "Edit Virtual Directory";
            txtAlias.ReadOnly = VirtualDirectory != null;
            if (VirtualDirectory == null)
            {
                // TODO: test if IIS does this
            }
            else
            {
                txtAlias.Text        = VirtualDirectory.Path.PathToName();
                txtPhysicalPath.Text = VirtualDirectory.PhysicalPath;
            }

            var container = new CompositeDisposable();

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

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtAlias, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtAlias.Text) && !string.IsNullOrWhiteSpace(txtPhysicalPath.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in ApplicationCollection.InvalidApplicationPathCharacters())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        ShowMessage("The application path cannot contain the following characters: \\, ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }
                }

                foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        ShowMessage("The site name cannot contain the following characters: ' '.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }
                }

                if (!application.Server.Verify(txtPhysicalPath.Text))
                {
                    ShowMessage("The specified directory does not exist on the server.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

                if (VirtualDirectory == null)
                {
                    // TODO: fix this
                    try
                    {
                        VirtualDirectory = new VirtualDirectory(null, application.VirtualDirectories)
                        {
                            Path = "/" + txtAlias.Text
                        };
                    }
                    catch (COMException ex)
                    {
                        ShowError(ex, string.Empty, false);
                        return;
                    }

                    VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
                    VirtualDirectory.Parent.Add(VirtualDirectory);
                }
                else
                {
                    VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
                }

                DialogResult = DialogResult.OK;
            }));
        }
Exemple #19
0
        public NewApplicationDialog(IServiceProvider serviceProvider, Site site, string parentPath, string pool, Application existing)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = site.Name;
            txtPath.Text      = parentPath;
            btnBrowse.Visible = site.Server.IsLocalhost;
            btnSelect.Enabled = site.Server.Mode != WorkingMode.Jexus;
            _site             = site;
            _parentPath       = parentPath;
            Application       = existing;
            Text = Application == null ? "Add Application" : "Edit Application";
            txtAlias.ReadOnly = Application != null;
            if (Application == null)
            {
                // TODO: test if IIS does this
                txtPool.Text = pool;
            }
            else
            {
                txtAlias.Text = Application.Name ?? Application.Path.PathToName();
                txtPool.Text  = Application.ApplicationPoolName;
                foreach (VirtualDirectory directory in Application.VirtualDirectories)
                {
                    if (directory.Path == Application.Path)
                    {
                        txtPhysicalPath.Text = directory.PhysicalPath;
                    }
                }

                RefreshButton();
            }

            var item = new ConnectAsItem(Application?.VirtualDirectories[0]);

            var container = new CompositeDisposable();

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

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtAlias, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                RefreshButton();
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in ApplicationCollection.InvalidApplicationPathCharacters())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        MessageBox.Show("The application path cannot contain the following characters: \\, ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

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

                if (!_site.Server.Verify(txtPhysicalPath.Text, site.Applications[0].GetActualExecutable()))
                {
                    MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (Application == null)
                {
                    string path = string.Format("{0}/{1}", _parentPath.TrimEnd('/'), txtAlias.Text);
                    foreach (VirtualDirectory virtualDirectory in _site.Applications[0].VirtualDirectories)
                    {
                        if (string.Equals(virtualDirectory.Path, path, StringComparison.OrdinalIgnoreCase))
                        {
                            ShowMessage("This virtual directory already exists.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            return;
                        }
                    }

                    foreach (Application application in _site.Applications)
                    {
                        if (string.Equals(path, application.Path))
                        {
                            ShowMessage("An application with this virtual path already exists.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            return;
                        }
                    }

                    Application      = _site.Applications.Add(path, txtPhysicalPath.Text);
                    Application.Name = txtAlias.Text;
                    Application.ApplicationPoolName = txtPool.Text;

                    item.Element = Application.VirtualDirectories[0];
                    item.Apply();
                }
                else
                {
                    foreach (VirtualDirectory directory in Application.VirtualDirectories)
                    {
                        if (directory.Path == Application.Path)
                        {
                            directory.PhysicalPath = txtPhysicalPath.Text;
                        }
                    }
                }

                DialogResult = DialogResult.OK;
            }));

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

                txtPool.Text = dialog.Selected.Name;
                if (Application != null)
                {
                    Application.ApplicationPoolName = dialog.Selected.Name;
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnConnect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var dialog = new ConnectAsDialog(ServiceProvider, item);
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                item.Apply();
                txtConnectAs.Text = string.IsNullOrEmpty(item.UserName)
                        ? "Pass-through authentication"
                        : $"connect as '{item.UserName}'";
                RefreshButton();
            }));

            txtConnectAs.Text = string.IsNullOrEmpty(item.UserName)
                ? "Pass-through authentication"
                : $"connect as '{item.UserName}'";
        }
        private static IISApplication PopulateApplication(Application smApp)
        {
            var app = new IISApplication();
            app.AppPoolName = smApp.ApplicationPoolName;
            app.Path = smApp.Path;
            var attributes = smApp.Attributes;
            if(attributes["preloadEnabled"]!=null && attributes["preloadEnabled"].Value != null && attributes["preloadEnabled"].Value is bool)
            {
                app.EnablePreload = (bool)attributes["preloadEnabled"].Value;
            }
            app.EnabledProtocols = attributes["enabledProtocols"]?.Value as string;
            if (smApp.VirtualDirectories.Count >= 1)
            {
                app.PhysicalPath = Environment.ExpandEnvironmentVariables(smApp.VirtualDirectories[0].PhysicalPath);
                app.SpecificUser = smApp.VirtualDirectories[0].UserName;
                app.AuthenticationLogonMethod = Enum.GetName(typeof(AuthenticationLogonMethod), smApp.VirtualDirectories[0].LogonMethod);
            }
            app.Libraries = GetLibsForApp(app.PhysicalPath);
            app.Modules = GetModulesForApp(app.PhysicalPath);

            return app;
        }
        public async Task SaveAsync(Application application)
        {
            var variables = new SortedDictionary<string, List<string>>();
            foreach (var item in application.Extra)
            {
                variables.Add(item.Key, item.Value);
            }

            var vDir = application.VirtualDirectories[0];

            Configuration config = application.GetWebConfiguration();
            ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
            ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
            ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location);
            ConfigurationSection ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location);

            ConfigurationSection requestFilteringSection = config.GetSection("system.webServer/security/requestFiltering");
            ConfigurationElement hiddenSegmentsElement = requestFilteringSection.GetChildElement("hiddenSegments");
            ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();

            ConfigurationSection httpErrorsSection = config.GetSection("system.webServer/httpErrors");
            ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection();

            var urlCompressionSection = config.GetSection("system.webServer/urlCompression");

            ConfigurationSection httpProtocolSection = config.GetSection("system.webServer/httpProtocol");

            ConfigurationSection rewriteSection = config.GetSection("system.webServer/rewrite/rules");
            ConfigurationElementCollection rewriteCollection = rewriteSection.GetCollection();

            variables.Add("usehttps", new List<string> { (application.Site.Bindings[0].Protocol == "https").ToString() });
            variables.Add("addr", new List<string> { application.Site.Bindings[0].EndPoint.Address.ToString() });
            variables.Add("port", new List<string> { application.Site.Bindings[0].EndPoint.Port.ToString() });
            variables.Add("hosts", new List<string> { application.Site.Bindings[0].Host });
            variables.Add("root", new List<string> { string.Format("{0} {1}", vDir.Path, vDir.PhysicalPath) });
            variables.Add("nolog", new List<string> { httpLoggingSection["dontLog"].ToString() });
            variables.Add("keep_alive", new List<string> { httpProtocolSection["allowKeepAlive"].ToString() });

            var indexes = new StringBuilder();
            foreach (ConfigurationElement item in filesCollection)
            {
                indexes.AppendFormat("{0},", item.RawAttributes["value"]);
            }

            if (indexes.Length > 0)
            {
                indexes.Length--;
            }

            variables.Add("indexes", new List<string> { indexes.ToString() });

            var allows = new List<string>();
            var denys = new List<string>();
            foreach (ConfigurationElement item in ipSecuritySection.GetCollection())
            {
                string element = string.IsNullOrEmpty((string)item["subnetMask"])
                    ? (string)item["ipAddress"]
                    : string.Format("{0}/{1}", item["ipAddress"], item["subnetMask"]);
                if ((bool)item["allowed"])
                {
                    allows.Add(element);
                }
                else
                {
                    denys.Add(element);
                }
            }

            variables.Add("allowfrom", allows);
            variables.Add("denyfrom", denys);

            var segments = new StringBuilder();
            foreach (ConfigurationElement item in hiddenSegmentsCollection)
            {
                segments.AppendFormat("{0},", item["segment"]);
            }

            if (segments.Length > 0)
            {
                segments.Length--;
            }

            variables.Add("denydirs", new List<string> { segments.ToString() });

            foreach (ConfigurationElement item in httpErrorsCollection)
            {
                if ((uint)item["statusCode"] == 404 && (int)item["subStatusCode"] == 0
                    && (string)item["prefixLanguageFilePath"] == @"%SystemDrive%\inetpub\custerr"
                    && (long)item["responseMode"] == 1)
                {
                    variables.Add("nofile", new List<string> { item["path"].ToString() });
                }
            }

            variables.Add("usegzip", new List<string> { urlCompressionSection["doStaticCompression"].ToString() });

            var rules = new List<string>();
            foreach (ConfigurationElement item in rewriteCollection)
            {
                var action = item.GetChildElement("action");
                var match = item.GetChildElement("match");
                if ((long)action["type"] == 2)
                {
                    rules.Add(string.Format("{0}{2} {1}", match["url"], action["url"], (bool)match["ignoreCase"] ? "/i" : string.Empty));
                }
            }

            variables.Add("rewrite", rules);

            if (string.IsNullOrEmpty(application.Server.HostName))
            {
                var rows = new List<string>();
                foreach (var item in variables)
                {
                    foreach (var line in item.Value)
                    {
                        rows.Add(string.Format("{0}={1}", item.Key, line));
                    }
                }

                var fileName = Path.Combine("siteconf", application.ToFileName());
                File.WriteAllLines(fileName, rows);
            }
            else
            {
                using (var client = GetClient())
                {
                    HttpResponseMessage response = await client.PutAsJsonAsync(string.Format("api/site/{0}", application.ToFileName()), variables);
                    if (response.IsSuccessStatusCode)
                    {
                    }
                }
            }
        }
        public async Task LoadAsync(Application application, string file, string appName, SortedDictionary<string, List<string>> variables)
        {
            if (variables == null)
            {
                if (Credentials == null)
                {
                    var rows = File.ReadAllLines(file);
                    variables = 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 (variables.ContainsKey(key))
                        {
                            variables[key].Add(value);
                            continue;
                        }

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

            variables.Load(new List<string> { "false" }, "usehttps");
            variables.Load(new List<string> { "*" }, "hosts", "host");
            variables.Load(new List<string> { IPAddress.Any.ToString() }, "addr", "address");
            variables.Load(new List<string> { "80" }, "port");
            var root = variables.Load(new List<string> { "/ /var/www/default" }, "root")[0];
            var split = root.IndexOf(' ');
            if (split == -1 || split == 0)
            {
                throw new ServerManagerException("invalid root mapping");
            }

            var virtualDirectory = new VirtualDirectory(null, application.VirtualDirectories);
            virtualDirectory.Path = root.Substring(0, split);
            virtualDirectory.PhysicalPath = root.Substring(split + 1);
            application.VirtualDirectories.Add(virtualDirectory);
            var configuration = application.GetWebConfiguration();
            var defaultDocument = configuration.GetSection("system.webServer/defaultDocument");
            defaultDocument["enabled"] = true;
            var collection = defaultDocument.GetCollection("files");
            collection.Clear();
            var names = variables.Load(new List<string> { Constants.DefaultDocumentList }, "indexes", "indexs")[0];
            var pageNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var name in pageNames)
            {
                var file1 = collection.CreateElement();
                file1.Attributes["value"].Value = name;
                collection.Add(file1);
            }


            ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location);
            var dontLog = Convert.ToBoolean(variables.Load(new List<string> { "false" }, "nolog")[0]);
            httpLoggingSection["dontLog"] = dontLog;

            var ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location);
            ipSecuritySection["enableReverseDns"] = false;
            ipSecuritySection["allowUnlisted"] = true;

            ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
            ipSecurityCollection.Clear();
            var deny = variables.Load(new List<string>(), "denyfrom", "ip.deny");
            foreach (var denyEntry in deny)
            {
                var denyItems = denyEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in denyItems)
                {
                    ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                    if (item.Contains("/"))
                    {
                        var parts = item.Split('/');
                        addElement["ipAddress"] = parts[0];
                        addElement["subnetMask"] = parts[1];
                    }
                    else
                    {
                        addElement["ipAddress"] = item;
                    }

                    addElement["allowed"] = false;
                    ipSecurityCollection.Add(addElement);
                }
            }

            var allow = variables.Load(new List<string>(), "allowfrom", "ip.allow");
            foreach (var allowEntry in allow)
            {
                var allowItems = allowEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in allowItems)
                {
                    ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                    if (item.Contains("/"))
                    {
                        var parts = item.Split('/');
                        addElement["ipAddress"] = parts[0];
                        addElement["subnetMask"] = parts[1];
                    }
                    else
                    {
                        addElement["ipAddress"] = item;
                    }

                    addElement["allowed"] = true;
                    ipSecurityCollection.Add(addElement);
                }
            }

            ConfigurationSection requestFilteringSection = configuration.GetSection("system.webServer/security/requestFiltering");
            ConfigurationElement hiddenSegmentsElement = requestFilteringSection.ChildElements["hiddenSegments"];
            ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
            hiddenSegmentsCollection.Clear();
            var hidden = variables.Load(new List<string> { string.Empty }, "denydirs")[0];
            var hiddenItems = hidden.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in hiddenItems)
            {
                ConfigurationElement add = hiddenSegmentsCollection.CreateElement("add");
                add["segment"] = item;
                hiddenSegmentsCollection.Add(add);
            }

            ConfigurationSection httpErrorsSection = configuration.GetSection("system.webServer/httpErrors");
            ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection();
            httpErrorsCollection.Clear();
            Debug.Assert(variables != null, "variables != null");
            if (variables.ContainsKey("nofile"))
            {
                var error = variables["nofile"][0];
                ConfigurationElement errorElement = httpErrorsCollection.CreateElement("error");
                errorElement["statusCode"] = 404;
                errorElement["subStatusCode"] = 0;
                errorElement["prefixLanguageFilePath"] = @"%SystemDrive%\inetpub\custerr";
                errorElement["responseMode"] = "ExecuteURL";
                errorElement["path"] = error;
                httpErrorsCollection.Add(errorElement);
                variables.Remove("nofile");
            }

            var urlCompressionSection = configuration.GetSection("system.webServer/urlCompression");
            urlCompressionSection["doStaticCompression"] = Convert.ToBoolean(variables.Load(new List<string> { "true" }, "usegzip")[0]);

            ConfigurationSection httpProtocolSection = configuration.GetSection("system.webServer/httpProtocol");
            httpProtocolSection["allowKeepAlive"] = Convert.ToBoolean(variables.Load(new List<string> { "true" }, "keep_alive")[0]);

            ConfigurationSection rulesSection = configuration.GetSection("system.webServer/rewrite/rules");
            ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
            rulesCollection.Clear();
            if (variables.ContainsKey("rewrite"))
            {
                var rules = variables["rewrite"];
                for (int i = 0; i < rules.Count; i++)
                {
                    var rule = rules[i];
                    ConfigurationElement ruleElement = rulesCollection.CreateElement("rule");
                    ruleElement["name"] = @"rule" + i;
                    ruleElement["enabled"] = true;
                    ruleElement["patternSyntax"] = 0;
                    ruleElement["stopProcessing"] = false;

                    var parts = rule.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    ConfigurationElement matchElement = ruleElement.GetChildElement("match");
                    matchElement["ignoreCase"] = parts[0].EndsWith("/i", StringComparison.Ordinal);
                    matchElement["url"] = parts[0].EndsWith("/i", StringComparison.Ordinal) ? parts[0].Substring(0, parts[0].Length - 2) : parts[0];

                    ConfigurationElement actionElement = ruleElement.GetChildElement("action");
                    actionElement["type"] = 2;
                    actionElement["url"] = parts[1];
                    actionElement["appendQueryString"] = true;
                    rulesCollection.Add(ruleElement);
                }

                variables.Remove("rewrite");
            }

            application.Extra = variables;
        }
        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;
        }
Exemple #24
0
        private WebApplicationInfo GetWebApplicationInfo(Application application)
        {
            var virtualPath = _serverManager.Sites[DefaultWebsiteName].GetHttpVirtualPath() + application.Path;

            if (TestEasyConfig.Instance.Client.Remote)
            {
                virtualPath = virtualPath.Replace("localhost", Environment.MachineName);
            }

            var remoteVirtualPath = virtualPath.Replace("localhost", Environment.MachineName);
            return new WebApplicationInfo
            {
                Name = application.Path.Trim('/'),
                PhysicalPath = application.VirtualDirectories[0].PhysicalPath,
                VirtualPath = virtualPath,
                RemoteVirtualPath = remoteVirtualPath
            };
        }
 private void loadVirtualDirectory()
 {
     using (var iis = ServerManager.OpenRemote("localhost"))
     {
         var site = iis.Sites[WebSiteName];
         var appPath = "/" + VirtualDirectory;
         _application = site.Applications[appPath];
         _virtualDirectory = _application.VirtualDirectories["/"];
         _appPool = iis.ApplicationPools[_application.ApplicationPoolName];
     }
 }
Exemple #26
0
 public ConfigurationService(Form form, Configuration config, ManagementScope scope, ServerManager server, Site site, Microsoft.Web.Administration.Application application, VirtualDirectory virtualDirectory, PhysicalDirectory physicalDirectory, string location)
 {
     Scope             = scope;
     Server            = server;
     Application       = application;
     Site              = site;
     Form              = form;
     VirtualDirectory  = virtualDirectory;
     PhysicalDirectory = physicalDirectory;
     _config           = config;
     _location         = location;
 }
Exemple #27
0
        public EditSiteDialog(IServiceProvider serviceProvider, Application application)
            : base(serviceProvider)
        {
            InitializeComponent();
            _application         = application;
            txtPool.Text         = application.ApplicationPoolName;
            txtAlias.Text        = application.Site.Name;
            txtPhysicalPath.Text = application.PhysicalPath;
            btnBrowse.Visible    = application.Server.IsLocalhost;
            btnSelect.Enabled    = application.Server.Mode != WorkingMode.Jexus;

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (!_application.Server.Verify(txtPhysicalPath.Text))
                {
                    MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                _application.PhysicalPath        = txtPhysicalPath.Text;
                _application.ApplicationPoolName = txtPool.Text;
                _application.Server.CommitChanges();
                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPool, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtPhysicalPath.Text);
            }));

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

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

                txtPool.Text = dialog.Selected.Name;
            }));
        }
Exemple #28
0
        public NewVirtualDirectoryDialog(IServiceProvider serviceProvider, VirtualDirectory existing, string pathToSite, Application application)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = application.Site.Name;
            txtPath.Text      = pathToSite;
            btnBrowse.Visible = application.Server.IsLocalhost;
            VirtualDirectory  = existing;
            Text = VirtualDirectory == null ? "Add Virtual Directory" : "Edit Virtual Directory";
            txtAlias.ReadOnly = VirtualDirectory != null;
            if (VirtualDirectory == null)
            {
                // TODO: test if IIS does this
            }
            else
            {
                txtAlias.Text        = VirtualDirectory.Path.PathToName();
                txtPhysicalPath.Text = VirtualDirectory.PhysicalPath;
                RefreshButton();
            }

            var item = new ConnectAsItem(VirtualDirectory);

            var container = new CompositeDisposable();

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

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtAlias, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(0.5))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                RefreshButton();
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in ApplicationCollection.InvalidApplicationPathCharacters())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        ShowMessage("The application path cannot contain the following characters: \\, ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }
                }

                foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        ShowMessage("The site name cannot contain the following characters: ' '.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }
                }

                if (!application.Server.Verify(txtPhysicalPath.Text, application.GetActualExecutable()))
                {
                    ShowMessage("The specified directory does not exist on the server.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

                if (VirtualDirectory == null)
                {
                    string path = "/" + txtAlias.Text;
                    foreach (VirtualDirectory virtualDirectory in application.VirtualDirectories)
                    {
                        if (string.Equals(virtualDirectory.Path, path, StringComparison.OrdinalIgnoreCase))
                        {
                            ShowMessage("This virtual directory already exists.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            return;
                        }
                    }

                    var fullPath = $"{txtPath.Text}{path}";
                    foreach (Application app in application.Site.Applications)
                    {
                        if (string.Equals(fullPath, app.Path))
                        {
                            ShowMessage("An application with this virtual path already exists.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            return;
                        }
                    }

                    try
                    {
                        VirtualDirectory = new VirtualDirectory(null, application.VirtualDirectories)
                        {
                            Path = path
                        };
                    }
                    catch (COMException ex)
                    {
                        ShowError(ex, Text, false);
                        return;
                    }

                    VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
                    VirtualDirectory.Parent.Add(VirtualDirectory);

                    item.Element = VirtualDirectory;
                    item.Apply();
                }
                else
                {
                    VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
                }

                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnConnect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                using (var dialog = new ConnectAsDialog(ServiceProvider, item))
                {
                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                }

                item.Apply();
                RefreshButton();
                txtConnectAs.Text = string.IsNullOrEmpty(item.UserName)
                        ? "Pass-through authentication"
                        : $"connect as '{item.UserName}'";
            }));

            txtConnectAs.Text = string.IsNullOrEmpty(item.UserName)
                ? "Pass-through authentication"
                : $"connect as '{item.UserName}'";
        }
		public ApplicationDesiredState(Application application, string siteKey, string siteName)
		{
			Initialize(application, siteKey, siteName);
		}
        /// <summary>
        /// Creates a virtual directory, if it does not already exist.
        /// </summary>
        /// <param name="parent">The parent application.</param>
        /// <param name="virtualDirectorySpec">Specification for an IIS Virtual Directory.</param>
        private void AddVirtualDirectory(Application parent, VirtualDirectorySpecification virtualDirectorySpec)
        {
            string iisFriendlyName = '/' + virtualDirectorySpec.Name;
            VirtualDirectory virtualDirectory = parent.VirtualDirectories.FirstOrDefault(v => v.Path == iisFriendlyName);
            if (virtualDirectory == null)
            {
                if (!File.Exists(virtualDirectorySpec.PhysicalPath))
                {
                    Directory.CreateDirectory(virtualDirectorySpec.PhysicalPath);
                }

                this.installLogger.Log(string.Format(Messages.WEB_CreateVirtualDirectory, virtualDirectorySpec.Name));
                parent.VirtualDirectories.Add(iisFriendlyName, virtualDirectorySpec.PhysicalPath);
                this.installLogger.LogSuccess(Messages.MAIN_StepComplete);
                this.AddFolderPermission(virtualDirectorySpec.PhysicalPath, virtualDirectorySpec.Permission, parent.ApplicationPoolName);
            }
        }
Exemple #31
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;
                }

                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)
                    {
                        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 = 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;
            }));

            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 = BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo);
                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;
            }));
        }
Exemple #32
0
        public EditSiteDialog(IServiceProvider serviceProvider, Application application)
            : base(serviceProvider)
        {
            InitializeComponent();
            _application         = application;
            txtPool.Text         = application.ApplicationPoolName;
            txtAlias.Text        = application.Site.Name;
            txtPhysicalPath.Text = application.PhysicalPath;
            btnBrowse.Visible    = application.Server.IsLocalhost;
            btnSelect.Enabled    = application.Server.Mode != WorkingMode.Jexus;
            RefreshButton();

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (!_application.Server.Verify(txtPhysicalPath.Text, _application.GetActualExecutable()))
                {
                    MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                _application.PhysicalPath        = txtPhysicalPath.Text;
                _application.ApplicationPoolName = txtPool.Text;
                _application.Server.CommitChanges();
                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPool, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                RefreshButton();
            }));

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

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

                txtPool.Text = dialog.Selected.Name;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnConnect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var item = new ConnectAsItem(_application.VirtualDirectories[0]);
                using (var dialog = new ConnectAsDialog(ServiceProvider, item))
                {
                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                }

                item.Apply();
                txtConnectAs.Text = string.IsNullOrEmpty(application.VirtualDirectories[0].UserName)
                        ? "Pass-through authentication"
                        : $"connect as '{application.VirtualDirectories[0].UserName}'";
                RefreshButton();
            }));

            txtConnectAs.Text = string.IsNullOrEmpty(application.VirtualDirectories[0].UserName)
                ? "Pass-through authentication"
                : $"connect as '{application.VirtualDirectories[0].UserName}'";
        }
 public static List <VirtualDirectory> virtualDirs(this Microsoft.Web.Administration.Application application)
 {
     return(application.VirtualDirectories.toList());
 }
Exemple #34
0
 private VirtualDirectory CreateVirtualDirectory(Application application, string name)
 {
     return application.VirtualDirectories.Add(string.Concat("/", name), Path.Combine(_webPhysicalPath, name));
 }
        public NewApplicationDialog(IServiceProvider serviceProvider, Site site, string parentPath, string pool, Application existing)
            : base(serviceProvider)
        {
            InitializeComponent();
            txtSite.Text      = site.Name;
            txtPath.Text      = parentPath;
            btnBrowse.Visible = site.Server.IsLocalhost;
            btnSelect.Enabled = site.Server.Mode != WorkingMode.Jexus;
            _site             = site;
            _parentPath       = parentPath;
            Application       = existing;
            Text = Application == null ? "Add Application" : "Edit Application";
            txtAlias.ReadOnly = Application != null;
            if (Application == null)
            {
                // TODO: test if IIS does this
                txtPool.Text = pool;
            }
            else
            {
                txtAlias.Text = Application.Name ?? Application.Path.PathToName();
                txtPool.Text  = Application.ApplicationPoolName;
                foreach (VirtualDirectory directory in Application.VirtualDirectories)
                {
                    if (directory.Path == Application.Path)
                    {
                        txtPhysicalPath.Text = directory.PhysicalPath;
                    }
                }
            }

            var container = new CompositeDisposable();

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

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtAlias, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPhysicalPath, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtAlias.Text) && !string.IsNullOrWhiteSpace(txtPhysicalPath.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in ApplicationCollection.InvalidApplicationPathCharacters())
                {
                    if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                    {
                        MessageBox.Show("The application path cannot contain the following characters: \\, ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

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

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

                if (Application == null)
                {
                    Application = new Application(_site.Applications)
                    {
                        Name = txtAlias.Text,
                        ApplicationPoolName = txtPool.Text
                    };
                    Application.Path = string.Format("{0}/{1}", _parentPath.TrimEnd('/'), Application.Name);
                    Application.Load(Application.Path, txtPhysicalPath.Text);
                    Application.Parent.Add(Application);
                }
                else
                {
                    foreach (VirtualDirectory directory in Application.VirtualDirectories)
                    {
                        if (directory.Path == Application.Path)
                        {
                            directory.PhysicalPath = txtPhysicalPath.Text;
                        }
                    }
                }

                DialogResult = DialogResult.OK;
            }));

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

                txtPool.Text = dialog.Selected.Name;
                if (Application != null)
                {
                    Application.ApplicationPoolName = dialog.Selected.Name;
                }
            }));
        }
 public void DeleteApplication(App application, Site site)
 {
     site.Applications.Remove(application);
     _serverManager.CommitChanges();
 }
        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 ApplicationConfigurer(Application application)
 {
     _application = application;
 }
        protected void LoadChildren(Application rootApp, int rootLevel, string rootFolder, string pathToSite, ContextMenuStrip phyMenu, ContextMenuStrip vDirMenu, ContextMenuStrip appMenu)
        {
            var treeNodes = new List <TreeNode>();

            foreach (VirtualDirectory virtualDirectory in rootApp.VirtualDirectories)
            {
                var path = virtualDirectory.PathToSite();
                if (!path.StartsWith(pathToSite))
                {
                    continue;
                }

                if (GetLevel(path) != rootLevel + 1)
                {
                    continue;
                }

                // IMPORTANT: only create level+1 vDir nodes.
                var virtualDirectoryNode = new VirtualDirectoryTreeNode(ServiceProvider, virtualDirectory, ServerNode)
                {
                    ContextMenuStrip = vDirMenu
                };
                treeNodes.Add(virtualDirectoryNode);
            }

            var loaded = new HashSet <string>();

            if (Directory.Exists(rootFolder))
            {
                // IMPORTANT: only create level+1 physical nodes.
                foreach (var folder in new DirectoryInfo(rootFolder).GetDirectories())
                {
                    var path  = folder.Name;
                    var isApp = false;
                    foreach (Application app in rootApp.Site.Applications)
                    {
                        if (!app.Path.StartsWith(pathToSite))
                        {
                            continue;
                        }

                        if (app.Path != pathToSite + '/' + path)
                        {
                            continue;
                        }

                        loaded.Add(app.Path);
                        var appNode = new ApplicationTreeNode(ServiceProvider, app, ServerNode)
                        {
                            ContextMenuStrip = appMenu
                        };
                        treeNodes.Add(appNode);
                        isApp = true;
                    }

                    if (isApp)
                    {
                        continue;
                    }

                    var directory = new PhysicalDirectoryTreeNode(ServiceProvider, new PhysicalDirectory(folder, path, rootApp), ServerNode)
                    {
                        ContextMenuStrip = phyMenu
                    };
                    treeNodes.Add(directory);
                }
            }

            foreach (Application application in rootApp.Site.Applications)
            {
                if (application.IsRoot())
                {
                    continue;
                }

                if (!application.Path.StartsWith(pathToSite))
                {
                    continue;
                }

                if (loaded.Contains(application.Path))
                {
                    continue;
                }

                if (GetLevel(application.Path) != rootLevel + 1)
                {
                    continue;
                }

                // IMPORTANT: only create level+1 physical nodes.
                var appNode = new ApplicationTreeNode(ServiceProvider, application, ServerNode)
                {
                    ContextMenuStrip = appMenu
                };
                treeNodes.Add(appNode);
            }

            treeNodes.Sort(s_comparer);
            Nodes.AddRange(treeNodes.ToArray());
        }
        internal static void Deploy(Application application, string relativeFilePath, string fileContents, IFileSystem fileSystem)
        {
            if (application.VirtualDirectories.Count <= 0)
            {
                throw new Exception(string.Format("Application '{0}' does not have a virtual directory.", application.Path));
            }

            var targetFilePath = Path.Combine(application.VirtualDirectories[0].PhysicalPath, relativeFilePath);

            fileSystem.FileWrite(targetFilePath, fileContents);
        }
        public override void Expand(MainForm mainForm)
        {
            if (_loaded)
            {
                return;
            }

            _loaded = true;
            Nodes.Clear();
            var rootFolder = Application.PhysicalPath.ExpandIisExpressEnvironmentVariables(Application.GetActualExecutable());
            var rootLevel  = GetLevel(Application.Path);

            LoadChildren(Application, rootLevel, rootFolder, Application.Path, mainForm.PhysicalDirectoryMenu, mainForm.VirtualDirectoryMenu, mainForm.ApplicationMenu);
        }
        internal static void Deploy(Application application, string[] filePaths, string relativePathUnderVDir, IFileSystem fileSystem)
        {
            if (filePaths == null)
            {
                throw new ArgumentNullException("filePaths");
            }

            if (application.VirtualDirectories.Count <= 0)
            {
                throw new Exception(string.Format("Application '{0}' does not have a virtual directory.", application.Path));
            }

            var physicalPath = application.VirtualDirectories[0].PhysicalPath;
            if (!fileSystem.DirectoryExists(physicalPath))
            {
                fileSystem.DirectoryCreate(physicalPath);
            }

            var relativeDirectoryPath = Path.Combine(physicalPath, relativePathUnderVDir);
            if (!fileSystem.DirectoryExists(relativeDirectoryPath))
            {
                fileSystem.DirectoryCreate(relativeDirectoryPath);
            }

            foreach (var sourceFilePath in filePaths)
            {
                if (fileSystem.FileExists(sourceFilePath))
                {
                    var sourceFileName = Path.GetFileName(sourceFilePath) ?? sourceFilePath;
                    var destinationFileName = Path.Combine(relativeDirectoryPath, sourceFileName);
                    fileSystem.FileCopy(sourceFilePath, destinationFileName, true);
                }
            }
        }
 private string GetApplicationPhisicalPath(Application application)
 {
     return(application.VirtualDirectories[0].PhysicalPath);
 }
 internal async Task RemoveApplicationAsync(Application application)
 {
     Applications = await application.RemoveAsync();
 }