Ejemplo n.º 1
0
        private static int?FindPidForAppPool(String appPoolName)
        {
            var appPools = new Microsoft.Web.Administration.ServerManager().ApplicationPools;

            Console.WriteLine("AppPools:");
            foreach (var appPoolI in appPools)
            {
                Console.WriteLine(appPoolI.Name);
            }

            var appPool = appPools.SingleOrDefault(i => i.Name == appPoolName);

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

            var worker = appPool.WorkerProcesses.FirstOrDefault();

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

            return(worker.ProcessId);
        }
        private void UpdateMimeMappings(SPFeatureReceiverProperties properties)
        {
            try
            {
                if (webApp != null)
                {
                    SPMimeMappingCollection mappings = webApp.MimeMappings;
                    webApp.MimeMappings.Add("mp4", "Website.Video", "video/mp4");
                    webApp.MimeMappings.Add("ogg", "Website.Video", "video/ogg");
                    webApp.MimeMappings.Add("webm", "Website.Video", "video/webm");
                    webApp.MimeMappings.Add("flv", "Website.Video", "video/flv");
                    webApp.MimeMappings.Add("mpg", "Website.Video", "video/mpeg");
                    webApp.MimeMappings.Add("avi", "Website.Video", "video/x-msvideo");
                    webApp.MimeMappings.Add("mov", "Website.Video", "video/quicktime");
                    webApp.MimeMappings.Add("wmv", "Website.Video", "video/x-ms-wmv");
                    webApp.Update();
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                //ex.ToString();
            }

            try
            {
                Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager();
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 站点操作
        /// </summary>
        public static bool SetWebsite(string siteName, MethodType method)
        {
            try
            {
                var webManager = new Microsoft.Web.Administration.ServerManager();
                var site       = webManager.Sites[siteName];
                if (site == null)
                {
                    LogHelper.Info(new string[] { "Can't not find site:{0}", siteName });
                    return(false);
                }
                switch (method)
                {
                case MethodType.Start:
                    site.Start();
                    break;

                case MethodType.Stop:
                    site.Stop();
                    break;

                default:
                    break;
                }
                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return(false);
            }
        }
Ejemplo n.º 4
0
 public static IEnumerable <string> GetAll()
 {
     using (var manager = new Microsoft.Web.Administration.ServerManager())
     {
         return(manager.ApplicationPools.Select(x => x.Name));
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Beware: Web site component-dependent logic
        /// </summary>
        /// <param name="setupVariables"></param>
        /// <returns></returns>
        public static string ResolveAspNet40RegistrationToolPath_Iis7(SetupVariables setupVariables)
        {
            // By default we fallback to the corresponding tool version based on the platform bitness
            var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;

            // Choose appropriate tool version for IIS 7
            if (setupVariables.IISVersion.Major >= 7 && setupVariables.SetupAction == SetupActions.Update)
            {
                // Evaluate app pool settings on x64 platform only when update is running
                if (Environment.Is64BitOperatingSystem == true)
                {
                    // Change to x86 tool version if the component's app pool is in WOW64 mode
                    using (var srvman = new Microsoft.Web.Administration.ServerManager())
                    {
                        // Retrieve the component's app pool
                        var appPoolObj = srvman.ApplicationPools[setupVariables.WebApplicationPoolName];
                        // We are
                        if (appPoolObj == null)
                        {
                            throw new ArgumentException(String.Format("Could not find '{0}' web application pool", setupVariables.WebApplicationPoolName), "appPoolObj");
                        }
                        // Check app pool mode
                        else if (appPoolObj.Enable32BitAppOnWin64 == true)
                        {
                            util = AspNet40RegistrationToolx86;
                        }
                    }
                }
            }
            // Build path to the tool
            return(Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util));
        }
Ejemplo n.º 6
0
 public static IEnumerable<string> GetAll()
 {
     using (var manager = new Microsoft.Web.Administration.ServerManager())
     {
         return manager.ApplicationPools.Select(x => x.Name);
     }
 }
Ejemplo n.º 7
0
 public static void Delete(string applicationPool)
 {
     using(var manager = new Microsoft.Web.Administration.ServerManager())
     {
         manager.ApplicationPools.Single(x => x.Name.ToLower() == applicationPool.ToLower()).Delete();
         manager.CommitChanges();
     }
 }
Ejemplo n.º 8
0
 public static void Delete(string applicationPool)
 {
     using (var manager = new Microsoft.Web.Administration.ServerManager())
     {
         manager.ApplicationPools.Single(x => x.Name.ToLower() == applicationPool.ToLower()).Delete();
         manager.CommitChanges();
     }
 }
        public static void RecycleAppPool(string appPoolName)
        {
            using (Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager())
            {
                var pool = serverManager.ApplicationPools[appPoolName];

                pool.Recycle();
            }
        }
        private void OnWorkerProcessFillItems(object sender, EventArgs e)
        {
            var args = e as OleMenuCmdEventArgs;

            using (var serverManager = new Microsoft.Web.Administration.ServerManager())
            {
                var workerProcesses = serverManager.WorkerProcesses.Select(wp => wp.AppPoolName).OrderBy(pname => pname).ToArray();
                Marshal.GetNativeVariantForObject(workerProcesses, args.OutValue);
            }
        }
Ejemplo n.º 11
0
        public IEnumerable <Site> Index([FromUri] List <string> filter = null)
        {
            var sitesFound = new Microsoft.Web.Administration.ServerManager()
                             .Sites
                             .Where(x => filter.Count == 0 || filter.Any(y => x.Name.Contains(y)))
                             .ToList();

            for (int i = 0; i < sitesFound.Count(); i++)
            {
                yield return(ParseSite(sitesFound[i]));
            }
        }
        private void PublishBackendServiceProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                backendServiceParams = "-f netcoreapp3.0 -c Release -o \"C:\\For Waleed\\DeploymentArea\\BisiparişArkaUçİşlemlerHizmet\""
                                       + " \"C:\\Users\\pc\\Source\\Repos\\Bisipariş V 1_0Alpha04\\2 Altyapı\\Hizmetler\\ArkaUçİşlemlerHizmet\\ArkaUçİşlemlerHizmet.csproj\"";
                using (var prs = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/k dotnet publish {backendServiceParams}",
                        UseShellExecute = true,
                        CreateNoWindow = true,
                        WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
                    }
                })
                {
                    Dispatcher.Invoke(() =>
                    {
                        bkEndPrjLabel.Foreground = Brushes.Orange; bkEndPrjLabel.Content = "Publishing...";
                        bkEndPrjLabel.Visibility = Visibility.Visible;
                    });

                    using (var iisSrvr = new Microsoft.Web.Administration.ServerManager())
                    {
                        //DisplayMessage("Stopping IIS site...");

                        iisSrvr.Sites["BisiparişArkaUçİşlemlerHizmet"].Stop();

                        //DisplayMessage("Starting process...");

                        prs.Start();

                        do
                        {
                        } while (!prs.HasExited);

                        iisSrvr.Sites["BisiparişArkaUçİşlemlerHizmet"].Start();
                    }

                    Dispatcher.Invoke(() =>
                    {
                        bkEndPrjLabel.Foreground = Brushes.Green; bkEndPrjLabel.Content = "Done";
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 13
0
        private void ConfigurationEditorForm_Load(object sender, EventArgs e)
        {

            if (_configuration.ForPublication)
            {
                okToolStripButton.Text = "Close";
                cancelToolStripButton.Visible = false;
                bool serverOk = false;
                try
                {
                    Microsoft.Web.Administration.ServerManager serverMgr = null;
                    serverMgr = new Microsoft.Web.Administration.ServerManager();
                    serverOk = true;
                }
                catch { }
                if (serverOk)
                {
                    infoTextBox.Text = string.Format(@"This simple helper allows to publish the Web Server application on your Internet Information Server version 7 or 8.
It creates an application under the 'Default Web Site' of IIS using the 'LocalSystem' Windows Account.

IIS must be installed with the following features: 
IIS version 7: Application Development/ASP.Net
IIS version 8: Application Development/ASP.Net 3.5, Application Development/ASP.Net 4.5
MVC 4 extension

The site can be configured with any user having the following rights:
Read access to the repository directory ({0}).
Rights to connect to the databases defined in the Data Sources.
Read/Write access to the temp sub-folder created in the published directory ({1}).

Note that publishing will stop the current Web Server instance.
", _configuration.Repository.RepositoryPath, Path.Combine(_configuration.WebPublicationDirectory, "temp"));
                }
                else
                {
                    infoTextBox.Text = @"No Internet Information Server detected on this machine.
Please install IIS with the following features: 
IIS version 7: Application Development/ASP.Net
IIS version 8: Application Development/ASP.Net 3.5, Application Development/ASP.Net 4.5
MVC 4 extension
";
                }
            }
            else
            {
                infoTextBox.Text = @"This editor allows to configure your Seal Server parameters.

New parameter values may require a restart of the Report Designer or the Web Server.";
            }
            Visible = true;
        }
Ejemplo n.º 14
0
 public static bool IsIisInstalled()
 {
     using(var manager = new Microsoft.Web.Administration.ServerManager()) {
         try
         {
             var test = manager.Sites.First();
             return true;
         }
         catch (COMException)
         {
             return false;
         }
     }
 }
        private void ConfigurationEditorForm_Load(object sender, EventArgs e)
        {
            if (_configuration.ForPublication)
            {
                okToolStripButton.Text        = "Close";
                cancelToolStripButton.Visible = false;
                bool serverOk = false;
                try
                {
                    Microsoft.Web.Administration.ServerManager serverMgr = null;
                    serverMgr = new Microsoft.Web.Administration.ServerManager();
                    serverOk  = true;
                }
                catch { }
                if (serverOk)
                {
                    infoTextBox.Text = string.Format(@"This simple helper allows to publish the Web Server application on your Internet Information Server version 7 or 8.
It creates an application under the 'Default Web Site' of IIS using the 'LocalSystem' Windows Account.

IIS must be installed with the following features: 
IIS version 7: Application Development/ASP.Net
IIS version 8: Application Development/ASP.Net 3.5, Application Development/ASP.Net 4.5
MVC 4 extension

The site can be configured with any user having the following rights:
Read access to the repository directory ({0}).
Rights to connect to the databases defined in the Data Sources.
Read/Write access to the temp sub-folder created in the published directory ({1}).

Note that publishing will stop the current Web Server instance.
", _configuration.Repository.RepositoryPath, Path.Combine(_configuration.WebPublicationDirectory, "temp"));
                }
                else
                {
                    infoTextBox.Text = @"No Internet Information Server detected on this machine.
Please install IIS with the following features: 
IIS version 7: Application Development/ASP.Net
IIS version 8: Application Development/ASP.Net 3.5, Application Development/ASP.Net 4.5
MVC 4 extension
";
                }
            }
            else
            {
                infoTextBox.Text = @"This editor allows to configure your server parameters.

New parameter values may require a restart of the Report Designer or the Web Server.";
            }
            Visible = true;
        }
Ejemplo n.º 16
0
        public static void RestartWebSite(string websiteName)
        {
            var webManager = new Microsoft.Web.Administration.ServerManager();
            var startSite  = webManager.Sites[websiteName];

            if (startSite == null)
            {
                throw new Exception(string.Format("Can't not find site:{0}", websiteName));
            }

            startSite.Stop();
            Thread.Sleep(500);
            startSite.Start();
        }
Ejemplo n.º 17
0
 public static bool IsIisInstalled()
 {
     using (var manager = new Microsoft.Web.Administration.ServerManager()) {
         try
         {
             var test = manager.Sites.First();
             return(true);
         }
         catch (COMException)
         {
             return(false);
         }
     }
 }
Ejemplo n.º 18
0
        public static IEnumerable <string> GetUnusedApplicationPools()
        {
            using (var manager = new Microsoft.Web.Administration.ServerManager())
            {
                IEnumerable <string> appPoolsInUse = manager.Sites.Select(x => x.Applications.First().ApplicationPoolName).ToList();

                foreach (var appPool in manager.ApplicationPools)
                {
                    if (!appPoolsInUse.Contains(appPool.Name))
                    {
                        yield return(appPool.Name);
                    }
                }
            }
        }
    static void Main(string[] args)
    {
        string serverName = "localhost";

        using (Microsoft.Web.Administration.ServerManager sm = Microsoft.Web.Administration.ServerManager.OpenRemote(serverName))
        {
            int counter = 1;
            foreach (var site in sm.Sites)
            {
                Console.Write(String.Format(CultureInfo.InvariantCulture, "Site number {0} : {1}{2}", counter.ToString(), site.Name, Environment.NewLine));
                counter++;
            }
        }
        Console.ReadLine();
    }
Ejemplo n.º 20
0
 public Models.ResponseMessage.ResponseMessage CreateApplication(Application app)
 {
     Microsoft.Web.Administration.ServerManager iisWeb = new Microsoft.Web.Administration.ServerManager();
     iisWeb.Sites.Add(app.appName, "http", "*:80", app.appFolder);
     iisWeb.CommitChanges();
     Microsoft.Web.Administration.Site site = iisWeb.Sites[app.appName];
     site.Stop();
     site.ApplicationDefaults.ApplicationPoolName = pool;
     site.Start();
     iisWeb.CommitChanges();
     Models.ResponseMessage.ResponseMessage rm = new ResponseMessage.ResponseMessage();
     rm.type    = "success";
     rm.message = "Anwendung erfolgreich erstellt";
     return(rm);
 }
Ejemplo n.º 21
0
        public static IEnumerable<string> GetUnusedApplicationPools()
        {
            using(var manager = new Microsoft.Web.Administration.ServerManager())
             {
                 IEnumerable<string> appPoolsInUse = manager.Sites.Select(x => x.Applications.First().ApplicationPoolName).ToList();

                 foreach(var appPool in manager.ApplicationPools)
                 {
                     if (!appPoolsInUse.Contains(appPool.Name))
                     {
                         yield return appPool.Name;
                     }
                 }
             }
        }
Ejemplo n.º 22
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var appPath      = Application.StartupPath;
                var serverName   = cmbSqlInstances.SelectedItem.ToString();
                var userName     = txtUserName.Text;
                var password     = txtPassword.Text;
                var databaseName = txtDatabaseName.Text;

                var           bakFilePath = appPath + "\\db.bak";
                string        sql         = $@"RESTORE DATABASE {databaseName} FROM DISK = '{bakFilePath}'
                    WITH FILE = 1,
                    MOVE 'AdventureWorks2014_Data' 
	                TO '{appPath}\{databaseName}.mdf', 
                    MOVE 'AdventureWorks2014_Log' 
	                TO '{appPath}\{databaseName}.ldf';"    ;
                SqlConnection con         = new SqlConnection($@"Server={serverName};Database=master;User Id={userName};
Password={password};Integrated Security=True");
                SqlCommand    command     = new SqlCommand(sql, con);
                con.Open();
                command.ExecuteNonQuery();
                MessageBox.Show("Veri Tabanı Yüklendi. Tamama tıkladığınızda web sitesi açılacaktır.");
                con.Close();
                con.Dispose();

                Microsoft.Web.Administration.ServerManager iisManager = new Microsoft.Web.Administration.ServerManager();
                var check = iisManager.Sites.Any(x => x.Name == "TestSite");
                if (!check)
                {
                    iisManager.Sites.Add("TestSite", "http", "*:4545:", appPath + "\\Publish");
                    iisManager.CommitChanges();
                }

                Configuration            config = OpenConfigFile(appPath + "/Publish/web.config");
                ConnectionStringsSection sec    = (ConnectionStringsSection)config.GetSection("connectionStrings");
                sec.ConnectionStrings["Context"].ConnectionString = $@"metadata=res://*/Models.AdventureWorksModel.csdl|res://*/Models.AdventureWorksModel.ssdl|res://*/Models.AdventureWorksModel.msl;provider=System.Data.SqlClient;provider connection string=" + HttpUtility.HtmlDecode("&quot;") + $"data source={serverName};initial catalog={databaseName};persist security info=True;user id={userName};password={password};MultipleActiveResultSets=True;App=EntityFramework" + HttpUtility.HtmlDecode("&quot;") + ";";
                config.Save();

                ProcessStartInfo sInfo = new ProcessStartInfo("http://localhost:4545");
                Process.Start(sInfo);
                Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 23
0
        void configureClick(object sender, EventArgs e)
        {
            _repository.Configuration.ForPublication = (sender == publishWebMenuItem);
            if (_repository.Configuration.ForPublication && string.IsNullOrEmpty(_repository.Configuration.WebPublicationDirectory))
            {
                try
                {
                    Microsoft.Web.Administration.ServerManager serverMgr = new Microsoft.Web.Administration.ServerManager();
                    //try to get default directory...
                    _repository.Configuration.WebPublicationDirectory = Path.Combine(serverMgr.Sites[0].Applications[0].VirtualDirectories[0].PhysicalPath.Replace("%SystemDrive%\\", Path.GetPathRoot(Environment.SystemDirectory)), _repository.Configuration.WebApplicationName);
                }
                catch { }
            }

            if (!_adminWarningDone && !Helper.IsMachineAdministrator())
            {
                if (MessageBox.Show("We recommend to execute the 'Server Manager' application with the option 'Run as administrator' to publish the Web Server application...\r\nDo you want to continue ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                {
                    _adminWarningDone = true;
                    return;
                }
            }

            if (_repository.Configuration.ForPublication)
            {
                if (!Helper.CheckWebServerOS())
                {
                    return;
                }
            }

            var frm = new ConfigurationEditorForm(_repository.Configuration);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(_repository.Configuration.FilePath))
                {
                    _repository.Configuration.FilePath = _repository.ConfigurationPath;
                }
                _repository.Configuration.SaveToFile();
            }
            else
            {
                //reload configuration
                _repository.ReloadConfiguration();
            }
        }
        private void OnWorkerProcessSelection(object sender, EventArgs e)
        {
            var args = e as OleMenuCmdEventArgs;

            if (args.InValue != null)
            {
                var selectedProcess = args.InValue.ToString();
                using (var serverManager = new Microsoft.Web.Administration.ServerManager())
                {
                    var workerProcess = serverManager.WorkerProcesses.FirstOrDefault(wp => wp.AppPoolName == selectedProcess);
                    if (workerProcess != null)
                    {
                        var dte2    = (EnvDTE80.DTE2)Package.GetGlobalService(typeof(SDTE));
                        var process = dte2.Debugger.LocalProcesses.Cast <EnvDTE.Process>().FirstOrDefault(p => p.ProcessID == workerProcess.ProcessId);
                        if (process != null)
                        {
                            process.Attach();
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private static bool UpdateWifSettings()
        {
            using (var server = new Microsoft.Web.Administration.ServerManager())
            {
                var siteNameFromServiceModel = "Web";
                var siteName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);

                var configFilePath = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\Web.config", server.Sites[siteName].Applications[0].VirtualDirectories[0].PhysicalPath);
                var xml = System.Xml.Linq.XElement.Load(configFilePath);
                var identityModelService = xml.Element("microsoft.identityModel").Element("service");

                if (UpdateAttributeWithRoleSetting(identityModelService.Element("audienceUris").Element("add").Attribute("value"), "realm") &&
                    UpdateAttributeWithRoleSetting(identityModelService.Element("issuerTokenResolver").Element("serviceKeys").Element("add").Attribute("serviceName"), "realm") &&
                    UpdateAttributeWithRoleSetting(identityModelService.Element("issuerTokenResolver").Element("serviceKeys").Element("add").Attribute("serviceKey"), "serviceKey") &&
                    UpdateAttributeWithRoleSetting(identityModelService.Element("issuerNameRegistry").Element("trustedIssuers").Element("add").Attribute("issuerIdentifier"), "trustedIssuersIdentifier") &&
                    UpdateAttributeWithRoleSetting(identityModelService.Element("issuerNameRegistry").Element("trustedIssuers").Element("add").Attribute("name"), "trustedIssuerName"))
                {
                    xml.Save(configFilePath);
                    return true;
                }

                return false;
            }
        }
        public static List<AppData> GetWebsitesHavingWcf()
        {
            List<AppData> appDataList = new List<AppData>();
            Microsoft.Web.Administration.ServerManager manager = new Microsoft.Web.Administration.ServerManager();

            try
            {
                foreach (var site in manager.Sites)
                {
                    foreach (var application in site.Applications)
                    {
                        foreach (var vd in application.VirtualDirectories)
                        {
                            string configPath = vd.PhysicalPath + @"\web.config";
                            if (System.IO.File.Exists(configPath))
                            {
                                XElement doc = XElement.Load(configPath);
                                var serviceModelNode = doc.Descendants("system.serviceModel");
                                if (serviceModelNode.Count() > 0)
                                {
                                    AppData pd = new AppData(application.ToString(), vd.PhysicalPath, "web.config");
                                    appDataList.Add(pd);
                                }
                            }

                        }
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return appDataList;
        }
        private static void RemoveWebSite(string siteName)
        {
            using (var serverManager = new Microsoft.Web.Administration.ServerManager())
            {
                var testSite = serverManager.Sites.SingleOrDefault(s => s.Name == siteName);
                if (testSite != null)
                {
                    serverManager.Sites.Remove(testSite);
                    serverManager.CommitChanges();
                }

                var testAppPool = serverManager.ApplicationPools.SingleOrDefault(s => s.Name == siteName);
                if (testAppPool != null)
                {
                    serverManager.ApplicationPools.Remove(testAppPool);
                    serverManager.CommitChanges();
                }
            }
        }
 private static IEnumerable<Microsoft.Web.Administration.Site> RetrieveWebSites()
 {
     using (var serverManager = new Microsoft.Web.Administration.ServerManager())
     {
         return serverManager.Sites.Where(s => s.Name != "Default Web Site").ToList();
     }
 }
Ejemplo n.º 29
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir  = Context.Parameters[Arguments.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);
            System.Configuration.Configuration        config  = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll")));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.BaseDir]))
            {
                section.DEA.BaseDir = Context.Parameters[Arguments.BaseDir];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.EnforceUlimit]))
            {
                section.DEA.EnforceUsageLimit = Convert.ToBoolean(Context.Parameters[Arguments.EnforceUlimit], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.FilerPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.FilerPort], CultureInfo.InvariantCulture);
                section.DEA.FilerPort = port;
                FirewallTools.OpenPort(port, "DEA FileServer");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.StatusPort], CultureInfo.InvariantCulture);
                section.DEA.StatusPort = port;
                FirewallTools.OpenPort(port, "DEA Status");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.HeartBeatInterval]))
            {
                section.DEA.HeartbeatIntervalMs = Convert.ToInt32(Context.Parameters[Arguments.HeartBeatInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.LocalRoute]))
            {
                section.DEA.LocalRoute = Context.Parameters[Arguments.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.DEA.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MaxMemory]))
            {
                section.DEA.MaxMemoryMB = Convert.ToInt32(Context.Parameters[Arguments.MaxMemory], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MessageBus]))
            {
                section.DEA.MessageBus = Context.Parameters[Arguments.MessageBus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MultiTenant]))
            {
                section.DEA.Multitenant = Convert.ToBoolean(Context.Parameters[Arguments.MultiTenant], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.Secure]))
            {
                section.DEA.Secure = Convert.ToBoolean(Context.Parameters[Arguments.Secure], CultureInfo.InvariantCulture);
            }

            section.Service = null;
            config.Save();

            using (Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager())
            {
                Microsoft.Web.Administration.Configuration authenticationConfig = serverManager.GetApplicationHostConfiguration();

                Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = authenticationConfig.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                anonymousAuthenticationSection["enabled"]     = true;
                anonymousAuthenticationSection["userName"]    = string.Empty;
                anonymousAuthenticationSection["password"]    = string.Empty;
                anonymousAuthenticationSection["logonMethod"] = @"ClearText";

                serverManager.CommitChanges();
            }

            Registry.LocalMachine.CreateSubKey(@"System\CurrentControlSet\Services\Inetinfo\Parameters").SetValue("DoDirMonitoringForUNC", 1, RegistryValueKind.DWord);
        }
Ejemplo n.º 30
0
		/// <summary>
		/// Beware: Web site component-dependent logic
		/// </summary>
		/// <param name="setupVariables"></param>
		/// <returns></returns>
		public static string ResolveAspNet40RegistrationToolPath_Iis7(SetupVariables setupVariables)
		{
			// By default we fallback to the corresponding tool version based on the platform bitness
			var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;
			// Choose appropriate tool version for IIS 7
			if (setupVariables.IISVersion.Major == 7 && setupVariables.SetupAction == SetupActions.Update)
			{
				// Evaluate app pool settings on x64 platform only when update is running
				if (Environment.Is64BitOperatingSystem == true)
				{
					// Change to x86 tool version if the component's app pool is in WOW64 mode
					using (var srvman = new Microsoft.Web.Administration.ServerManager())
					{
						// Retrieve the component's app pool
						var appPoolObj = srvman.ApplicationPools[setupVariables.WebApplicationPoolName];
						// We are 
						if (appPoolObj == null)
						{
							throw new ArgumentException(String.Format("Could not find '{0}' web application pool", setupVariables.WebApplicationPoolName), "appPoolObj");
						}
						// Check app pool mode
						else if (appPoolObj.Enable32BitAppOnWin64 == true)
						{
							util = AspNet40RegistrationToolx86;
						}
					}
				}
			}
			// Build path to the tool
			return Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util);
		}
Ejemplo n.º 31
0
        void publish(ExecutionLogInterface log, bool filesOnly)
        {
            log.Log("Starting Web Site Publishing...");
            _publicationInError = false;
            try
            {
                string publicationDirectory = _configuration.WebPublicationDirectory;
                string sourceDirectory      = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), _configuration.WebNETCore ? "NETCore" : "Web.Net");
#if DEBUG
                sourceDirectory = Path.GetDirectoryName(Application.ExecutablePath) + @"\..\..\..\..\SealWebServer\";
                if (_configuration.WebNETCore)
                {
                    sourceDirectory = Path.GetDirectoryName(Application.ExecutablePath) + @"\..\..\..\..\..\Projects.NETCore\SealWebServer\bin\Release\netcoreapp3.1\publish\";
                }
#endif

                //Copy installation directory
                log.Log("Copying files from '{0}' to '{1}'", sourceDirectory, publicationDirectory);
                FileHelper.CopyDirectory(sourceDirectory, publicationDirectory, true);

                //Check config...
                var currentConfig = Path.Combine(publicationDirectory, _configuration.WebNETCore ? "appsettings.json" : "web.config");
                var releaseConfig = Path.Combine(publicationDirectory, _configuration.WebNETCore ? "appsettings.Release.json" : "web.release.config");
                if (!File.Exists(currentConfig) && File.Exists(releaseConfig))
                {
                    log.Log("Creating Config file from '{0}'", releaseConfig);
                    //Replace repository path
                    var configText = File.ReadAllText(releaseConfig);
                    if (_configuration.WebNETCore)
                    {
                        configText = configText.Replace("\"RepositoryPath\": \"\",", string.Format("\"RepositoryPath\": \"{0}\",", _configuration.Repository.RepositoryPath.Replace("\\", "\\\\")));
                    }
                    else
                    {
                        configText = configText.Replace(@"C:\ProgramData\Seal Report Repository", _configuration.Repository.RepositoryPath);
                    }
                    File.WriteAllText(currentConfig, configText);
                }

                if (!filesOnly && !log.IsJobCancelled())
                {
                    log.Log("Publishing Site on IIS...");

                    Microsoft.Web.Administration.ServerManager serverMgr = new Microsoft.Web.Administration.ServerManager();
                    Microsoft.Web.Administration.Site          site      = null;
                    if (serverMgr.Sites.Count == 0)
                    {
                        log.Log("Creating Default Web Site");
                        site = serverMgr.Sites.Add("Default Web Site", "C:\\inetpub\\wwwroot", 80);
                    }
                    else
                    {
                        site = serverMgr.Sites[0];
                    }

                    Microsoft.Web.Administration.ApplicationPool pool = serverMgr.ApplicationPools.FirstOrDefault(i => i.Name == _configuration.WebApplicationPoolName);
                    if (pool == null)
                    {
                        log.Log("Creating Application Pool");
                        pool = serverMgr.ApplicationPools.Add(_configuration.WebApplicationPoolName);
                    }
                    pool.ManagedRuntimeVersion = _configuration.WebNETCore ?  "" : "v4.0";
                    if (Marshal.SizeOf(typeof(IntPtr)) != 8)
                    {
                        pool.Enable32BitAppOnWin64 = true;                                      //Test if 32bit
                    }
                    pool.ProcessModel.IdentityType = Microsoft.Web.Administration.ProcessModelIdentityType.LocalSystem;

                    if (string.IsNullOrEmpty(_configuration.WebApplicationName))
                    {
                        _configuration.WebApplicationName = "/";
                    }
                    var application = site.Applications.FirstOrDefault(i => i.Path == _configuration.WebApplicationName);
                    if (application == null)
                    {
                        log.Log("Creating Application");
                        application = site.Applications.Add(_configuration.WebApplicationName, _configuration.WebPublicationDirectory);
                    }
                    if (_configuration.WebApplicationName == "/")
                    {
                        Microsoft.Web.Administration.VirtualDirectory vDir = application.VirtualDirectories[0];
                        vDir.Path         = _configuration.WebApplicationName;
                        vDir.PhysicalPath = _configuration.WebPublicationDirectory;
                    }
                    application.ApplicationPoolName = _configuration.WebApplicationPoolName;
                    if (!log.IsJobCancelled())
                    {
                        serverMgr.CommitChanges();
                    }
                    log.Log("Web Site has been published successfully.");
                }
            }
            catch (Exception ex)
            {
                _publicationInError = true;
                log.Log("\r\n[UNEXPECTED ERROR RECEIVED]\r\n{0}\r\n", ex.Message);
                if (ex.InnerException != null)
                {
                    log.Log("{0}\r\n", ex.InnerException.Message);
                }
            }
            log.Log("Web Site Publishing terminated.");
            if (log.IsJobCancelled())
            {
                log.Log("Publication has been cancelled.");
            }
        }
Ejemplo n.º 32
0
        void publish(ExecutionLogInterface log, bool filesOnly)
        {
            log.Log("Starting Web Site Publishing...");
            _publicationInError = false;
            try
            {
                string publicationDirectory = _configuration.WebPublicationDirectory;
                string sourceDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Web");
            #if DEBUG
                sourceDirectory = Path.GetDirectoryName(Application.ExecutablePath) + @"\..\..\..\SealWebServer\";
            #endif

                //Copy installation directory
                log.Log("Copying files from '{0}' to '{1}'", sourceDirectory, publicationDirectory);
                FileHelper.CopyDirectory(sourceDirectory, publicationDirectory, true);

                //Check web config...
                if (!File.Exists(Path.Combine(publicationDirectory, "web.config")) && File.Exists(Path.Combine(publicationDirectory, "web.release.config")))
                {
                    log.Log("Creating web.config file");
                    File.Copy(Path.Combine(publicationDirectory, "web.release.config"), Path.Combine(publicationDirectory, "web.config"));
                }

                if (!filesOnly && !log.IsJobCancelled())
                {
                    log.Log("Publishing Site on IIS...");

                    Microsoft.Web.Administration.ServerManager serverMgr = new Microsoft.Web.Administration.ServerManager();
                    Microsoft.Web.Administration.Site site = null;
                    if (serverMgr.Sites.Count == 0)
                    {
                        log.Log("Creating Default Web Site");
                        site = serverMgr.Sites.Add("Default Web Site", "C:\\inetpub\\wwwroot", 80);
                    }
                    else site = serverMgr.Sites[0];

                    Microsoft.Web.Administration.ApplicationPool pool = serverMgr.ApplicationPools.FirstOrDefault(i => i.Name == _configuration.WebApplicationPoolName);
                    if (pool == null)
                    {
                        log.Log("Creating Application Pool");
                        pool = serverMgr.ApplicationPools.Add(_configuration.WebApplicationPoolName);
                    }
                    pool.ManagedRuntimeVersion = "v4.0";
                    pool.Enable32BitAppOnWin64 = true;
                    pool.ProcessModel.IdentityType = Microsoft.Web.Administration.ProcessModelIdentityType.LocalSystem;

                    Microsoft.Web.Administration.Application application = site.Applications.FirstOrDefault(i => i.Path == _configuration.WebApplicationName);
                    if (application == null)
                    {
                        log.Log("Creating Application");
                        application = site.Applications.Add(_configuration.WebApplicationName, _configuration.WebPublicationDirectory);
                    }
                    application.ApplicationPoolName = _configuration.WebApplicationPoolName;
                    if (!log.IsJobCancelled())
                    {
                        serverMgr.CommitChanges();
                    }
                    log.Log("Web Site has been published successfully.");
                }
            }
            catch (Exception ex)
            {
                _publicationInError = true;
                log.Log("\r\n[UNEXPECTED ERROR RECEIVED]\r\n{0}\r\n", ex.Message);
                if (ex.InnerException != null) log.Log("{0}\r\n", ex.InnerException.Message);
            }
            log.Log("Web Site Publishing terminated.");
            if (log.IsJobCancelled()) log.Log("Publication has been cancelled.");
        }
Ejemplo n.º 33
0
        void configureClick(object sender, EventArgs e)
        {
            _repository.Configuration.ForPublication = (sender == publishWebMenuItem);
            if (_repository.Configuration.ForPublication && string.IsNullOrEmpty(_repository.Configuration.WebPublicationDirectory))
            {

                try
                {
                    Microsoft.Web.Administration.ServerManager serverMgr = new Microsoft.Web.Administration.ServerManager();
                    //try to get default directory...
                    _repository.Configuration.WebPublicationDirectory = Path.Combine(serverMgr.Sites[0].Applications[0].VirtualDirectories[0].PhysicalPath.Replace("%SystemDrive%\\", Path.GetPathRoot(Environment.SystemDirectory)), _repository.Configuration.WebApplicationName);
                }
                catch { }
            }

            if (!_adminWarningDone && !Helper.IsMachineAdministrator())
            {
                if (MessageBox.Show("We recommend to execute the 'Server Manager' application with the option 'Run as administrator' to publish the Web Server application...\r\nDo you want to continue ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                {
                    _adminWarningDone = true;
                    return;
                }
            }

            if (_repository.Configuration.ForPublication)
            {
                if (!Helper.CheckWebServerOS()) return;
            }

            var frm = new ConfigurationEditorForm(_repository.Configuration);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(_repository.Configuration.FilePath)) _repository.Configuration.FilePath = _repository.ConfigurationPath;
                _repository.Configuration.SaveToFile();
            }
        }
 private static Microsoft.Web.Administration.Site RetrieveWebSite(string siteName)
 {
     using (var serverManager = new Microsoft.Web.Administration.ServerManager())
     {
         return serverManager.Sites.SingleOrDefault(s => s.Name == siteName);
     }
 }
Ejemplo n.º 35
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir = Context.Parameters[Arguments.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll"));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");
            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.BaseDir]))
            {
                section.DEA.BaseDir = Context.Parameters[Arguments.BaseDir];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.EnforceUlimit]))
            {
                section.DEA.EnforceUsageLimit = Convert.ToBoolean(Context.Parameters[Arguments.EnforceUlimit], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.FilerPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.FilerPort], CultureInfo.InvariantCulture);
                section.DEA.FilerPort = port;
                FirewallTools.OpenPort(port, "DEA FileServer");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.StatusPort], CultureInfo.InvariantCulture);
                section.DEA.StatusPort = port;
                FirewallTools.OpenPort(port, "DEA Status");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.HeartBeatInterval]))
            {
                section.DEA.HeartbeatIntervalMs = Convert.ToInt32(Context.Parameters[Arguments.HeartBeatInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.LocalRoute]))
            {
                section.DEA.LocalRoute = Context.Parameters[Arguments.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.DEA.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MaxMemory]))
            {
                section.DEA.MaxMemoryMB = Convert.ToInt32(Context.Parameters[Arguments.MaxMemory], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MessageBus]))
            {
                section.DEA.MessageBus = Context.Parameters[Arguments.MessageBus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MultiTenant]))
            {
                section.DEA.Multitenant = Convert.ToBoolean(Context.Parameters[Arguments.MultiTenant], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.Secure]))
            {
                section.DEA.Secure = Convert.ToBoolean(Context.Parameters[Arguments.Secure], CultureInfo.InvariantCulture);
            }

            section.Service = null;
            config.Save();

            using (Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager())
            {
                Microsoft.Web.Administration.Configuration authenticationConfig = serverManager.GetApplicationHostConfiguration();

                Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = authenticationConfig.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                anonymousAuthenticationSection["enabled"] = true;
                anonymousAuthenticationSection["userName"] = string.Empty;
                anonymousAuthenticationSection["password"] = string.Empty;
                anonymousAuthenticationSection["logonMethod"] = @"ClearText";

                serverManager.CommitChanges();
            }

            Registry.LocalMachine.CreateSubKey(@"System\CurrentControlSet\Services\Inetinfo\Parameters").SetValue("DoDirMonitoringForUNC", 1, RegistryValueKind.DWord);
        }
Ejemplo n.º 36
0
        void publish(ExecutionLogInterface log, bool filesOnly)
        {
            log.Log("Starting Web Site Publishing...");
            _publicationInError = false;
            try
            {
                string publicationDirectory = _configuration.WebPublicationDirectory;
                string sourceDirectory      = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Web");
#if DEBUG
                sourceDirectory = Path.GetDirectoryName(Application.ExecutablePath) + @"\..\..\..\SealWebServer\";
#endif

                //Copy installation directory
                log.Log("Copying files from '{0}' to '{1}'", sourceDirectory, publicationDirectory);
                FileHelper.CopyDirectory(sourceDirectory, publicationDirectory, true);

                //Copy license files if any
                foreach (var path in Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath), "*.slc"))
                {
                    File.Copy(path, Path.Combine(Path.Combine(publicationDirectory, "bin"), Path.GetFileName(path)), true);
                }

                //Check web config...
                if (!filesOnly || (!File.Exists(Path.Combine(publicationDirectory, "web.config")) && File.Exists(Path.Combine(publicationDirectory, "web.release.config"))))
                {
                    log.Log("Creating web.config file");
                    File.Copy(Path.Combine(publicationDirectory, "web.release.config"), Path.Combine(publicationDirectory, "web.config"), true);
                }

                if (!filesOnly && !log.IsJobCancelled())
                {
                    log.Log("Publishing Site on IIS...");

                    Microsoft.Web.Administration.ServerManager serverMgr = new Microsoft.Web.Administration.ServerManager();
                    Microsoft.Web.Administration.Site          site      = null;
                    if (serverMgr.Sites.Count == 0)
                    {
                        log.Log("Creating Default Web Site");
                        site = serverMgr.Sites.Add("Default Web Site", "C:\\inetpub\\wwwroot", 80);
                    }
                    else
                    {
                        site = serverMgr.Sites[0];
                    }

                    Microsoft.Web.Administration.ApplicationPool pool = serverMgr.ApplicationPools.FirstOrDefault(i => i.Name == _configuration.WebApplicationPoolName);
                    if (pool == null)
                    {
                        log.Log("Creating Application Pool");
                        pool = serverMgr.ApplicationPools.Add(_configuration.WebApplicationPoolName);
                    }
                    pool.ManagedRuntimeVersion = "v4.0";
                    if (Marshal.SizeOf(typeof(IntPtr)) != 8)
                    {
                        pool.Enable32BitAppOnWin64 = true;                                      //Test if 32bit
                    }
                    pool.ProcessModel.IdentityType = Microsoft.Web.Administration.ProcessModelIdentityType.LocalSystem;

                    if (string.IsNullOrEmpty(_configuration.WebApplicationName))
                    {
                        _configuration.WebApplicationName = "/";
                    }
                    var application = site.Applications.FirstOrDefault(i => i.Path == _configuration.WebApplicationName);
                    if (application == null)
                    {
                        log.Log("Creating Application");
                        application = site.Applications.Add(_configuration.WebApplicationName, _configuration.WebPublicationDirectory);
                    }
                    if (_configuration.WebApplicationName == "/")
                    {
                        Microsoft.Web.Administration.VirtualDirectory vDir = application.VirtualDirectories[0];
                        vDir.Path         = _configuration.WebApplicationName;
                        vDir.PhysicalPath = _configuration.WebPublicationDirectory;
                    }
                    application.ApplicationPoolName = _configuration.WebApplicationPoolName;
                    if (!log.IsJobCancelled())
                    {
                        serverMgr.CommitChanges();
                    }
                    log.Log("Web Site has been published successfully.");
                }
            }
            catch (Exception ex)
            {
                _publicationInError = true;
                log.Log("\r\n[UNEXPECTED ERROR RECEIVED]\r\n{0}\r\n", ex.Message);
                if (ex.InnerException != null)
                {
                    log.Log("{0}\r\n", ex.InnerException.Message);
                }
            }
            log.Log("Web Site Publishing terminated.");
            if (log.IsJobCancelled())
            {
                log.Log("Publication has been cancelled.");
            }
        }
Ejemplo n.º 37
0
        private static bool DeployToIISWebsite(string sourcePackagesFolder, string websiteName)
        {
            // Get the physical website install dir and url.

            // string siteName = "Default Web Site";

            var serverManager = new Microsoft.Web.Administration.ServerManager();
            var site = serverManager.Sites.FirstOrDefault(w => w.Name.ToLower() == websiteName.ToLower());
            if (site == null)
            {
                throw new ArgumentOutOfRangeException("Could not find IIS website named: " + websiteName);
            }

            var defaultBinding = site.Bindings.FirstOrDefault();
            if (defaultBinding == null)
            {
                throw new ArgumentOutOfRangeException("The IIS website named: " + websiteName + " does not appear to have any Bindings. Please set up a binding for it.");
            }

            int port = 80;
            string protocol = "http";
            string host = "localhost";
            if (defaultBinding.EndPoint != null)
            {
                port = defaultBinding.EndPoint.Port;
            }
            if (!string.IsNullOrEmpty(defaultBinding.Protocol))
            {
                protocol = defaultBinding.Protocol;
            }
            if (!string.IsNullOrEmpty(defaultBinding.Host))
            {
                host = defaultBinding.Host;
            }

            string websiteUrl = string.Format("{0}://{1}:{2}", protocol, host, port);

            var uriBuilder = new UriBuilder(websiteUrl);
            var portalUrl = uriBuilder.Uri;
            var installUri = new Uri(portalUrl, @"Install/Install.aspx?mode=installresources");

            // Clean target install directory.
            if (site.Applications == null || site.Applications.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("The IIS website named: " + websiteName + " does not appear to be set up as a web application.");
            }

            var siteApp = site.Applications["/"];
            if (siteApp == null)
            {
                throw new ArgumentOutOfRangeException("The IIS website named: " + websiteName + " does not appear to be set up as a web application.");
            }

            if (siteApp.VirtualDirectories == null || siteApp.VirtualDirectories.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("The IIS website named: " + websiteName + " does not appear to have a virtual directory configured.");
            }

            var siteVirtualDir = siteApp.VirtualDirectories["/"];
            string websitePhysicalPath = siteVirtualDir.PhysicalPath;

            var targetPath = Path.GetFullPath(websitePhysicalPath);
            var targetInstallModulePath = Path.Combine(targetPath, "Install", "Module");
            var targetInstallModuleDirInfo = new DirectoryInfo(targetInstallModulePath);

            Console.WriteLine("Clearing Install/Module directory " + targetInstallModulePath);
            DnnInstallHelper.DeleteInstallPackagesInDirectory(targetInstallModuleDirInfo);

            var sourcePath = Path.GetFullPath(sourcePackagesFolder);
            var sourceDirInfo = new DirectoryInfo(sourcePath);
            // Default to a "Content" subfolder if there is one.
            if (sourceDirInfo.GetDirectories("Content").Any())
            {
                sourceDirInfo = sourceDirInfo.GetDirectories("Content").First();
            }
            Console.WriteLine("Deploying install packages..");
            var deployedPackages = DnnInstallHelper.DeployInstallPackages(sourceDirInfo, targetInstallModuleDirInfo, (i, t) => Console.WriteLine(string.Format("Deploying package {0} of {1}", i, t)));
            foreach (var deployedPackage in deployedPackages)
            {
                Console.WriteLine("Dnn Extension Package: " + deployedPackage.Name + " will be installed.");
            }

            Console.WriteLine("Installing packages..");
            int maxAttempt = 10;
            bool success = DnnInstallHelper.PerformBulkInstall(installUri, targetInstallModuleDirInfo, Console.WriteLine, 10);
            if (!success)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                var message = string.Format("After {0} attempts, the following packages have failed to install:", maxAttempt);
                Console.WriteLine(message);

                // Get failed install packages.
                var failures = DnnInstallHelper.GetInstallPackagesInDirectory(targetInstallModuleDirInfo);
                foreach (var fileInfo in failures)
                {
                    Console.WriteLine(fileInfo.Name);
                }
                Console.WriteLine("Some packages failed to install.");
                Console.ResetColor();
                return false;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Dnn package installation successful.");
            return true;
        }