Esempio n. 1
0
        private void mtlBackup_Click(object sender, EventArgs e)
        {
            try
            {
                var servidor = new Microsoft.SqlServer.Management.Smo.Server(txtServidor.Text);

                if (_config.UsarDestinoPersonalizado && !string.IsNullOrEmpty(_config.DestinoPersonalizado))
                {
                    servidor.BackupDirectory = _config.DestinoPersonalizado;
                }

                var backup = new Microsoft.SqlServer.Management.Smo.Backup
                {
                    Database    = txtDatabase.Text,
                    Incremental = false
                };
                var filename = $"{txtDatabase.Text}_{DateTime.Now:g}.bak";

                backup.Devices.AddDevice(filename, Microsoft.SqlServer.Management.Smo.DeviceType.File);
                backup.SqlBackup(servidor);

                MetroMessageBox.Show(this, $"Backup '{filename}' Concluido com Sucesso!");
            }
            catch (Exception ex)
            {
                MetroMessageBox.Show(this, ex.Message);
            }
        }
Esempio n. 2
0
        private bool ExceSQL(string path, string constr, ref string logtxt)
        {
            string sql = System.IO.File.ReadAllText(path);

            bool isBuild = false;

            logtxt = "ExceSQL Finished,sql count:0.";
            try
            {
                // string connectonstring = "data source=10.1.8.188;initial catalog=WAPPDB;user id=sa;password=mindray99!";
                SqlConnection conn = new SqlConnection(constr);
                Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new  Microsoft.SqlServer.Management.Common.ServerConnection(conn));
                int i = server.ConnectionContext.ExecuteNonQuery(sql);
                if (i > 0)
                {
                    isBuild = true;
                    logtxt  = "ExceSQL Success,sql count:" + (0 - i).ToString() + ".";
                }
            }
            catch (Exception ex)
            {
                logtxt = "ExceSQL Failed - " + ex.Message;
            }
            return(isBuild);
        }
Esempio n. 3
0
        private void mtlBackup_Click(object sender, EventArgs e)
        {
            try
            {
                var servidor = new Microsoft.SqlServer.Management.Smo.Server(txtServidor.Text);

                if (_config.UsarDestinoPersonalizado && !string.IsNullOrEmpty(_config.DestinoPersonalizado))
                {
                    servidor.BackupDirectory = _config.DestinoPersonalizado;
                }

                var backup = new Microsoft.SqlServer.Management.Smo.Backup
                {
                    Database = txtDatabase.Text,
                    Incremental = false
                };
                var filename = $"{txtDatabase.Text}_{DateTime.Now:g}.bak";

                backup.Devices.AddDevice(filename, Microsoft.SqlServer.Management.Smo.DeviceType.File);
                backup.SqlBackup(servidor);

                MetroMessageBox.Show(this, $"Backup '{filename}' Concluido com Sucesso!");
            }
            catch (Exception ex)
            {
                MetroMessageBox.Show(this, ex.Message);
            }
        }
        /// <summary>
        /// Return false if login user is not DBO.
        /// </summary>
        /// <param name="tpf">a TracePropertiesForm object</param>
        /// <returns>False if login user is not DBO.</returns>
        bool permission(TracePropertiesForm tpf)
        {
            System.Data.SqlClient.SqlConnection conn;
            if (tpf.RawConn != null)
            {
                conn = new System.Data.SqlClient.SqlConnection(tpf.RawConn);
            }
            else
            {
                string str_conn = string.Format("Data Source={0};Application Name={1};Database={2};",
                                                tpf.ServerName, "sqlprofilerapp", "master");
                if (tpf.Username == string.Empty)
                {
                    str_conn += string.Format("Integrated Security={0};", true);
                }
                else
                {
                    str_conn += string.Format("User ID={0};Password={1};", tpf.Username, tpf.Password);
                }
                conn = new System.Data.SqlClient.SqlConnection(str_conn);
            }
            conn.Open();
            Microsoft.SqlServer.Management.Common.ServerConnection sconn;
            sconn = new Microsoft.SqlServer.Management.Common.ServerConnection(conn);
            Microsoft.SqlServer.Management.Smo.Server server;
            server = new Microsoft.SqlServer.Management.Smo.Server(sconn);
            bool rc = server.Databases["master"].DboLogin;

            conn.Close();

            return(rc);
        }
        public string CopyDataBase(string BackUpFile, string DatabaseFilePath, string _databaseName)
        {
            try
            {
                string        connectionString = connection.getConnectionString();
                SqlConnection sqlConnection    = new SqlConnection(connectionString);
                Microsoft.SqlServer.Management.Common.ServerConnection conn = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
                Microsoft.SqlServer.Management.Smo.Server server            = new Microsoft.SqlServer.Management.Smo.Server(conn);
                string databaseName      = GetNextDatabaseName();
                string backUpFile        = BackUpFile;
                string DatabaseFilesPath = DatabaseFilePath;

                try
                {
                    string Query = @"USE [master] 
                    GO
                    RESTORE DATABASE " + databaseName + @" FROM  DISK = N'" + backUpFile + @"' WITH MOVE 'Smart1' TO '" + DatabaseFilesPath + @"\" + databaseName + @".mdf',MOVE 'Smart1_Log' TO '" + DatabaseFilesPath + @"\" + databaseName + @".ldf',REPLACE,STATS=10";
                    server.ConnectionContext.ExecuteNonQuery(Query);
                }
                catch (Exception ex)
                { string str = ex.Message; }


                return(databaseName);
            }
            catch (Exception ex) { string str = ex.Message; return(_databaseName); }
        }
Esempio n. 6
0
        public bool Backing(string database, SqlConnection connection)
        {
            try
            {
                var ServerConnection = new ServerConnection(connection);
                //var Server = new Microsoft.SqlServer.Management.Smo.Server();
                var Server = new Microsoft.SqlServer.Management.Smo.Server(ServerConnection);
                var bkpDBFullWithCompression = new Microsoft.SqlServer.Management.Smo.Backup();
                /* Specify whether you want to back up database or files or log */
                bkpDBFullWithCompression.Action = Microsoft.SqlServer.Management.Smo.BackupActionType.Database;
                /* Specify the name of the database to back up */
                bkpDBFullWithCompression.Database = database;

                /* You can use back up compression technique of SQL Server 2008,
                 * specify CompressionOption property to On for compressed backup */
                if (Server.Name != "(localdb)\\MSSQLLocalDB")
                {
                    bkpDBFullWithCompression.CompressionOption = Microsoft.SqlServer.Management.Smo.BackupCompressionOptions.On;
                }
                bkpDBFullWithCompression.Devices.AddDevice($"{_path}{database}_{DateTime.Now.ToString("yyyyMMdd")}_{Guid.NewGuid()}.bak", Microsoft.SqlServer.Management.Smo.DeviceType.File);
                bkpDBFullWithCompression.BackupSetName        = database + " database Backup - Compressed";
                bkpDBFullWithCompression.BackupSetDescription = database + " database - Full Backup with Compressin - only in SQL Server 2008";
                bkpDBFullWithCompression.SqlBackup(Server);
                return(true);
            }
            catch (Exception) { throw; }
        }
Esempio n. 7
0
 public static void ExecuteSql(string connectionString, string sql)
 {
     using (var conn = new Microsoft.Data.SqlClient.SqlConnection(connectionString))
     {
         var server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(conn));
         server.ConnectionContext.ExecuteNonQuery(sql);
     }
 }
 private void CleaningUpPreviousDb()
 {
     Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(connectionStringBuilder.DataSource);
     if (server.Databases.Contains(connectionStringBuilder.InitialCatalog))
     {
         server.KillAllProcesses(connectionStringBuilder.InitialCatalog);
         server.DetachDatabase(connectionStringBuilder.InitialCatalog, true);
     }
 }
        public void ExecuteString(string script)
        {
            var sqlConnection = (SqlConnection)OpenConnection();

            var server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(sqlConnection));

            server.ConnectionContext.ExecuteNonQuery(script);
            sqlConnection.Close();
        }
Esempio n. 10
0
        private void IPComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            var server = new Microsoft.SqlServer.Management.Smo.Server(IPComboBox.ValueMember.ToString().Trim());

            foreach (Microsoft.SqlServer.Management.Smo.Database db in server.Databases)
            {
                DataComboBox.Items.Add(db.Name);
            }
        }
Esempio n. 11
0
        public bool InitialDBInstance(String dbInstanceName, String dbName, Int32 interval, Int32 timeout, String uid, String dbFilePath)
        {
            bool sqlServerAlive = false;

            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder();

            sqlConnectionStringBuilder.DataSource         = dbInstanceName;
            sqlConnectionStringBuilder.InitialCatalog     = dbName;
            sqlConnectionStringBuilder.ConnectTimeout     = interval;
            sqlConnectionStringBuilder.IntegratedSecurity = true;   //Windows认证

            if (File.Exists(dbFilePath))
            {
                sqlConnectionStringBuilder.AttachDBFilename = dbFilePath;
                Microsoft.SqlServer.Management.Smo.Server server = null;
                bool  retry = true;
                Int32 SQLSERVER_CONNECT_RETRY_COUNT    = 10;
                Int32 SQLSERVER_CONNECT_RETRY_INTERVAL = 1000;
                Int32 connectTryCount = 0;
                while (retry)
                {
                    connectTryCount++;
                    try
                    {
                        server         = new Microsoft.SqlServer.Management.Smo.Server(dbInstanceName);
                        retry          = false;
                        sqlServerAlive = server.Databases.Contains(dbName);
                    }
                    catch (Exception ex)
                    {
                        retry = connectTryCount <= SQLSERVER_CONNECT_RETRY_COUNT;
                        Thread.Sleep(SQLSERVER_CONNECT_RETRY_INTERVAL);
                        //日志
                    }
                }

                if (sqlServerAlive)
                {
                    try
                    {
                        server.DetachDatabase(dbName, false);
                    }
                    catch (Exception ex)
                    {
                        //日志
                    }
                }
            }
            else
            {
                //
            }

            this.m_connectionString = sqlConnectionStringBuilder.ConnectionString;
            return(sqlServerAlive);
        }
Esempio n. 12
0
        public void ExecuteScriptAndUpdateVersionTable(FileInfo fi)
        {
            bool      success    = true;
            Exception exc        = null;
            string    scriptText = null;

            if (string.IsNullOrWhiteSpace(_props.Encoding))
            {
                scriptText = File.ReadAllText(fi.FullName);
            }
            else
            {
                scriptText = File.ReadAllText(fi.FullName, ArgumentHelper.GetEncoding(_props.Encoding));
            }

            using (SqlConnection sqlConnection = new SqlConnection(_props.ConnectionString))
            {
                Microsoft.SqlServer.Management.Common.ServerConnection svrConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
                Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(svrConnection);

                string fileName = fi.FullName.Substring(fi.FullName.IndexOf(_props.VersionScriptsFolder, StringComparison.Ordinal));

                bool hasRows = false;
                using (SqlDataReader reader = server.ConnectionContext.ExecuteReader($"SELECT * FROM {_props.VersionTable} WHERE FileName = '{fileName}'"))
                {
                    hasRows = reader.HasRows;
                }

                if (!hasRows)
                {
                    server.ConnectionContext.BeginTransaction();
                    try
                    {
                        server.ConnectionContext.ExecuteNonQuery(scriptText);
                    }
                    catch (Exception ex)
                    {
                        success = false;
                        exc     = ex;
                        server.ConnectionContext.RollBackTransaction();
                    }

                    if (success)
                    {
                        server.ConnectionContext.CommitTransaction();
                        UpdateVersion(fileName, scriptText);
                    }
                }
            }

            if (!success)
            {
                throw exc;
            }
        }
 //METODO QUE DESCOBRE O DIRETORIO PADRAO DE BACKUP DO SQL
 private void DescobrirDiretoriosPadrao(out string diretorioDados, out string diretorioLog, out string diretorioBackup)
 {
     using (var connection = new System.Data.SqlClient.SqlConnection(@"Server=.\SQLEXPRESS;Database=master;Trusted_Connection=True;"))
     {
         var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(connection);
         var server           = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
         diretorioDados  = !string.IsNullOrWhiteSpace(server.Settings.DefaultFile) ? server.Settings.DefaultFile : (!string.IsNullOrWhiteSpace(server.DefaultFile) ? server.DefaultFile : server.MasterDBPath);
         diretorioLog    = !string.IsNullOrWhiteSpace(server.Settings.DefaultLog) ? server.Settings.DefaultLog : (!string.IsNullOrWhiteSpace(server.DefaultLog) ? server.DefaultLog : server.MasterDBLogPath);
         diretorioBackup = !string.IsNullOrWhiteSpace(server.Settings.BackupDirectory) ? server.Settings.BackupDirectory : server.BackupDirectory;
     }
 }
Esempio n. 14
0
        public static List <string> ListTables(string dbName)
        {
            List <string> tables = new List <string>();

            var server = new Microsoft.SqlServer.Management.Smo.Server(serverName);
            var db     = new Microsoft.SqlServer.Management.Smo.Database(server, dbName);

            db.Refresh();
            foreach (Microsoft.SqlServer.Management.Smo.Table item in db.Tables)
            {
                tables.Add(UpperFirstLetter(item.Name));
            }
            return(tables);
        }
 public static void ClearCreateCoreEntitiesDatabase()
 {
     var clearFile = new FileInfo(ClearCoreEntitiesDatabaseScriptLocation);
     var createFile = new FileInfo(CreateCoreEntitiesDatabaseScriptLocation);
     string clearScript = clearFile.OpenText().ReadToEnd();
     string createScript = createFile.OpenText().ReadToEnd();
     using (var conn = new SqlConnection(ServerConstants.SqlConnectionString))
     {
         var server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
         server.ConnectionContext.ExecuteNonQuery(clearScript);
         server.ConnectionContext.ExecuteNonQuery(createScript);
     }
     clearFile.OpenText().Close();
     createFile.OpenText().Close();
 }
Esempio n. 16
0
        private static Microsoft.SqlServer.Management.Smo.Database GetDatabase()
        {
            var databaseName = System.Configuration.ConfigurationManager.AppSettings["ActiveDatabaseConnection"].ToString();
            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[databaseName].ToString();

            var conn = new Microsoft.SqlServer.Management.Common.ServerConnection();
            conn.ConnectionString = connectionString;
            var server = new Microsoft.SqlServer.Management.Smo.Server(conn);
            server.SetDefaultInitFields(typeof (Microsoft.SqlServer.Management.Smo.StoredProcedure), "IsSystemObject");
            server.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.StoredProcedureParameter), "IsOutputParameter");
            server.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.StoredProcedureParameter), "DataType");
            server.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.StoredProcedureParameter),"DefaultValue");
            var database = server.Databases[databaseName];
            return database;
        }
 public override void GetDatabases(Common.Entities.MetaDataSchema.Project project)
 {
     System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(project.ExtractorManager.ConnectionString);
     conn.Open();
     Microsoft.SqlServer.Management.Common.ServerConnection connection = new Microsoft.SqlServer.Management.Common.ServerConnection(conn);
     Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(connection);
     project.Databases.Clear();
     foreach (Microsoft.SqlServer.Management.Smo.Database database in server.Databases)
     {
         Entities.MetaDataSchema.Database db = new Common.Entities.MetaDataSchema.Database();
         db.Name          = database.Name;
         db.ParentProject = project;
         project.Databases.Add(db);
         project.AddDatabaseNode(project.SchemaDataset.Schema, db.GuidId, "", db.Name, db.Name);
     }
 }
Esempio n. 18
0
 public override DataTable GetDatabases(string serverName)
 {
     DataTable _databases = new DataTable();
     _databases.Columns.Add("database");
     Microsoft.SqlServer.Management.Smo.Server _server = new Microsoft.SqlServer.Management.Smo.Server(serverName);
     if (_server != null)
     {
         foreach (Microsoft.SqlServer.Management.Smo.Database _db in _server.Databases)
         {
             if (!_db.IsSystemObject)
                 _databases.Rows.Add(_db.Name);
         }
         return _databases;
     }
     return null;
 }
Esempio n. 19
0
 public void ExecuteFileSql(string path, ref int count, ref string error)
 {
     try
     {
         FileInfo      file   = new FileInfo(path);
         string        script = file.OpenText().ReadToEnd();
         SqlConnection conn   = new SqlConnection("Data Source=127.0.0.1;User Id=admin;Password=admin;Database=ps_gx");
         Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(conn));
         count = server.ConnectionContext.ExecuteNonQuery(script);
         conn.Close();
     }
     catch (Exception e)
     {
         logger.Info("ExecuteFileSql - error=" + e.Message);
     }
 }
 public override void GetDatabases(Common.Entities.MetaDataSchema.Project project)
 {
     System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(project.ExtractorManager.ConnectionString);
     conn.Open();
     Microsoft.SqlServer.Management.Common.ServerConnection connection = new Microsoft.SqlServer.Management.Common.ServerConnection(conn);
     Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(connection);
     project.Databases.Clear();
     foreach (Microsoft.SqlServer.Management.Smo.Database database in server.Databases)
     {
         Entities.MetaDataSchema.Database db = new Common.Entities.MetaDataSchema.Database();
         db.Name = database.Name;
         db.ParentProject = project;
         project.Databases.Add(db);
         project.AddDatabaseNode(project.SchemaDataset.Schema, db.GuidId, "", db.Name, db.Name);
     }
 }
Esempio n. 21
0
 public static void DropDatabase(string connectionName)
 {
     using (
         var sqlConnection =
             new SqlConnection(
                 ConfigurationManager.ConnectionStrings[connectionName]
                 .ConnectionString))
     {
         var serverConnection = new ServerConnection(sqlConnection);
         var server           = new Microsoft.SqlServer.Management.Smo.Server(
             serverConnection);
         if (server.Databases[sqlConnection.Database] != null)
         {
             server.KillDatabase(sqlConnection.Database);
         }
     }
 }
Esempio n. 22
0
        public bool DropDatabase(string connectionName)
        {
            try
            {
                using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionName].ConnectionString))
                {
                    var serverConnection = new ServerConnection(sqlConnection);
                    var server           = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
                    server.KillDatabase(sqlConnection.Database);

                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 23
0
        public static string DatabaseConnection(string connectionString)
        {
            //Server = 2.56.154.97; Database = myDataBase; User Id = sa; Password = @acm ^ G6U
            string           ServerName = "2.56.154.97";
            string           UserName   = "******";
            string           Password   = "******";
            ServerConnection cn         = new ServerConnection(ServerName, UserName, Password);
            var           server        = new Microsoft.SqlServer.Management.Smo.Server(cn);
            List <string> alldatabases  = new List <string>();

            foreach (Microsoft.SqlServer.Management.Smo.Database db in server.Databases)
            {
                alldatabases.Add(db.Name);
            }
            string databaseName = alldatabases.Find(d => d == connectionString);

            return(databaseName);
        }
Esempio n. 24
0
        public static void ExecuteSqlScript(string script)
        {
            var _oSqlConnection = new ServerConnection
                {
					ServerInstance = "172.16.162.101",
                    SqlExecutionModes = SqlExecutionModes.ExecuteSql,
                    LoginSecure = false,
                    Login = "******",
                    Password = "******"
                };
            Console.WriteLine("Success init ServerConnection");
           
            var server = new Microsoft.SqlServer.Management.Smo.Server();
            Console.WriteLine("Success init Server 1");
            server.ConnectionContext.ConnectionString = _oSqlConnection.ConnectionString;
            Console.WriteLine("Success init Server 2");

            server.ConnectionContext.ExecuteNonQuery(script);

        }
Esempio n. 25
0
 private static void PrepareDatabase()
 {
     Microsoft.SqlServer.Management.Common.ServerConnection svrConnection = new ServerConnection(sqlConnection);
     Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(svrConnection);
     try
     {
         string sqlScript = File.ReadAllText(DatabaseConnectionSettings.DatabaseScriptPath);
         server.ConnectionContext.ExecuteNonQuery(sqlScript);
     }
     catch (System.Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         if (sqlConnection.State == ConnectionState.Open)
         {
             sqlConnection.Close();
         }
     }
 }
Esempio n. 26
0
 public override void Execute(IDictionary<string, object> scope)
 {
     try
     {
         this.Status = OperationStatus.RUNNING;
         SqlConnection conn = scope["CONNECTION"] as SqlConnection;
         DatabaseExplorer exp = new DatabaseExplorer(conn, new SQLServerDefaultConf());
         Schema schema = scope["SCHEMA"] as Schema;
         SqlServerCrudGenerator gen = new SqlServerCrudGenerator(null);
         string script = gen.Generate(schema);
         Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
         server.ConnectionContext.ExecuteNonQuery(script);
         Status = OperationStatus.COMPLETED;
     }
     catch (Exception ex)
     {
         this.Exception = ex;
         this.Status = OperationStatus.FAILED;
         throw ex;
     }
 }
Esempio n. 27
0
        public void ExecuteScriptAndUpdateVersionTable(int versionNo, System.IO.FileInfo fi)
        {
            bool      success    = true;
            Exception exc        = null;
            string    scriptText = null;

            if (string.IsNullOrWhiteSpace(_props.Encoding))
            {
                scriptText = File.ReadAllText(fi.FullName);
            }
            else
            {
                scriptText = File.ReadAllText(fi.FullName, ArgumentHelper.GetEncoding(_props.Encoding));
            }
            using (SqlConnection sqlConnection = new SqlConnection(_props.ConnectionString))
            {
                Microsoft.SqlServer.Management.Common.ServerConnection svrConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
                Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(svrConnection);
                server.ConnectionContext.BeginTransaction();
                try
                {
                    server.ConnectionContext.ExecuteNonQuery(scriptText);
                }
                catch (Exception ex)
                {
                    success = false;
                    exc     = ex;
                    server.ConnectionContext.RollBackTransaction();
                }
                if (success)
                {
                    server.ConnectionContext.CommitTransaction();
                    this.UpdateVersion(versionNo, scriptText);
                }
            }
            if (!success)
            {
                throw exc;
            }
        }
Esempio n. 28
0
        public void CheckSavedPassword()
        {
            if (MainFrm.CurrentProject != null)
            {
                ProjectInfo current = MainFrm.CurrentProject;
                Microsoft.SqlServer.Management.Smo.Server server = null;

                if (current.WindowsAudhority)
                {
                    if (ChinaBest.SQLServer.SmoUtilities.SmoTools.TestDBConnection(current.ServerAddress))
                    {
                        server = new Microsoft.SqlServer.Management.Smo.Server(current.ServerAddress);
                    }
                }
                else
                {
                    if (ChinaBest.SQLServer.SmoUtilities.SmoTools.TestDBConnection(current.ServerAddress, current.UserName, current.Password))
                    {
                        server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(current.ServerAddress, current.UserName, current.Password));
                    }
                }

                if (server != null)
                {
                    MainTreeView.Nodes.Clear();

                    AddServer(server);

                    Microsoft.SqlServer.Management.Smo.Server server1 = (Microsoft.SqlServer.Management.Smo.Server)serverlist[serverlist.Count - 1];
                    serverNode = new TreeNode();
                    serverNode.Name = server1.Name;
                    serverNode.Text = server1.Name;
                    serverNode.ImageIndex = 0;
                    serverNode.SelectedImageIndex = 0;
                    serverNode.Tag = server1;
                    this.MainTreeView.Nodes.Add(serverNode);
                }
            }
        }
Esempio n. 29
0
        public static List <EntityProperty> ListColumnsOfTable(string dbName, string tableName)
        {
            var result = new List <EntityProperty>();

            var server = new Microsoft.SqlServer.Management.Smo.Server(serverName);
            var db     = new Microsoft.SqlServer.Management.Smo.Database(server, dbName);
            var table  = new Microsoft.SqlServer.Management.Smo.Table(db, tableName);

            table.Refresh();
            var dic = new Dictionary <string, string>();

            foreach (Microsoft.SqlServer.Management.Smo.ForeignKey item in table.ForeignKeys)
            {
                dic.Add(item.Columns[0].Name, item.ReferencedTable);
            }
            foreach (Microsoft.SqlServer.Management.Smo.Column item in table.Columns)
            {
                var propertyType = _typeMapping[item.DataType.Name];
                if (item.Nullable == true && propertyType != "string")
                {
                    propertyType = propertyType + "?";
                }

                var entityProperty = new EntityProperty()
                {
                    PropertyType = propertyType,
                    PropertyName = item.Name,
                    IsForeignKey = item.IsForeignKey,
                    IsIdentity   = item.Identity
                };
                if (item.IsForeignKey == true)
                {
                    entityProperty.ForeignKeyTableName = UpperFirstLetter(dic[item.Name]);
                }
                result.Add(entityProperty);
            }
            return(result);
        }
Esempio n. 30
0
 private void BtRestauracao_Click(object sender, EventArgs e)
 {            
     try
     {
         OpenFileDialog d = new OpenFileDialog();
         d.Filter = "Backup Files|*.bak";
         d.ShowDialog();
         if (d.FileName != "")
         {
             String nomeBanco = DadosDaConexao.banco;
             String localBackup = d.FileName;
             String conexao = @"Data Source=" + DadosDaConexao.servidor  + ";Initial Catalog=master;User="******";Password="******"Backup restaurado com sucesso!!!!!");
         }
     }
     catch (Exception erro)
     {
         MessageBox.Show(erro.Message);
     }
 }
Esempio n. 31
0
 private void BtRestauracao_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog d = new OpenFileDialog();
         d.Filter = "Backup Files|*.bak";
         d.ShowDialog();
         if (d.FileName != "")
         {
             String nomeBanco   = DadosDaConexao.banco;
             String localBackup = d.FileName;
             String conexao     = @"Data Source=" + DadosDaConexao.servidor + ";Initial Catalog=master;User="******";Password="******"Backup restaurado com sucesso!!!!!");
         }
     }
     catch (Exception erro)
     {
         MessageBox.Show(erro.Message);
     }
 }
Esempio n. 32
0
        /// <summary>
        /// Return false if login user is not DBO.
        /// </summary>
        /// <param name="tpf">a TracePropertiesForm object</param>
        /// <returns>False if login user is not DBO.</returns>
        bool permission(TracePropertiesForm tpf)
        {
            System.Data.SqlClient.SqlConnection conn;
            if (tpf.RawConn != null)
                conn = new System.Data.SqlClient.SqlConnection(tpf.RawConn);
            else
            {
                string str_conn = string.Format("Data Source={0};Application Name={1};Database={2};",
                    tpf.ServerName, "sqlprofilerapp", "master");
                if (tpf.Username == string.Empty)
                    str_conn += string.Format("Integrated Security={0};", true);
                else
                    str_conn += string.Format("User ID={0};Password={1};", tpf.Username, tpf.Password);
                conn = new System.Data.SqlClient.SqlConnection(str_conn);
            }
            conn.Open();
            Microsoft.SqlServer.Management.Common.ServerConnection sconn;
            sconn = new Microsoft.SqlServer.Management.Common.ServerConnection(conn);
            Microsoft.SqlServer.Management.Smo.Server server;
            server = new Microsoft.SqlServer.Management.Smo.Server(sconn);
            bool rc = server.Databases["master"].DboLogin;
            conn.Close();

            return rc;
        }
Esempio n. 33
0
 /// <summary>
 /// Connects to a named SQL Server using windows authentication
 /// </summary>
 /// <param name="ServerName"></param>
 public Server(string ServerName)
 {
     _server = new Microsoft.SqlServer.Management.Smo.Server(ServerName);
 }
Esempio n. 34
0
        protected override void DoWork(object state)
        {
            var mainCancellationTokenSource = new CancellationToken();

            try
            {
                var tasks          = new List <Task>();
                var deploymentJobs = _deploymentJobService.Get(p => p.Server.Code == ServerId &&
                                                               (p.MarkToRemove ?? false) &&
                                                               !(p.IsRemoveDone ?? false)).Take(3).ToList();

                if (!deploymentJobs.Any())
                {
                    return;
                }

                var listJobUpdated = new List <DeploymentJob>();

                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t        = Task.Factory.StartNew(() =>
                    {
                        //path
                        var serviceDest = localJob.Configuration.DestinationWindowServicePath;
                        var webDest     = localJob.Configuration.DestinationWebPath;
                        var webDestApi  = localJob.Configuration.DestinationWebApiPath;

                        //uninstall servie
                        if (localJob.JobType == (int)JobType.WindowService && Directory.Exists(serviceDest))
                        {
                            try
                            {
                                StopService(localJob.Configuration.ServiceName, serviceDest + @"\" + localJob.Configuration.ServiceFileName);
                                if (Directory.Exists(serviceDest))
                                {
                                    Directory.Delete(serviceDest, true);
                                }
                            }
                            catch (Exception exception)
                            {
                                _diagnosticService.Error(exception);
                            }
                        }

                        //unstall host
                        if (localJob.JobType == (int)JobType.WebApp)
                        {
                            if (!localJob.Configuration.WebDomainName.Contains("http"))
                            {
                                localJob.Configuration.WebDomainName = "http://" + localJob.Configuration.WebDomainName + "/";
                            }

                            var uri = new Uri(localJob.Configuration.WebDomainName);
                            _iisHostingHelper.RemoveHost(uri.Host);
                            if (Directory.Exists(webDest))
                            {
                                Directory.Delete(webDest, true);
                            }
                        }
                        if (localJob.JobType == (int)JobType.WebApi)
                        {
                            if (!localJob.Configuration.WebApiDomainName.Contains("http"))
                            {
                                localJob.Configuration.WebApiDomainName = "http://" + localJob.Configuration.WebApiDomainName + "/";
                            }

                            var uri = new Uri(localJob.Configuration.WebApiDomainName);
                            _iisHostingHelper.RemoveHost(uri.Host);
                            if (Directory.Exists(webDestApi))
                            {
                                Directory.Delete(webDestApi, true);
                            }
                        }

                        //delete database
                        if (localJob.JobType == (int)JobType.Database)
                        {
                            var conn   = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString);
                            var server = new Server(new ServerConnection(conn));
                            var db     = server.Databases[localJob.Configuration.DatabaseName];
                            if (db != null)
                            {
                                server.KillAllProcesses(localJob.Configuration.DatabaseName);
                                server.KillDatabase(localJob.Configuration.DatabaseName);
                                db.Drop();
                            }
                            var login = server.Logins[localJob.Configuration.DatabaseUsername];
                            if (login != null)
                            {
                                login.Drop();
                            }
                        }

                        localJob.IsCopySourceDone = false;
                        localJob.IsRemoveDone     = true;

                        listJobUpdated.Add(localJob);
                    }, mainCancellationTokenSource);

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray(), mainCancellationTokenSource);
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Esempio n. 35
0
File: Lib.cs Progetto: PavelPZ/REW
 public static void includeClrExtensionToDB(string servId) {
   string fn; string sql;
   using (var rdr = getInfo("WebCourseStatistics.sql", out fn)) sql = rdr.ReadToEnd();
   if (string.IsNullOrEmpty(sql)) return;
   var cb = getConnectionStringInfo(servId);
   sql = string.Format(sql, cb.UserID, servId == "lm-virtual-1_run" ? "NewLMComServices" : "NewLMCom", BitConverter.ToString(File.ReadAllBytes(fn)).Replace("-", ""));
   //File.WriteAllText(@"d:\temp\pom.sql", sql);
   Microsoft.SqlServer.Management.Common.ServerConnection connection = new Microsoft.SqlServer.Management.Common.ServerConnection(cb.DataSource, cb.UserID, cb.Password);
   Microsoft.SqlServer.Management.Smo.Server serv = new Microsoft.SqlServer.Management.Smo.Server(connection);
   serv.ConnectionContext.ExecuteNonQuery(sql);
   serv.ConnectionContext.ExecuteNonQuery("go");
 }
Esempio n. 36
0
 /// <summary>
 /// Connects to a named SQL Server with a user name and password
 /// </summary>
 /// <param name="ServerName"></param>
 /// <param name="UserName"></param>
 /// <param name="Password"></param>
 public Server(string ServerName, string UserName, string Password)
 {
     ServerConnection cn = new ServerConnection(ServerName, UserName, Password);
     _server = new Microsoft.SqlServer.Management.Smo.Server(cn);
 }
        public static bool ExecuteSQL(string sql)
        {
            Microsoft.SqlServer.Management.Smo.Server server = null;
            Microsoft.SqlServer.Management.Common.ServerConnection svrConnection = null;
            System.Data.SqlClient.SqlConnection sqlConnection = null;
            try
            {
                sqlConnection = new System.Data.SqlClient.SqlConnection(DataSDMX.SQLConnString_DB.ConnectionString);

                svrConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);

                server = new Microsoft.SqlServer.Management.Smo.Server(svrConnection);

                server.ConnectionContext.ExecuteNonQuery(sql);
                server.ConnectionContext.ForceDisconnected();
                return true;
            }
            catch (Exception ex)
            {
                if (server != null)
                {
                    server.ConnectionContext.ForceDisconnected();
                }
                return false;
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Enable File Streaming on the MediaDbContext
        /// </summary>
        public static void Enable( )
        {
            Log.Info("Enabling Sql File Streaming");

            // TODO: Configurable?
            const string fileGroupName = "fg";
            const string dataFileName  = "file";

            // Get the Connection String to the Media DbContext
            var mediaDbConnectionString = new SqlConnectionStringBuilder(ContextConnectionStringManager.Get(ContextNames.Media));

            // Get the server name from the connection string.
            var mediaDbDatasource = mediaDbConnectionString.DataSource;

            // Get the catalog name of the media database.
            var mediaDbDatabaseName = mediaDbConnectionString.InitialCatalog;

            // Connect with SMO.
            var server = new Microsoft.SqlServer.Management.Smo.Server(mediaDbDatasource);

            server.ConnectionContext.AutoDisconnectMode = Microsoft.SqlServer.Management.Common.AutoDisconnectMode.NoAutoDisconnect;

            // Determine the Filestream directory.
            var          serverName          = server.ComputerNamePhysicalNetBIOS;
            const string filestreamPathLocal = @"C:\TriTech\InformRMS\Data\FileStream"; // TODO: Derive from input options.
            var          isLocalDeploy       = IsHostLocal(serverName);
            var          filestreamPathUnc   = isLocalDeploy ? "" : String.Format(@"\\{0}\{1}", serverName, filestreamPathLocal.Replace(':', '$'));

            // Create the Filestream directory, if necessary.
            var filestreamDirectory = isLocalDeploy
                ? Path.GetDirectoryName(filestreamPathLocal)
                : Path.GetDirectoryName(filestreamPathUnc);

            if (!Directory.Exists(filestreamDirectory))
            {
                Directory.CreateDirectory(filestreamDirectory);
            }

            // Update the Filestream access level, if necessary. This is required before Filestream is enabled on a database.
            const int target = (int)Microsoft.SqlServer.Management.Smo.FilestreamAccessLevelType.FullAccess;

            if (server.Configuration.FilestreamAccessLevel.ConfigValue != target)
            {
                Log.Info("Changing Filestream access level to: {0}", target);
                server.Configuration.FilestreamAccessLevel.ConfigValue = target;
                server.Configuration.Alter();
            }

            // Manually create the database from the context.
            // We need to do this because Filestream has to be enabled on the database before we can create Filestream columns.
            var database = server.Databases
                           .Cast <Microsoft.SqlServer.Management.Smo.Database>()
                           .FirstOrDefault(x => x.Name.Equals(mediaDbDatabaseName, StringComparison.OrdinalIgnoreCase));

            if (database == null)
            {
                Log.Info("Creating database {0}.", mediaDbDatabaseName);
                database = new Microsoft.SqlServer.Management.Smo.Database(server, mediaDbDatabaseName);
                database.Create();
            }

            // Create a FileGroup for Filestream data, if necessary.
            if (String.IsNullOrWhiteSpace(database.FilestreamDirectoryName))
            {
                var fg = new Microsoft.SqlServer.Management.Smo.FileGroup(database, fileGroupName, true);
                fg.Create();

                var file = new Microsoft.SqlServer.Management.Smo.DataFile(fg, dataFileName, filestreamPathLocal);
                file.Create();
            }

            // Disconnect.
            server.ConnectionContext.Disconnect();

            // Attempt to determine if FileStreaming is already setup
            var result = SqlScripting.ExecuteNonQuery(mediaDbConnectionString.ToString(), @"
                SELECT OBJECT_NAME(object_id) AS TableName, name AS ColumnName
                FROM sys.columns
                WHERE is_filestream = 1 AND OBJECT_NAME(object_id) = 'MEDIASTORAGES' AND name = 'MEDIA'");

            // The Drop Column will fail if the table is already setup with File Streaming.
            // Make sure we only execute the script if the FileStream is not already setup.
            if (result < 1)
            {
                // Enable Filestream on the MediaStorages table.
                SqlScripting.ExecuteScript(mediaDbConnectionString.ToString(), @"
                -- Filestream-enabled tables must have a RowGuidCol column. This cannot be added through fluent mapping.
                alter table [dbo].[MediaStorages] drop column [MediaGuid]
                alter table [dbo].[MediaStorages] add [MediaGuid] UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWID()

                -- Manually create the filestream column. NOTE: SQL will not allow the FILESTREAM attribute to be added to an existing column, and the column must be created as part of the model (so it can be accessed via code), so drop and recreate it here.
                alter table [dbo].[MediaStorages] drop column [Media]
                alter table [dbo].[MediaStorages] add [Media] varbinary(max) FILESTREAM null");
            }
        }
Esempio n. 39
0
        public static List <DbTable> FromDB(string dbName)
        {
            var tables            = new List <DbTable>();
            var dicReferenceTable = new Dictionary <string, List <Reference> >();

            var server = new Microsoft.SqlServer.Management.Smo.Server(serverName);
            var db     = new Microsoft.SqlServer.Management.Smo.Database(server, dbName);

            db.Refresh();
            foreach (Microsoft.SqlServer.Management.Smo.Table table in db.Tables)
            {
                table.Refresh();

                var dic = new Dictionary <string, string>();

                foreach (Microsoft.SqlServer.Management.Smo.ForeignKey item in table.ForeignKeys)
                {
                    dic.Add(item.Columns[0].Name, item.ReferencedTable);

                    if (dicReferenceTable.ContainsKey(item.ReferencedTable) == false)
                    {
                        dicReferenceTable.Add(item.ReferencedTable, new List <Reference>());
                    }

                    dicReferenceTable[item.ReferencedTable].Add(new Reference()
                    {
                        PropertyName       = table.Name + item.Columns[0].Name,
                        ReferenceTableName = table.Name
                    });
                }

                var indexes     = GetIndexes(table);
                var foreignKeys = GetForeignKey(table);

                var columns            = new List <DbTableColumn>();
                var requiredMaxLengths = new List <RequiredMaxLength>();
                var defaultValues      = new List <DefaultValue>();
                var hasColumnTypes     = new List <HasColumnType>();

                foreach (Microsoft.SqlServer.Management.Smo.Column item in table.Columns)
                {
                    var propertyType = _typeMapping[item.DataType.Name];
                    if (item.Nullable == true && propertyType != "string")
                    {
                        propertyType = propertyType + "?";
                    }

                    var entityProperty = new DbTableColumn()
                    {
                        DataType     = propertyType,
                        ColumnName   = item.Name,
                        IsForeignKey = item.IsForeignKey,
                        IsPrimaryKey = item.InPrimaryKey,
                        IsIdentity   = item.Identity
                    };
                    if (item.IsForeignKey == true)
                    {
                        entityProperty.ForeignKeyTableName = dic[item.Name];
                    }
                    columns.Add(entityProperty);

                    //hascolumntype
                    if (entityProperty.DataType == "System.DateTime" ||
                        entityProperty.DataType == "System.TimeSpan")
                    {
                        hasColumnTypes.Add(new HasColumnType()
                        {
                            PropertyName = item.Name,
                            TypeName     = item.DataType.Name + "(" + item.DataType.NumericScale + ")"
                        });
                    }
                    else if (item.DataType.Name == "decimal" || item.DataType.Name == "numeric")
                    {
                        hasColumnTypes.Add(new HasColumnType()
                        {
                            PropertyName = item.Name,
                            TypeName     = item.DataType.Name + "(" + item.DataType.NumericPrecision + "," + item.DataType.NumericScale + ")"
                        });
                    }

                    //requiredmaxlength
                    var requiredMaxLength = new RequiredMaxLength()
                    {
                        PropertyName = item.Name, MaxLength = -1
                    };
                    if (item.Nullable == false && propertyType == "string")
                    {
                        requiredMaxLength.NeedIsRequired = true;
                    }
                    if (propertyType == "string" || propertyType == "byte[]")
                    {
                        requiredMaxLength.MaxLength = item.DataType.MaximumLength;
                    }
                    if (requiredMaxLength.NeedIsRequired == true || requiredMaxLength.MaxLength > 0)
                    {
                        requiredMaxLengths.Add(requiredMaxLength);
                    }

                    //defaultvalue
                    if (item.DefaultConstraint != null)
                    {
                        defaultValues.Add(new DefaultValue()
                        {
                            PropertyName = item.Name,
                            Value        = item.DefaultConstraint.Text
                        });
                    }
                }

                tables.Add(new DbTable()
                {
                    TableName          = table.Name,
                    Columns            = new ObservableCollection <DbTableColumn>(columns),
                    ForeignKeys        = new ObservableCollection <ForeignKey>(foreignKeys),
                    Indexes            = new ObservableCollection <Index>(indexes),
                    RequiredMaxLengths = new ObservableCollection <RequiredMaxLength>(requiredMaxLengths),
                    DefaultValues      = new ObservableCollection <DefaultValue>(defaultValues),
                    HasColumnTypes     = new ObservableCollection <HasColumnType>(hasColumnTypes)
                });
            }

            foreach (var table in tables)
            {
                List <Reference> reference;
                if (dicReferenceTable.TryGetValue(table.TableName, out reference) == true)
                {
                    table.ReferencesToThisTable = new ObservableCollection <Reference>(reference);
                }
            }
            return(tables);
        }
Esempio n. 40
0
        public bool CreateDatabase()
        {
            bool          done       = true;
            List <string> script     = new List <string>();
            string        datasource = "";

            try
            {
                datasource = Properties.Settings.Default.Servidor;
            }
            catch { }

            string sqlConnectionString = "Data Source=" + datasource + ";Initial Catalog=master;Integrated Security=True";

            try
            {
                string path4;
                path4 = System.IO.Path.GetDirectoryName(
                    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                path4 = path4 + "\\myscript.sql";
                path4 = path4.Replace("file:\\", "");
                string cmdText = ("SELECT SUBSTRING(filename, 1, CHARINDEX(N'master.mdf', LOWER(filename)) - 1) FROM master.dbo.sysdatabases WHERE name = 'master'");
                string path    = "";

                using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                {
                    sqlConnection.Open();
                    using (SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection))
                    {
                        var path1 = sqlCmd.ExecuteScalar();

                        path = Convert.ToString(path1);
                    }
                }

                string mdf = "N'" + path + b_KnowLedge.Properties.Settings.Default.BDName + "_data.mdf'";
                string ldf = "N'" + path + b_KnowLedge.Properties.Settings.Default.BDName + "_log.ldf'";

                string[] lines = System.IO.File.ReadAllLines(path4);
                string   aux   = "";
                foreach (string line in lines)
                {
                    aux = line;
                    aux = aux.Replace("@PathMdf", mdf);
                    aux = aux.Replace("@PathLdf", ldf);
                    aux = aux.Replace("@DatabaseName", b_KnowLedge.Properties.Settings.Default.BDName);
                    aux = Regex.Replace(aux, "([/*][*]).*([*][/])", " ");
                    script.Add(aux);
                }

                SqlConnection conn = new SqlConnection(sqlConnectionString);
                conn.Open();
                string query = "";
                foreach (string line in script)
                {
                    if (line == "GO")
                    {
                        Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
                        server.ConnectionContext.ExecuteNonQuery(query);
                        query = "";
                    }
                    else
                    {
                        query += " " + line;
                    }
                }
                conn.Close();
            }
            catch
            {
                done = false;
            }


            return(done);
        }
Esempio n. 41
0
        private static void GenerateScript(SqlConnectionStringBuilder builderTenantLocal, string databaseTenantLiveName, FileInfo fileScript, Encoding encoding)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"GenerateScript.");

            var tableNames = new string[] { "__MigrationHistory", "Culture", "Department", "Folder", "Subscription", "Tenant", "TenantSubscription", "Role", "User", "UserFolder", "UserRole", "RoleUsers", };

            using (var connection = new SqlConnection(builderTenantLocal.ConnectionString))
            {
                var scriptDataInsert   = "";
                var scriptSchemaDrop   = "";
                var scriptSchemaCreate = "";
                var serverConnection   = new Microsoft.SqlServer.Management.Common.ServerConnection(connection);
                var server             = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
                var database           = server.Databases[builderTenantLocal.InitialCatalog];
                var scripter           = new Microsoft.SqlServer.Management.Smo.Scripter(server);
                var tables             = new Microsoft.SqlServer.Management.Smo.UrnCollection();

                File.WriteAllText(fileScript.FullName, $"USE [{databaseTenantLiveName}]{Environment.NewLine}{Environment.NewLine}", encoding);

                tables.Clear();
                scripter.Options.ScriptDrops            = true;
                scripter.Options.ScriptSchema           = true;
                scripter.Options.ScriptData             = false;
                scripter.Options.WithDependencies       = true;
                scripter.Options.DriAllConstraints      = true;
                scripter.Options.NoCommandTerminator    = true;
                scripter.Options.IncludeDatabaseContext = false;
                scripter.Options.FileName           = fileScript.FullName;
                scripter.Options.AppendToFile       = true;
                scripter.Options.ToFileOnly         = false;
                scripter.Options.IncludeHeaders     = true;
                scripter.Options.IncludeIfNotExists = true;
                scripter.Options.PrimaryObject      = true;
                scripter.Options.ExtendedProperties = true;
                scripter.Options.Encoding           = encoding;
                foreach (Microsoft.SqlServer.Management.Smo.Table table in database.Tables)
                {
                    tables.Add(table.Urn);
                }
                scriptSchemaDrop = string.Join(Environment.NewLine, scripter.EnumScript(tables));

                tables.Clear();
                scripter.Options.ScriptDrops            = false;
                scripter.Options.ScriptSchema           = true;
                scripter.Options.ScriptData             = false;
                scripter.Options.WithDependencies       = true;
                scripter.Options.DriAllConstraints      = true;
                scripter.Options.NoCommandTerminator    = true;
                scripter.Options.IncludeDatabaseContext = false;
                scripter.Options.FileName           = fileScript.FullName;
                scripter.Options.AppendToFile       = true;
                scripter.Options.ToFileOnly         = false;
                scripter.Options.IncludeHeaders     = true;
                scripter.Options.IncludeIfNotExists = true;
                scripter.Options.PrimaryObject      = true;
                scripter.Options.ExtendedProperties = true;
                scripter.Options.Encoding           = encoding;
                foreach (Microsoft.SqlServer.Management.Smo.Table table in database.Tables)
                {
                    tables.Add(table.Urn);
                }
                scriptSchemaCreate = string.Join(Environment.NewLine, scripter.EnumScript(tables));

                tables.Clear();
                scripter.Options.ScriptDrops            = false;
                scripter.Options.ScriptSchema           = false;
                scripter.Options.ScriptData             = true;
                scripter.Options.WithDependencies       = true;
                scripter.Options.DriAllConstraints      = true;
                scripter.Options.NoCommandTerminator    = true;
                scripter.Options.IncludeDatabaseContext = false;
                scripter.Options.FileName           = fileScript.FullName;
                scripter.Options.AppendToFile       = true;
                scripter.Options.ToFileOnly         = false;
                scripter.Options.IncludeHeaders     = true;
                scripter.Options.IncludeIfNotExists = true;
                scripter.Options.PrimaryObject      = true;
                scripter.Options.ExtendedProperties = true;
                scripter.Options.Encoding           = encoding;
                foreach (var tableName in tableNames)
                {
                    tables.Add(database.Tables[tableName].Urn);
                }
                scriptDataInsert = string.Join(Environment.NewLine, scripter.EnumScript(tables));
            }
        }
Esempio n. 42
0
        public static List <DbTable> FromDB(string dbName, string serverName, string user = null, SecureString pass = null)
        {
            var tables            = new List <DbTable>();
            var dicReferenceTable = new Dictionary <string, List <Reference> >();

            var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(serverName);

            if (string.IsNullOrEmpty(user) == false)
            {
                serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(serverName, user, pass);
            }

            var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
            var db     = new Microsoft.SqlServer.Management.Smo.Database(server, dbName);

            db.Refresh();
            foreach (Microsoft.SqlServer.Management.Smo.Table table in db.Tables)
            {
                table.Refresh();

                var dic = new Dictionary <string, string>();

                foreach (Microsoft.SqlServer.Management.Smo.ForeignKey item in table.ForeignKeys)
                {
                    dic.Add(item.Columns[0].Name, item.ReferencedTable);

                    if (dicReferenceTable.ContainsKey(item.ReferencedTable) == false)
                    {
                        dicReferenceTable.Add(item.ReferencedTable, new List <Reference>());
                    }

                    dicReferenceTable[item.ReferencedTable].Add(new Reference()
                    {
                        PropertyName       = item.Columns[0].Name,
                        ReferenceTableName = table.Name
                    });
                }

                var indexes     = GetIndexes(table);
                var foreignKeys = GetForeignKey(table);

                var columns            = new List <DbTableColumn>();
                var requiredMaxLengths = new List <RequiredMaxLength>();
                var defaultValues      = new List <DefaultValue>();
                var hasColumnTypes     = new List <HasColumnType>();

                foreach (Microsoft.SqlServer.Management.Smo.Column item in table.Columns)
                {
                    var sqlDataType = item.DataType.Name;
                    var dotnetType  = _typeMapping[sqlDataType];
                    if (item.Nullable == true && dotnetType != "string" && dotnetType != "byte[]")
                    {
                        dotnetType = dotnetType + "?";
                    }

                    var entityProperty = new DbTableColumn()
                    {
                        DataType     = dotnetType,
                        ColumnName   = item.Name,
                        IsForeignKey = item.IsForeignKey,
                        IsPrimaryKey = item.InPrimaryKey,
                        IsIdentity   = item.Identity
                    };
                    if (item.IsForeignKey == true)
                    {
                        entityProperty.ForeignKeyTableName = dic[item.Name];
                    }
                    columns.Add(entityProperty);

                    //hascolumntype
                    if (sqlDataType == "decimal" ||
                        sqlDataType == "numeric" ||
                        sqlDataType == "datetime2" ||
                        sqlDataType == "datetimeoffset" ||
                        sqlDataType == "time")
                    {
                        hasColumnTypes.Add(new HasColumnType()
                        {
                            PropertyName     = item.Name,
                            TypeName         = sqlDataType,
                            NumericPrecision = item.DataType.NumericPrecision,
                            NumericScale     = item.DataType.NumericScale
                        });
                    }

                    //requiredmaxlength
                    var requiredMaxLength = new RequiredMaxLength()
                    {
                        PropertyName = item.Name, MaxLength = -1
                    };
                    if (item.Nullable == false && dotnetType == "string")
                    {
                        requiredMaxLength.NeedIsRequired = true;
                    }
                    if (dotnetType == "string" || dotnetType == "byte[]")
                    {
                        requiredMaxLength.MaxLength = item.DataType.MaximumLength;
                    }
                    if (requiredMaxLength.NeedIsRequired == true || requiredMaxLength.MaxLength > 0)
                    {
                        requiredMaxLengths.Add(requiredMaxLength);
                    }

                    //defaultvalue
                    if (item.DefaultConstraint != null)
                    {
                        defaultValues.Add(new DefaultValue()
                        {
                            PropertyName = item.Name,
                            Value        = item.DefaultConstraint.Text
                        });
                    }
                }

                var t = new DbTable()
                {
                    TableName          = table.Name,
                    Columns            = new ObservableCollection <DbTableColumn>(columns),
                    ForeignKeys        = new ObservableCollection <ForeignKey>(foreignKeys),
                    Indexes            = new ObservableCollection <Index>(indexes),
                    RequiredMaxLengths = new ObservableCollection <RequiredMaxLength>(requiredMaxLengths),
                    DefaultValues      = new ObservableCollection <DefaultValue>(defaultValues),
                    HasColumnTypes     = new ObservableCollection <HasColumnType>(hasColumnTypes)
                };

                if (table.Name.StartsWith("Smt"))
                {
                    t.IsSelected = false;
                }
                else
                {
                    t.IsSelected = true;
                }

                tables.Add(t);
            }

            foreach (var table in tables)
            {
                List <Reference> reference;
                if (dicReferenceTable.TryGetValue(table.TableName, out reference) == true)
                {
                    table.ReferencesToThisTable = new ObservableCollection <Reference>(reference);
                }
                else
                {
                    table.ReferencesToThisTable = new ObservableCollection <Reference>();
                }
            }

            CalculateReferenceLevel(tables);

            return(tables);
        }
Esempio n. 43
-1
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //��������
            DataBaseFrm objOwner = (DataBaseFrm)this.Owner;
            //�������ݲ��ԣ��ж��Ƿ���Ȩ��
            Microsoft.SqlServer.Management.Smo.Server server;
            if (cmbSQLValidModeSelect.SelectedIndex == 0)
            {
            #if DEBUG
                server = new Microsoft.SqlServer.Management.Smo.Server(cmbServerSelect.Text);
            #else
                server = new Microsoft.SqlServer.Management.Smo.Server(cmbServerSelect.Text);
            #endif
            }
            else
            {
            #if DEBUG
                server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(cmbServerSelect.Text, cmbAccountSelect.Text, txtPassword.Text));
            #else
                server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(cmbServerSelect.Text, cmbAccountSelect.Text, txtPassword.Text));
            #endif
            }

            MainFrm.CurrentConnection.IsWindowAuth = cmbSQLValidModeSelect.SelectedIndex == 0;
            MainFrm.CurrentConnection.ServerAddress = cmbServerSelect.Text;
            MainFrm.CurrentConnection.UserName = cmbAccountSelect.Text;
            MainFrm.CurrentConnection.Password = txtPassword.Text;

            objOwner.AddServer(server);
            this.DialogResult = DialogResult.OK;
        }