コード例 #1
0
 public void ServiceFormatConversion()
 {
     Assert.AreEqual(System.Environment.MachineName,
                     DatabaseInstaller.ServiceFormatToHostFormat("MSSQLSERVER"));
     Assert.AreEqual(System.Environment.MachineName + @"\SQLEXPRESS",
                     DatabaseInstaller.ServiceFormatToHostFormat("MSSQL$SQLEXPRESS"));
 }
コード例 #2
0
        public ActionResult Uninstall(string moduleName)
        {
            ModuleType moduleType = this._moduleTypeService.GetModuleByName(moduleName);
            // First check if there are no sections attached
            IList <Section> sectionsByModuleType = this._sectionService.GetSectionsByModuleType(moduleType);

            if (sectionsByModuleType.Count > 0)
            {
                StringBuilder messageBuilder = new StringBuilder();
                messageBuilder.Append(GetText("UninstallModuleForbiddenBecauseOfRelatedSectionsMessage"));
                messageBuilder.Append(":<br />");
                foreach (var section in sectionsByModuleType)
                {
                    messageBuilder.AppendFormat("{0} ({1})<br />", section.Title, section.Id);
                }
                Messages.AddFlashMessage(messageBuilder.ToString());
            }
            else
            {
                try
                {
                    DatabaseInstaller dbInstaller = GetDbInstallerForModuleType(moduleType);
                    dbInstaller.Uninstall();
                    Messages.AddFlashMessageWithParams("ModuleUninstalledMessage", moduleName);
                }
                catch (Exception ex)
                {
                    Messages.AddFlashException(ex);
                }
            }
            return(RedirectToAction("Index"));
        }
コード例 #3
0
        private void CheckInstaller()
        {
            // Check version and redirect to install pages if neccessary.
            DatabaseInstaller dbInstaller = new DatabaseInstaller(HttpContext.Current.Server.MapPath("~/Install/Core"),
                                                                  Assembly.Load("CMS.Core"));

            if (dbInstaller.TestDatabaseConnection())
            {
                if (dbInstaller.CanUpgrade)
                {
                    HttpContext.Current.Application.Lock();
                    HttpContext.Current.Application["IsUpgrading"] = true;
                    HttpContext.Current.Application.UnLock();

                    HttpContext.Current.Response.Redirect("~/Install/Upgrade.aspx");
                }
                else if (dbInstaller.CanInstall)
                {
                    HttpContext.Current.Application.Lock();
                    HttpContext.Current.Application["IsInstalling"] = true;
                    HttpContext.Current.Application.UnLock();
                    HttpContext.Current.Response.Redirect("~/Install/Install.aspx");
                }
            }
            else
            {
                throw new Exception("Cuyahoga can't connect to the database. Please check your application settings.");
            }
        }
コード例 #4
0
 public DatabaseGraphType(
     DatabaseInstaller databaseInstaller
     )
 {
     this.DatabaseInstaller = databaseInstaller;
     Field(x => x.IsInstalled).Description("Indicates whether the database is installed or not");
 }
コード例 #5
0
        private void DropDatabase(System.Collections.IDictionary savedState)
        {
            // Try and drop the database
            try
            {
                if ((savedState[_serverString] == null) ||
                    (savedState[_dataString] == null) ||
                    (savedState[_userString] == null) ||
                    (savedState[_passString] == null))
                {
                    // Had not completed database configuration - can safely ignore
                    return;
                }

                DatabaseInstaller dbIns = new
                                          DatabaseInstaller((string)savedState[_serverString],
                                                            (string)savedState[_dataString],
                                                            (string)savedState[_userString],
                                                            (string)savedState[_passString]);
                dbIns.DropDatabase();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Service.SyslogServiceName, ex.Message,
                                    EventLogEntryType.Error);
                // Not fatal - manual database uninstall required however
            }
        }
コード例 #6
0
        protected override void OnBeforeInstall(System.Collections.IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);

            // Set up SQL server dependency (if required)
            if (SkipDatabaseInstallation)
            {
                return;
            }

            try
            {
                DatabaseInstaller dbInsSys = GetSystemInstaller();
                if (dbInsSys.LocalServer)
                {
                    serviceInstaller.ServicesDependedOn = new string[]
                    { dbInsSys.SQLServerServiceInstance() }
                }
                ;
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Service.SyslogServiceName, ex.Message,
                                    EventLogEntryType.Error);
            }
        }
コード例 #7
0
        private void btnUpgradeDatabase_Click(object sender, EventArgs e)
        {
            DatabaseInstaller dbInstaller        = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("CMS.Core"));
            DatabaseInstaller modulesDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("CMS.Modules"));

            try
            {
                dbInstaller.Upgrade();
                if (modulesDbInstaller.CanUpgrade)
                {
                    modulesDbInstaller.Upgrade();
                }
                this.pnlIntro.Visible    = false;
                this.pnlFinished.Visible = true;

                // Remove the IsUpgrading flag, so users can view the pages again.
                HttpContext.Current.Application.Lock();
                HttpContext.Current.Application["IsUpgrading"] = false;
                HttpContext.Current.Application.UnLock();
            }
            catch (Exception ex)
            {
                ShowError("An error occured while installing the database tables: <br/>" + ex.ToString());
            }
        }
コード例 #8
0
        private void Page_Load(object sender, EventArgs e)
        {
            this.pnlErrors.Visible = false;

            // Check security first
            User cuyahogaUser = (User)this.User.Identity;

            if (!cuyahogaUser.HasPermission(AccessLevel.Administrator))
            {
                throw new AccessForbiddenException("Upgrade not allowed for the current user");
            }

            if (!this.IsPostBack)
            {
                try
                {
                    // Check upgradable state. Check both CMS.Core and CMS.Modules.
                    bool canUpgrade = false;

                    // Core
                    DatabaseInstaller dbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("CMS.Core"));
                    if (dbInstaller.CanUpgrade)
                    {
                        canUpgrade = true;
                        lblCoreAssemblyCurrent.Text = "Cuyahoga Core " + dbInstaller.CurrentVersionInDatabase.ToString(3);
                        lblCoreAssemblyNew.Text     = "Cuyahoga Core " + dbInstaller.NewAssemblyVersion.ToString(3);
                        // Core modules
                        DatabaseInstaller moduleDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("CMS.Modules"));
                        lblModulesAssemblyCurrent.Text = "Cuyahoga Core Modules " + moduleDbInstaller.CurrentVersionInDatabase.ToString(3);
                        if (moduleDbInstaller.CanUpgrade)
                        {
                            lblModulesAssemblyNew.Text = "Cuyahoga Core Modules " + moduleDbInstaller.NewAssemblyVersion.ToString(3);
                        }
                        else
                        {
                            lblModulesAssemblyNew.Text = "Cuyahoga Core Modules - no upgrade available";
                        }
                    }
                    if (canUpgrade)
                    {
                        this.pnlIntro.Visible = true;
                    }
                    else
                    {
                        ShowError("Nothing to upgrade.");
                    }
                }
                catch (Exception ex)
                {
                    ShowError("An error occured: <br/><br/>" + ex.ToString());
                }
            }
        }
コード例 #9
0
ファイル: Install.aspx.cs プロジェクト: xiaopohou/cuyahoga
 private void InstallOptionalModules()
 {
     foreach (RepeaterItem ri in this.rptModules.Items)
     {
         CheckBox chkInstall = ri.FindControl("chkInstall") as CheckBox;
         if (chkInstall != null && chkInstall.Checked)
         {
             Literal           litModuleName   = (Literal)ri.FindControl("litModuleName");
             string            moduleName      = litModuleName.Text;
             DatabaseInstaller moduleInstaller = new DatabaseInstaller(Path.Combine(Server.MapPath("~/Modules/" + moduleName), "Install"), null);
             moduleInstaller.Install();
         }
     }
 }
コード例 #10
0
        public ActionResult Upgrade(string moduleName)
        {
            ModuleType moduleType = this._moduleTypeService.GetModuleByName(moduleName);

            try
            {
                DatabaseInstaller dbInstaller = GetDbInstallerForModuleType(moduleType);
                dbInstaller.Upgrade();
                Messages.AddFlashMessageWithParams("ModuleUpgradedMessage", moduleName);
            }
            catch (Exception ex)
            {
                Messages.AddFlashException(ex);
            }
            return(RedirectToAction("Index"));
        }
コード例 #11
0
ファイル: Install.aspx.cs プロジェクト: xiaopohou/cuyahoga
        private void Page_Load(object sender, EventArgs e)
        {
            this.pnlErrors.Visible = false;

            if (!this.IsPostBack)
            {
                try
                {
                    // Check installable state. Check both Cuyahoga.Core and Cuyahoga.Modules.
                    bool canInstall = false;
                    // Core
                    DatabaseInstaller dbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("Cuyahoga.Core"));
                    if (dbInstaller.CanInstall)
                    {
                        lblCoreAssembly.Text = "Cuyahoga Core " + dbInstaller.NewAssemblyVersion.ToString(3);
                        // Core modules
                        DatabaseInstaller moduleDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("Cuyahoga.Modules"));
                        if (moduleDbInstaller.CanInstall)
                        {
                            canInstall = true;
                            lblModulesAssembly.Text = "Cuyahoga Core Modules " + moduleDbInstaller.NewAssemblyVersion.ToString(3);
                        }
                    }
                    if (canInstall)
                    {
                        this.pnlIntro.Visible = true;
                    }
                    else
                    {
                        // Check if we perhaps need to add an admin
                        if (this._commonDao.GetAll(typeof(User)).Count == 0)
                        {
                            this.pnlAdmin.Visible = true;
                        }
                        else
                        {
                            ShowError("Can't install Cuyahoga. Check if the install.sql file exists in the /Install/Core|Modules/Database/DATABASE_TYPE/ directory and that there isn't already a version installed.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowError("An error occured: <br/><br/>" + ex.ToString());
                }
            }
        }
コード例 #12
0
ファイル: Install.aspx.cs プロジェクト: xiaopohou/cuyahoga
        private void btnInstallDatabase_Click(object sender, EventArgs e)
        {
            DatabaseInstaller dbInstaller        = new DatabaseInstaller(Server.MapPath("~/Install/Core"), Assembly.Load("Cuyahoga.Core"));
            DatabaseInstaller modulesDbInstaller = new DatabaseInstaller(Server.MapPath("~/Install/Modules"), Assembly.Load("Cuyahoga.Modules"));

            try
            {
                dbInstaller.Install();
                modulesDbInstaller.Install();
                this.pnlIntro.Visible   = false;
                this.pnlModules.Visible = true;
                BindOptionalModules();
                ShowMessage("Database tables successfully created.");
            }
            catch (Exception ex)
            {
                ShowError("An error occured while installing the database tables: <br/>" + ex.ToString());
            }
        }
コード例 #13
0
 public ActionResult Install(string moduleName)
 {
     try
     {
         string            moduleInstallDirectory = GetPhysicalModuleInstallDirectory(moduleName);
         DatabaseInstaller dbInstaller            = new DatabaseInstaller(moduleInstallDirectory, null);
         dbInstaller.Install();
         ModuleType moduleType = this._moduleTypeService.GetModuleByName(moduleName);
         moduleType.AutoActivate = true;
         this._moduleTypeService.SaveOrUpdateModuleType(moduleType);
         this._moduleLoader.ActivateModule(moduleType);
         Messages.AddFlashMessageWithParams("ModuleInstalledAndActivatedMessage", moduleName);
     }
     catch (Exception ex)
     {
         Messages.AddFlashException(ex);
     }
     return(RedirectToAction("Index"));
 }
コード例 #14
0
        private void rptModules_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string[] commandArguments = e.CommandArgument.ToString().Split(':');
            string   moduleName       = commandArguments[0];
            string   assemblyName     = commandArguments[1];
            Assembly assembly         = null;

            if (assemblyName.Length > 0)
            {
                assembly = Assembly.Load(assemblyName);
            }

            string            moduleInstallDirectory = Path.Combine(Server.MapPath("~/Modules/" + moduleName), "Install");
            DatabaseInstaller dbInstaller            = new DatabaseInstaller(moduleInstallDirectory, assembly);

            try
            {
                switch (e.CommandName.ToLower())
                {
                case "install":
                    dbInstaller.Install();
                    break;

                case "upgrade":
                    dbInstaller.Upgrade();
                    break;

                case "uninstall":
                    dbInstaller.Uninstall();
                    break;
                }

                // Rebind modules
                BindModules();

                ShowMessage(e.CommandName + ": thao tác thành công với " + moduleName + ".");
            }
            catch (Exception ex)
            {
                ShowError(e.CommandName + ": thao tác thất bại với " + moduleName + ".<br/>" + ex.Message);
            }
        }
コード例 #15
0
ファイル: Install.aspx.cs プロジェクト: xiaopohou/cuyahoga
        private void BindOptionalModules()
        {
            // Retrieve the modules that are already installed.
            IList availableModules = this._commonDao.GetAll(typeof(ModuleType), "Name");
            // Retrieve the available modules from the filesystem.
            string moduleRootDir = HttpContext.Current.Server.MapPath("~/Modules");

            DirectoryInfo[] moduleDirectories = new DirectoryInfo(moduleRootDir).GetDirectories();
            // Go through the directories and add the modules that can be installed
            ArrayList installableModules = new ArrayList();

            foreach (DirectoryInfo di in moduleDirectories)
            {
                // Skip hidden directories.
                bool shouldAdd = (di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden;
                foreach (ModuleType moduleType in availableModules)
                {
                    if (moduleType.Name == di.Name)
                    {
                        shouldAdd = false;
                        break;
                    }
                }
                if (shouldAdd)
                {
                    // Check if the module can be installed
                    DatabaseInstaller moduleInstaller = new DatabaseInstaller(Path.Combine(Server.MapPath("~/Modules/" + di.Name), "Install"), null);
                    if (moduleInstaller.CanInstall)
                    {
                        installableModules.Add(di.Name);
                    }
                }
            }
            this.rptModules.DataSource = installableModules;
            this.rptModules.DataBind();
        }
コード例 #16
0
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            try
            {
                if (SkipDatabaseInstallation)
                {
                    EventLog.WriteEntry(Service.SyslogServiceName,
                                        "Installation of database skipped - manual configuration will be required",
                                        EventLogEntryType.Warning);
                    return;
                }

                DatabaseInstaller dbInsSys  = GetSystemInstaller();
                DatabaseInstaller dbInsUser = GetUserInstaller();

                // Ensure same username not given if not using IWA
                if (!dbInsSys.TrustedConnection && !dbInsUser.TrustedConnection &&
                    (dbInsSys.UserName == dbInsUser.UserName))
                {
                    throw new Exception("When not using Windows authentication the username given to "
                                        + "create the database must be different from the username Syslog Server will use");
                }

                // Check database does not already exist
                if (dbInsSys.DatabaseExists)
                {
                    throw new InstallException(
                              String.Format("The database {0} already exists on the server {1}",
                                            dbInsSys.Database, dbInsSys.Server));
                }

                // Check user can access the database server
                if (!dbInsUser.TrustedConnection)
                {
                    try
                    {
                        dbInsUser.TestMasterConnection();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(String.Format(
                                                "Unable to connect to the database server as user {0}: {1}",
                                                dbInsUser.UserName, ex.Message));
                    }
                }

                // Time to do the actual work

                // Create database
                dbInsSys.CreateDatabase(Assembly.GetExecutingAssembly(),
                                        "Aonaware.SyslogService.database.create.sql");

                // Add system logon credentials stateServer for uninstall / rollback
                // Todo: encrypt this
                stateSaver.Add(_serverString, dbInsSys.Server);
                stateSaver.Add(_dataString, dbInsSys.Database);
                stateSaver.Add(_userString, dbInsSys.UserName);
                stateSaver.Add(_passString, dbInsSys.Password);

                // If not using IWA for our user connection, add the user to the service role
                if (!dbInsUser.TrustedConnection)
                {
                    Dictionary <string, string> rep = new Dictionary <string, string>();
                    rep["%SVCUSER%"] = dbInsUser.UserName;

                    dbInsSys.ExecuteGenericSQL(Assembly.GetExecutingAssembly(),
                                               "Aonaware.SyslogService.database.users.sql", rep);
                }

                // Finally modify the config file
                string configFile = Assembly.GetExecutingAssembly().Location + ".config";
                dbInsUser.ModifyConfigFile(configFile, "Aonaware.SyslogService.Properties.Settings.DbConnection");
            }
            catch (InstallException inst)
            {
                throw inst;
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Service.SyslogServiceName, ex.Message,
                                    EventLogEntryType.Error);
                throw new InstallException(ex.Message);
            }
        }
コード例 #17
0
        private void rptModules_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ModuleType moduleType = e.Item.DataItem as ModuleType;
                string     physicalModuleInstallDirectory =
                    Path.Combine(Server.MapPath("~/Modules/" + moduleType.Name), "Install");
                Assembly moduleAssembly = null;
                if (moduleType.AssemblyName != null)
                {
                    moduleAssembly = Assembly.Load(moduleType.AssemblyName);
                }
                DatabaseInstaller dbInstaller = new DatabaseInstaller(physicalModuleInstallDirectory, moduleAssembly);
                bool       canInstall         = dbInstaller.CanInstall;
                bool       canUpgrade         = dbInstaller.CanUpgrade;
                bool       canUninstall       = dbInstaller.CanUninstall;
                LinkButton lbtInstall         = e.Item.FindControl("lbtInstall") as LinkButton;
                lbtInstall.Visible = canInstall;
                lbtInstall.Attributes.Add("onclick", "return confirm('Cài đặt phân hệ?')");
                LinkButton lbtUpgrade = e.Item.FindControl("lbtUpgrade") as LinkButton;
                lbtUpgrade.Visible = canUpgrade;
                lbtUpgrade.Attributes.Add("onclick", "return confirm('Nâng cấp phân hệ?')");
                LinkButton lbtUninstall = e.Item.FindControl("lbtUninstall") as LinkButton;
                lbtUninstall.Visible = canUninstall;
                lbtUninstall.Attributes.Add("onclick", "return confirm('Gỡ bỏ phân hệ?')");

                CheckBox chkBox = e.Item.FindControl("chkBoxActivation") as CheckBox;
                if (canInstall)
                {
                    chkBox.Enabled = false;
                    chkBox.Checked = moduleType.AutoActivate;
                }
                else
                {
                    chkBox.Enabled = true;
                    chkBox.Checked = moduleType.AutoActivate;
                    if (moduleType.Name != null)
                    {
                        chkBox.InputAttributes.Add("moduleTypeId", moduleType.ModuleTypeId.ToString());
                    }
                }
                Literal litActivationStatus = e.Item.FindControl("litActivationStatus") as Literal;
                if (ModuleLoader.IsModuleActive(moduleType))
                {
                    litActivationStatus.Text = "<span style=\"color:green;\">Hoạt động</span>";
                }
                else
                {
                    litActivationStatus.Text = "<span style=\"color:red;\">Chưa nạp</span>";
                }

                Literal litStatus = e.Item.FindControl("litStatus") as Literal;
                if (dbInstaller.CurrentVersionInDatabase != null)
                {
                    litStatus.Text = String.Format("Đã cài ({0}.{1}.{2})"
                                                   , dbInstaller.CurrentVersionInDatabase.Major
                                                   , dbInstaller.CurrentVersionInDatabase.Minor
                                                   , dbInstaller.CurrentVersionInDatabase.Build);
                    if (dbInstaller.CanUpgrade)
                    {
                        litStatus.Text += " (tồn tại nâng cấp) ";
                    }
                }
                else
                {
                    litStatus.Text = "Đã gỡ bỏ";
                }
            }
        }
コード例 #18
0
 public DatabaseMutations(
     DatabaseInstaller databaseInstaller
     )
 {
     this.DatabaseInstaller = databaseInstaller;
 }
コード例 #19
0
        private static void StartupEndpoint()
        {
            try
            {
                Logger.LogInfo("Attempting to execute database upgrade.");
                var connectionStringSettings = ConfigurationManager.ConnectionStrings["gFileSystemEntities"];
                var connectionStringBuilder  = new SqlConnectionStringBuilder(connectionStringSettings.ConnectionString)
                {
                    InitialCatalog = "Master"
                };

                var installer = new DatabaseInstaller();
                if (installer.NeedsUpdate(connectionStringSettings.ConnectionString))
                {
                    var setup = new InstallSetup
                    {
                        AcceptVersionWarningsChangedScripts = true,
                        AcceptVersionWarningsNewScripts     = true,
                        ConnectionString       = connectionStringSettings.ConnectionString,
                        InstallStatus          = InstallStatusConstants.Upgrade,
                        MasterConnectionString = connectionStringBuilder.ToString()
                    };

                    installer.Install(setup);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Failed to execute database upgrade.");
                throw new Exception("Failed to execute database upgrade.");
            }

            Logger.LogInfo("Services Started Begin");
            try
            {
                #region Primary Endpoint

                var service        = new SystemCore();
                var primaryAddress = new Uri("net.tcp://localhost:" + ConfigHelper.Port + "/__gfile");
                var primaryHost    = new ServiceHost(service, primaryAddress);

                //Initialize the service
                //var netTcpBinding = new CompressedNetTcpBinding();
                var netTcpBinding = new NetTcpBinding {
                    MaxBufferSize = 10 * 1024 * 1024, MaxReceivedMessageSize = 10 * 1024 * 1024, MaxBufferPoolSize = 10 * 1024 * 1024
                };
                netTcpBinding.ReaderQuotas.MaxStringContentLength = 10 * 1024 * 1024;
                netTcpBinding.ReaderQuotas.MaxBytesPerRead        = 10 * 1024 * 1024;
                netTcpBinding.ReaderQuotas.MaxArrayLength         = 10 * 1024 * 1024;
                netTcpBinding.ReaderQuotas.MaxDepth = 10 * 1024 * 1024;
                netTcpBinding.ReaderQuotas.MaxNameTableCharCount = 10 * 1024 * 1024;
                netTcpBinding.Security.Mode = SecurityMode.None;
                primaryHost.AddServiceEndpoint(typeof(ISystemCore), netTcpBinding, string.Empty);
                primaryHost.Open();

                //Create Core Listener
                var primaryEndpoint = new EndpointAddress(primaryHost.BaseAddresses.First().AbsoluteUri);
                var primaryClient   = new ChannelFactory <ISystemCore>(netTcpBinding, primaryEndpoint);
                _core = primaryClient.CreateChannel();

                #endregion

                Logger.LogInfo("Service Running on Port " + ConfigHelper.Port);
                Logger.LogInfo("Services Started End");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                throw;
            }
        }
コード例 #20
0
        public void BestInstance()
        {
            string instance = DatabaseInstaller.DefaultInstance();

            Console.WriteLine("Best SQL Server instance on this machine: {0}", instance);
        }
コード例 #21
0
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            try
            {
                if (SkipDatabaseInstallation)
                {
                    EventLog.WriteEntry(_syslogWebName,
                                        "Installation of database skipped - manual configuration will be required",
                                        EventLogEntryType.Warning);
                    return;
                }

                DatabaseInstaller dbInsSys  = GetSystemInstaller();
                DatabaseInstaller dbInsUser = GetUserInstaller();

                // Check that the system login can access the database
                try
                {
                    dbInsSys.TestMasterConnection();
                }
                catch (Exception ex)
                {
                    throw new Exception(String.Format(
                                            "Unable to connect to the database server as user {0}: {1}",
                                            dbInsUser.UserName, ex.Message));
                }

                // If user login given, check that too
                if (!dbInsUser.TrustedConnection)
                {
                    try
                    {
                        dbInsUser.TestMasterConnection();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(String.Format(
                                                "Unable to connect to the database server as user {0}: {1}",
                                                dbInsUser.UserName, ex.Message));
                    }
                }

                // Check that the database already exists
                if (!dbInsSys.DatabaseExists)
                {
                    throw new InstallException(
                              String.Format("The database {0} does not exists on the server {1}",
                                            dbInsSys.Database, dbInsSys.Server));
                }

                // If we are installing this application
                //  - on the same computer as SQL Server / MSDE
                //  - using IWA
                // Then add the ASP.NET service account to the database
                if (dbInsUser.TrustedConnection && dbInsUser.LocalServer)
                {
                    try
                    {
                        // Determine which account to use
                        string accountDBName = String.Empty;
                        string accountNTName = String.Empty;

                        // Search for IIS user

                        List <LocalUsersAndGroups.User> au = LocalUsersAndGroups.Users();
                        foreach (LocalUsersAndGroups.User u in au)
                        {
                            if (u.Name.ToUpper() == _aspNet)
                            {
                                accountDBName = u.Name;
                                accountNTName = u.Caption;
                                break;
                            }
                        }

                        if (accountDBName.Length == 0)
                        {
                            // Assume network service
                            accountDBName = "NETWORK SERVICE";
                            accountNTName = @"NT AUTHORITY\NETWORK SERVICE";
                        }

                        // Add account to database if needed
                        Dictionary <string, string> rep = new Dictionary <string, string>();
                        rep["%NTUSER%"]    = accountNTName;
                        rep["%NEWDBUSER%"] = accountDBName;

                        dbInsSys.ExecuteGenericSQL(Assembly.GetExecutingAssembly(),
                                                   "Aonaware.SyslogWeb.database.createuser.sql", rep);

                        // Add some info to the event log
                        EventLog.WriteEntry(_syslogWebName, String.Format(
                                                "Automatically added account {0} to database", accountNTName),
                                            EventLogEntryType.Information);
                    }
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry(_syslogWebName,
                                            String.Format("Unable to create ASP.NET account on database server: {0}",
                                                          ex.Message), EventLogEntryType.Warning);
                    }
                }

                // If we are using SQL Server authentication, give access to database
                if (!dbInsUser.TrustedConnection)
                {
                    Dictionary <string, string> rep = new Dictionary <string, string>();
                    rep["%SVCUSER%"] = dbInsUser.UserName;

                    dbInsSys.ExecuteGenericSQL(Assembly.GetExecutingAssembly(),
                                               "Aonaware.SyslogWeb.database.users.sql", rep);
                }

                // Finally modify the config file
                string targetDir  = TargetDirectory;
                string configFile = Path.Combine(targetDir, "Web.config");
                dbInsUser.ModifyConfigFile(configFile, "Aonaware.SyslogWeb.Properties.Settings.DbConnection");
            }
            catch (InstallException inst)
            {
                throw inst;
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(_syslogWebName, ex.Message,
                                    EventLogEntryType.Error);
                throw new InstallException(ex.Message);
            }
        }
コード例 #22
0
        private IEnumerable <ModuleViewData> GetModuleViewData()
        {
            // Retrieve the available modules that are installed.
            IList <ModuleType> availableModules = this._moduleTypeService.GetAllModuleTypes();
            // Retrieve the available modules from the filesystem.
            string moduleRootDir = Server.MapPath("~/Modules");

            DirectoryInfo[] moduleDirectories = new DirectoryInfo(moduleRootDir).GetDirectories();
            // Go through the directories and check if there are missing ones. Those have to be added
            // as new ModuleType candidates.
            foreach (DirectoryInfo di in moduleDirectories)
            {
                // Skip hidden directories and shared directory.
                bool shouldAdd = (di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && di.Name.ToLowerInvariant() != "shared";

                foreach (ModuleType moduleType in availableModules)
                {
                    if (moduleType.Name == di.Name)
                    {
                        shouldAdd = false;
                        break;
                    }
                }
                if (shouldAdd)
                {
                    ModuleType newModuleType = new ModuleType();
                    newModuleType.Name = di.Name;
                    availableModules.Add(newModuleType);
                }
            }

            IList <ModuleViewData> moduleViewDataList = new List <ModuleViewData>();

            foreach (var availableModule in availableModules)
            {
                var moduleViewData = new ModuleViewData(availableModule);

                string   physicalModuleInstallDirectory = GetPhysicalModuleInstallDirectory(availableModule.Name);
                Assembly moduleAssembly = null;
                if (availableModule.AssemblyName != null)
                {
                    moduleAssembly = Assembly.Load(availableModule.AssemblyName);
                }
                DatabaseInstaller dbInstaller = new DatabaseInstaller(physicalModuleInstallDirectory, moduleAssembly);
                moduleViewData.CanInstall   = dbInstaller.CanInstall;
                moduleViewData.CanUpgrade   = dbInstaller.CanUpgrade;
                moduleViewData.CanUninstall = dbInstaller.CanUninstall;

                moduleViewData.ActivationStatus = this._moduleLoader.IsModuleActive(availableModule)
                                                                        ? GetText("ActiveStatus")
                                                                        : GetText("InactiveStatus");
                if (dbInstaller.CurrentVersionInDatabase != null)
                {
                    moduleViewData.ModuleVersion = dbInstaller.CurrentVersionInDatabase.ToString(3);
                    if (dbInstaller.CanUpgrade)
                    {
                        moduleViewData.InstallationStatus = GetText("InstalledUpgradeStatus");
                    }
                    else
                    {
                        moduleViewData.InstallationStatus = GetText("InstalledStatus");
                    }
                }
                else
                {
                    moduleViewData.InstallationStatus = GetText("UninstalledStatus");
                }
                moduleViewDataList.Add(moduleViewData);
            }
            return(moduleViewDataList);
        }
コード例 #23
0
        private void StartupEndpoint()
        {
            var config = new SetupConfig();

            try
            {
                LoggerCQ.LogInfo("Attempting to upgrade database.");
                var connectionStringSettings = ConfigurationManager.ConnectionStrings["DatastoreEntities"];
                var connectionStringBuilder  = new SqlConnectionStringBuilder(connectionStringSettings.ConnectionString)
                {
                    InitialCatalog = "Master"
                };

                //Make sure there are no other nHydrate installations on this database
                if (DbMaintenanceHelper.ContainsOtherInstalls(connectionStringSettings.ConnectionString))
                {
                    LoggerCQ.LogError($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}");
                    throw new Exception($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}");
                }

                //Even a blank database gets updated below so save if DB is blank when started
                var isBlank = DbMaintenanceHelper.IsBlank(connectionStringSettings.ConnectionString);

                var installer = new DatabaseInstaller();
                if (installer.NeedsUpdate(connectionStringSettings.ConnectionString))
                {
                    var setup = new InstallSetup
                    {
                        AcceptVersionWarningsChangedScripts = true,
                        AcceptVersionWarningsNewScripts     = true,
                        ConnectionString       = connectionStringSettings.ConnectionString,
                        InstallStatus          = InstallStatusConstants.Upgrade,
                        MasterConnectionString = connectionStringBuilder.ToString(),
                        SuppressUI             = true,
                    };
                    installer.Install(setup);
                }

                //If new database then add file split data files to reduce file locking
                if (isBlank)
                {
                    try
                    {
                        DbMaintenanceHelper.SplitDbFiles(connectionStringSettings.ConnectionString);
                        LoggerCQ.LogInfo("New database has split data files.");
                    }
                    catch
                    {
                        LoggerCQ.LogWarning("New database could not split data files.");
                    }

                    try
                    {
                        var configFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "setup.config");
                        if (File.Exists(configFile))
                        {
                            var barr = File.ReadAllBytes(configFile);
                            config = ServerUtilities.DeserializeObject <SetupConfig>(barr);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"Setup configuration file is not valid.");
                    }

                    if (config != null)
                    {
                        if (!string.IsNullOrEmpty(config.ListDataPath) && !Directory.Exists(config.ListDataPath))
                        {
                            throw new Exception("The setup configuration file value 'ListDataPath' is not valid");
                        }
                        if (!string.IsNullOrEmpty(config.IndexPath) && !Directory.Exists(config.IndexPath))
                        {
                            throw new Exception("The setup configuration file value 'IndexPath' is not valid");
                        }

                        //Create a file group for List tables
                        config.ListDataPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.ListDataPath, SetupConfig.YFileGroup);

                        //Create a file group for Indexes
                        config.IndexPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.IndexPath, SetupConfig.IndexFileGroup);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerCQ.LogError(ex, "Failed on database upgrade.");
                throw new Exception("Failed on database upgrade.");
            }

            LoggerCQ.LogInfo("Service started begin");
            try
            {
                #region Primary Endpoint

                var service = new Gravitybox.Datastore.Server.Core.SystemCore(ConfigurationManager.ConnectionStrings["DatastoreEntities"].ConnectionString, _enableHouseKeeping);
                if (config != null)
                {
                    ConfigHelper.SetupConfig = config;
                }

                #region Determine if configured port is free
                var isPortFree = false;
                do
                {
                    try
                    {
                        //Determine if can connect to port
                        using (var p1 = new System.Net.Sockets.TcpClient("localhost", ConfigHelper.Port))
                        {
                        }
                        //If did connect successfully then there is already something on this port
                        isPortFree = false;
                        LoggerCQ.LogInfo($"Port {ConfigHelper.Port} is in use...");
                        System.Threading.Thread.Sleep(3000); //wait...
                    }
                    catch (Exception ex)
                    {
                        //If there is an error connecting then nothing is listening on that port so FREE
                        isPortFree = true;
                    }
                } while (!isPortFree);
                #endregion

                var primaryAddress = new Uri($"net.tcp://localhost:{ConfigHelper.Port}/__datastore_core");
                var primaryHost    = new ServiceHost(service, primaryAddress);

                //Initialize the service
                var netTcpBinding = new NetTcpBinding();
                netTcpBinding.MaxConnections = ThrottleMax;
                netTcpBinding.Security.Mode  = SecurityMode.None;
                primaryHost.AddServiceEndpoint(typeof(Gravitybox.Datastore.Common.ISystemCore), netTcpBinding, string.Empty);

                //Add more threads
                var stb = new ServiceThrottlingBehavior
                {
                    MaxConcurrentSessions  = ThrottleMax,
                    MaxConcurrentCalls     = ThrottleMax,
                    MaxConcurrentInstances = ThrottleMax,
                };
                primaryHost.Description.Behaviors.Add(stb);

                primaryHost.Open();

                //Create Core Listener
                var primaryEndpoint = new EndpointAddress(primaryHost.BaseAddresses.First().AbsoluteUri);
                var primaryClient   = new ChannelFactory <Gravitybox.Datastore.Common.ISystemCore>(netTcpBinding, primaryEndpoint);
                _core = primaryClient.CreateChannel();
                (_core as IContextChannel).OperationTimeout = new TimeSpan(0, 0, 120); //Timeout=2m

                #endregion

                LoadEngine(service);
                service.Manager.ResetMaster();
                LoggerCQ.LogInfo("Service started complete");
                ConfigHelper.StartUp();
            }
            catch (Exception ex)
            {
                LoggerCQ.LogError(ex);
                throw;
            }
        }
コード例 #24
0
        private static void Main(string[] args)
        {
            NLog.Targets.Target.Register <Logging.ExceptionalErrorStoreTarget>("ErrorStore");

            LoggerCQ.LogInfo("Initializing Service...");

#if DEBUG
            LoggerCQ.LogInfo("(Debug Build)");
#endif

            //Try to connect to database and if successfull the assume service will start
            try
            {
                var installer = new DatabaseInstaller();
                var connectionStringSettings = ConfigurationManager.ConnectionStrings["DatastoreEntities"];

                //Just wait a few seconds to determine if the database is there
                var cb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionStringSettings.ConnectionString);
                cb.ConnectTimeout = 12;

                var b = installer.NeedsUpdate(cb.ToString());
            }
            catch (Exception ex)
            {
                LoggerCQ.LogError(ex, "Failed to connect to database.");
                throw new Exception("Failed to connect to database.");
            }

            LoggerCQ.LogInfo("Database connection verified.");

            if (args.Any(x => x == "-console" || x == "/console"))
            {
                try
                {
                    var enableHouseKeeping = true;
                    if (args.Any(x => x == "-nohousekeeping" || x == "/nohousekeeping"))
                    {
                        enableHouseKeeping = false;
                    }

                    var service = new PersistentService(enableHouseKeeping);
                    service.Start();
                    Console.WriteLine("Press <ENTER> to stop...");
                    Console.ReadLine();
                    service.Cleanup();
                    service.Stop();
                }
                catch (Exception ex)
                {
                    LoggerCQ.LogError(ex, "Failed to start service from console.");
                    throw;
                }
            }
            else
            {
                try
                {
                    var servicesToRun = new ServiceBase[]
                    {
                        new PersistentService()
                    };
                    ServiceBase.Run(servicesToRun);
                }
                catch (Exception ex)
                {
                    LoggerCQ.LogError(ex, "Failed to start service.");
                }
            }
        }