예제 #1
0
        /// <summary>
        ///     Gets the install setup.
        /// </summary>
        public InstallSetup GetSetup()
        {
            var setup = new InstallSetup();

            // TODO: Check for user/site token

            var steps = new List <InstallSetupStep>();

            var installSteps = _installSteps.GetStepsForCurrentInstallType().ToArray();

            //only get the steps that are targeting the current install type
            steps.AddRange(installSteps);
            setup.Steps = steps;

            _installStatusTracker.Initialize(setup.InstallId, installSteps);

            return(setup);
        }
예제 #2
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;
            }
        }
예제 #3
0
		public void Run(InstallSettings settings)
		{
			//STEPS TO COPY DATABASE TO AZURE
			//1. Verify that target is a blank database
			//2. Execute only tables schemas with no defaults, relations, etc
			//3. Copy data with BCP one table at a time
			//4. Run full installer on the target database

			//1. Verify that target is a blank database
			if (!this.TargetIsBlank(settings))
				throw new Exception("The target database must be empty!");

			//2. Execute only tables schemas and PK with no defaults, relations, etc
			Assembly assem = Assembly.GetExecutingAssembly();
			string[] resourceNames = assem.GetManifestResourceNames();
			var resourceName = resourceNames.FirstOrDefault(x => x.EndsWith(".Create_Scripts.Generated.CreateSchema.sql"));
			if (string.IsNullOrEmpty(resourceName)) throw new Exception("Could not find the 'CreateSchema.sql' resource!");

			var scripts = SqlServers.ReadSQLFileSectionsFromResource(resourceName, null);

			SqlConnection connection = null;
			try
			{
				connection = new SqlConnection(settings.GetCloudConnectionString());
				connection.Open();

				////Create version table
				//var sb = new StringBuilder();
				//sb.AppendLine("if not exists(select * from sysobjects where name = '__nhydrateschema' and xtype = 'U')");
				//sb.AppendLine("BEGIN");
				//sb.AppendLine("CREATE TABLE [__nhydrateschema] (");
				//sb.AppendLine("[dbVersion] [varchar] (50) NOT NULL,");
				//sb.AppendLine("[LastUpdate] [datetime] NOT NULL,");
				//sb.AppendLine("[ModelKey] [uniqueidentifier] NOT NULL,");
				//sb.AppendLine("[History] [text] NOT NULL");
				//sb.AppendLine(")");
				//sb.AppendLine("--PRIMARY KEY FOR TABLE");
				//sb.AppendLine("if not exists(select * from sysobjects where name = '__pk__nhydrateschema' and xtype = 'PK')");
				//sb.AppendLine("ALTER TABLE [__nhydrateschema] WITH NOCHECK ADD CONSTRAINT [__pk__nhydrateschema] PRIMARY KEY CLUSTERED ([ModelKey])");
				//sb.AppendLine("END");
				//var command2 = new SqlCommand(sb.ToString(), connection);
				//command2.ExecuteNonQuery();

				foreach (string sql in scripts)
				{
					if (
						sql.Contains("--CREATE TABLE") ||
						sql.Contains("--CREATE AUDIT TABLE") ||
						sql.StartsWith("--APPEND AUDIT") ||
						sql.StartsWith("--PRIMARY KEY FOR TABLE"))
					{
						var command = new SqlCommand(sql, connection);
						command.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				if (connection != null)
					connection.Close();
			}

			//3. Copy data with BCP one table at a time
			this.CopyData(settings);

			//4. Run full installer on the target database
			var setup = new InstallSetup()
			{
				ConnectionString = settings.GetCloudConnectionString(),
				InstallStatus = InstallStatusConstants.Upgrade,
			};
			UpgradeInstaller.UpgradeDatabase(setup);

		}
예제 #4
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;
            }
        }
예제 #5
0
		private bool CreateDatabase()
		{
			bool error = false;
			string connectString = SqlServers.BuildConnectionString(optCreationIntegratedSecurity.Checked, string.Empty, cboCreationServerName.Text, txtCreationUserName.Text, txtCreationPassword.Text);
			if (SqlServers.TestConnectionString(connectString) && SqlServers.HasCreatePermissions(connectString))
			{
				try
				{
					var setup = new InstallSetup()
					{
						MasterConnectionString = connectString,
						NewDatabaseName = txtCreationDatabaseName.Text,
					};
					SqlServers.CreateDatabase(setup);
				}
				catch (Exception ex)
				{
					error = true;
					System.Diagnostics.Debug.WriteLine(ex.ToString());
					MessageBox.Show("Could not create database." + Environment.NewLine + ex.Message);
				}
			}
			else
			{
				error = true;
				MessageBox.Show("The account does not have permissions to create a database on this server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			return error;
		}
예제 #6
0
		internal static void CreateDatabase(InstallSetup setup)
		{
			System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
			try
			{
				conn.ConnectionString = setup.MasterConnectionString;
				conn.Open();
				var cmdCreateDb = new SqlCommand();
				var collate = string.Empty;
				if (!string.IsNullOrEmpty(collate)) collate = " COLLATE " + collate;
				cmdCreateDb.CommandText = "CREATE DATABASE [" + setup.NewDatabaseName + "]" + collate;
				cmdCreateDb.CommandType = System.Data.CommandType.Text;
				cmdCreateDb.Connection = conn;
				cmdCreateDb.ExecuteNonQuery();
			}
			catch { throw; }
			finally
			{
				if (conn != null)
					conn.Close();
				System.Threading.Thread.Sleep(1000);
			}
		}