本文整理汇总了C#中Server.SetDefaultInitFields方法的典型用法代码示例。如果您正苦于以下问题:C# Server.SetDefaultInitFields方法的具体用法?C# Server.SetDefaultInitFields怎么用?C# Server.SetDefaultInitFields使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Server
的用法示例。
在下文中一共展示了Server.SetDefaultInitFields方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Connect
public Database Connect(string connectionString)
{
var connection = new ServerConnection { ConnectionString = connectionString };
var server = new Server(connection);
server.SetDefaultInitFields(typeof(Table), "IsSystemObject");
server.SetDefaultInitFields(typeof(View), "IsSystemObject");
server.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject");
server.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject");
server.SetDefaultInitFields(typeof(Trigger), "IsSystemObject");
if (server.Version.Major < 9)
throw new UnsupportedVersionException("SQL Server 2005 or greater is required.");
return server.Databases[connection.SqlConnectionObject.Database];
}
示例2: DatabaseDefrag_Load
private void DatabaseDefrag_Load(object sender, EventArgs e)
{
ServerConnection ServerConn;
ServerConnect scForm;
DialogResult dr;
Cursor csr = null;
try
{
csr = this.Cursor; // Save the old cursor
this.Cursor = Cursors.WaitCursor; // Display the waiting cursor
// Display the main window first
this.Show();
Application.DoEvents();
ServerConn = new ServerConnection();
scForm = new ServerConnect(ServerConn);
dr = scForm.ShowDialog(this);
if ((dr == DialogResult.OK) &&
(ServerConn.SqlConnectionObject.State == ConnectionState.Open))
{
SqlServerSelection = new Server(ServerConn);
if (SqlServerSelection != null)
{
this.Text = Properties.Resources.AppTitle
+ SqlServerSelection.Name;
// Limit the table properties returned to just those that we use
SqlServerSelection.SetDefaultInitFields(typeof(Table),
new String[] { "Schema", "Name", "IsSystemObject" });
ShowDatabases(true);
}
}
else
{
this.Close();
}
}
catch (SmoException ex)
{
ExceptionMessageBox emb = new ExceptionMessageBox(ex);
emb.Show(this);
}
finally
{
this.Cursor = csr; // Restore the original cursor
}
}
示例3: IndexSizes_Load
private void IndexSizes_Load(object sender, EventArgs e)
{
ServerConnection ServerConn;
ServerConnect scForm;
DialogResult dr;
// Display the main window first
this.Show();
Application.DoEvents();
ServerConn = new ServerConnection();
scForm = new ServerConnect(ServerConn);
dr = scForm.ShowDialog(this);
if ((dr == DialogResult.OK) &&
(ServerConn.SqlConnectionObject.State == ConnectionState.Open))
{
SqlServerSelection = new Server(ServerConn);
if (SqlServerSelection != null)
{
this.Text = Properties.Resources.AppTitle
+ SqlServerSelection.Name;
// Limit the properties returned to just those that we use
SqlServerSelection.SetDefaultInitFields(typeof(Table),
new String[] { "Schema", "Name", "IsSystemObject" });
SqlServerSelection.SetDefaultInitFields(typeof(Index),
new String[] { "Name", "IndexKeyType", "SpaceUsed" });
ShowDatabases(true);
}
}
else
{
this.Close();
}
}
示例4: GenerateScripts
/// <summary>
/// does all the work.
/// </summary>
/// <param name="connStr"></param>
/// <param name="outputDirectory"></param>
/// <param name="dataScriptingFormat"></param>
/// <param name="verbose"></param>
/// <param name="scriptAllDatabases"></param>
/// <param name="purgeDirectory"></param>
/// <param name="scriptProperties"></param>
public void GenerateScripts(string outputDirectory,
bool scriptAllDatabases, bool purgeDirectory,
DataScriptingFormat dataScriptingFormat, bool verbose, bool scriptProperties)
{
var connection = new SqlConnection(ConnectionString);
var sc = new ServerConnection(connection);
var s = new Server(sc);
s.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(Table), "IsSystemObject");
s.SetDefaultInitFields(typeof(View), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(DatabaseDdlTrigger), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(Schema), "IsSystemObject");
s.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql;
RunCommand(StartCommand, verbose, outputDirectory, s.Name, null);
// Purge at the Server level only when we're doing all databases
if (purgeDirectory && scriptAllDatabases && outputDirectory != null && Directory.Exists(outputDirectory))
{
if (verbose) Console.Error.Write("Purging directory...");
PurgeDirectory(outputDirectory, "*.sql");
if (verbose) Console.Error.WriteLine("Done");
}
if (!string.IsNullOrEmpty(OutputFileName) && File.Exists(OutputFileName))
{
try
{
File.Delete(OutputFileName);
}
catch (Exception e)
{
Console.Error.Write("Error deleting output file {0}: {1}", OutputFileName, e.Message);
}
}
if (scriptAllDatabases)
{
foreach (Database db in s.Databases)
{
try
{
RunCommand(PreScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
GenerateDatabaseScript(db, outputDirectory, purgeDirectory, dataScriptingFormat, verbose, scriptProperties, s);
RunCommand(PostScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
}
catch (Exception e)
{
Console.Error.WriteLine("Exception: {0}", e.Message);
}
}
}
else
{
//var db = s.Databases[connection.Database]; // Doesn't fix the case of the database name.
var db = s.Databases.Cast<Database>().Single(d => String.Equals(d.Name, connection.Database, StringComparison.InvariantCultureIgnoreCase));
if(db == null)
{
throw new Exception(string.Format("Database '{0}' was not found", connection.Database));
}
RunCommand(PreScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
GenerateDatabaseScript(db, outputDirectory, purgeDirectory,
dataScriptingFormat, verbose, scriptProperties, s);
RunCommand(PostScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
}
RunCommand(FinishCommand, verbose, outputDirectory, s.Name, null);
}
示例5: ExportData
public void ExportData(string connectionString, string outputDirectory, bool verbose)
{
ScriptingOptions _options = new ScriptingOptions()
{
AllowSystemObjects = false,
ScriptData = true,
ScriptSchema = false
};
// connection
using (SqlConnection _connection = new SqlConnection(connectionString))
{
ServerConnection _serverConn = new ServerConnection(_connection);
Server _server = new Server(_serverConn);
_server.SetDefaultInitFields(typeof(Table), "IsSystemObject");
Database _db = _server.Databases[_connection.Database];
Scripter _scripter = new Scripter(_server);
_scripter.Options = _options;
foreach (Table _table in _db.Tables)
{
if (!_table.IsSystemObject)
{
string _outputPath = this.CreateOutputFile(outputDirectory, _table);
this.ScriptTable(_scripter, _table, _outputPath, false);
}
}
}
}
示例6: bwCalculation_DoWork
private void bwCalculation_DoWork(object sender, DoWorkEventArgs e)
{
_workCompletedWithoutError = false;
var conn = new ServerConnection(ConnectionManager.GetInstance().GetSqlConnection());
//myLog.WriteEntry("--connection--"+conn.ToString());
try
{
_sbScript = new StringBuilder();
var server = new Server(conn);
//myLog.WriteEntry("--server initalized--" + server.ToString());
var db = server.Databases[AppSettings.DatabaseName];
//myLog.WriteEntry("--get db--" + db.ToString());
//myLog.WriteEntry("--sp contain check--" + db.StoredProcedures.Contains("sp_generate_inserts").ToString());
if (!db.StoredProcedures.Contains("sp_generate_inserts"))
{
// myLog.WriteEntry("--get into spgenerate and call SpGenerate--" );
try
{
db.ExecuteNonQuery(SpGenerate());
}
catch(Exception ex)
{
//myLog.WriteEntry("--error on excute SpGenerate()--"+ex.Message+"--trace--"+ex.StackTrace+"--spgenerate out--"+SpGenerate());
}
}
var scripter = new Scripter(server);
//myLog.WriteEntry("--scripter initalized--" + scripter.ToString());
scripter.ScriptingProgress += new ProgressReportEventHandler(ScriptingProgressEventHandler);
var so = new ScriptingOptions
{
IncludeIfNotExists = false,
IncludeHeaders = false,
Permissions = false,
ExtendedProperties = false,
ScriptDrops = false,
IncludeDatabaseContext = false,
NoCollation = false,
NoFileGroup = false,
NoIdentities = false,
TargetServerVersion = SqlServerVersion.Version90
};
scripter.Options = so;
SetProgressBarText(1);
SetProgressBarValue(0);
//myLog.WriteEntry("--scripter options set--" + scripter.Options.ToString());
this.Invoke(new MethodInvoker(() => progressBar1.Maximum = db.Tables.Count));
server.SetDefaultInitFields(typeof (Table), "IsSystemObject");
//myLog.WriteEntry("--init start looping tables--");
foreach (Table tb in db.Tables)
{
//myLog.WriteEntry("--start looping tables--" + tb.Name);
ProgressBarPerformStep();
if (!tb.IsSystemObject)
{
_sbScript.Append(ScriptObject(new Urn[] {tb.Urn}, scripter));
}
}
SetProgressBarValue(0);
SetProgressBarText(2);
this.Invoke(new MethodInvoker(() => progressBar1.Maximum = db.UserDefinedFunctions.Count));
server.SetDefaultInitFields(typeof (UserDefinedFunction), "IsSystemObject");
foreach (UserDefinedFunction udf in db.UserDefinedFunctions)
{
ProgressBarPerformStep();
if (!udf.IsSystemObject)
{
_sbScript.Append(ScriptObject(new Urn[] {udf.Urn}, scripter));
}
}
SetProgressBarValue(0);
SetProgressBarText(3);
this.Invoke(new MethodInvoker(() => progressBar1.Maximum = db.StoredProcedures.Count));
server.SetDefaultInitFields(typeof (StoredProcedure), "IsSystemObject");
foreach (StoredProcedure sp in db.StoredProcedures)
{
ProgressBarPerformStep();
if (!sp.IsSystemObject)
{
_sbScript.Append(ScriptObject(new Urn[] {sp.Urn}, scripter));
}
}
SetProgressBarValue(0);
SetProgressBarText(4);
this.Invoke(new MethodInvoker(delegate
{
lblProgress.Text = "Script Views";
}));
server.SetDefaultInitFields(typeof (Microsoft.SqlServer.Management.Smo.View), "IsSystemObject");
List<SqlSmoObject> views = db.Views.Cast<View>().Cast<SqlSmoObject>().ToList();
var sviews = SortViews(db, views);
this.Invoke(new MethodInvoker(() => progressBar1.Maximum = sviews.Count));
//.........这里部分代码省略.........
示例7: TableAttributesList
//private const string Catalog = "3plogic";
//private const string Password = "Zebra99";
//private const string SystemName = "W500DEV";
//private const string Username = "sa";
/// <summary>
/// gets attributes of all tables
/// </summary>
/// <param name="tableNameToFind">if empty, get all tables, otherwise, just tablename specified</param>
/// <param name="connectionString"></param>
/// <returns></returns>
public static List<FullMeta> TableAttributesList(string tableNameToFind, string connectionString)
{
var results = new List<FullMeta>();
// Pull out of connectionString the Catalog
// Catalog=3plogic;
const string catalogSearchString = "Catalog=";
int pos1 = connectionString.IndexOf(catalogSearchString, StringComparison.Ordinal) + catalogSearchString.Length;
int pos2 = connectionString.Substring(pos1).IndexOf(";", StringComparison.Ordinal) + pos1;
string catalogName = connectionString.Substring(pos1, pos2 - pos1).ToLower();
using (var sqlConnection = new SqlConnection(connectionString))
{
var serverConnection =
new ServerConnection(sqlConnection);
var svr = new Server(serverConnection);
StringCollection sc = svr.GetDefaultInitFields(typeof (Table));
svr.SetDefaultInitFields(typeof (View), sc);
DatabaseCollection databaseCollection = svr.Databases;
if (databaseCollection.Count > 0)
{
foreach (Database database in databaseCollection)
{
// only process tables in our catalog
if (!database.Name.ToLower().Equals(catalogName))
{
continue;
}
TableCollection tableCollection = database.Tables;
foreach (Table table in tableCollection)
{
if (table.IsSchemaOwned && !table.IsSystemObject)
{
try
{
if (String.IsNullOrEmpty(tableNameToFind) ||
table.Name.ToLower().Equals(tableNameToFind.ToLower()))
{
string xml = CreateXMLFromTableSqlServer(table.Name, sqlConnection);
List<AttributeInfo> listAttributeInfo = ParseXMLForAttributes(xml);
results.Add(new FullMeta(database.Name, table.Name, listAttributeInfo));
}
}
catch (Exception)
{
// todo: figure out how to skip tables that are not ours
Debug.WriteLine("problem: " + table.Name);
}
}
}
}
}
}
return results;
}
示例8: GenerateScripts
/// <summary>
/// does all the work.
/// </summary>
/// <param name="connStr"></param>
/// <param name="outputDirectory"></param>
/// <param name="verbose"></param>
public void GenerateScripts(string connStr, string outputDirectory,
bool scriptAllDatabases, bool purgeDirectory,
bool scriptData, bool verbose, bool scriptProperties)
{
SqlConnection connection = new SqlConnection(connStr);
ServerConnection sc = new ServerConnection(connection);
Server s = new Server(sc);
s.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(Table), "IsSystemObject");
s.SetDefaultInitFields(typeof(View), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject", "IsEncrypted");
s.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql;
if (scriptAllDatabases)
{
foreach (Database db in s.Databases)
{
try
{
GenerateDatabaseScript(db, outputDirectory, purgeDirectory, scriptData, verbose, scriptProperties);
}
catch (Exception e)
{
if (verbose) Console.WriteLine("Exception: {0}", e.Message);
}
}
}
else
GenerateDatabaseScript(s.Databases[connection.Database], outputDirectory, purgeDirectory,
scriptData, verbose, scriptProperties);
}
示例9: ScriptDatabase
private static void ScriptDatabase(string server, string database, string directory)
{
var so = new ScriptingOptions
{
ScriptDrops = false,
IncludeIfNotExists = false,
ClusteredIndexes = true,
DriAll = true,
Indexes = true,
SchemaQualify = true,
Triggers = true,
AnsiPadding = false
};
var conn = GetConnection(server, database);
var srv = new Server(new ServerConnection(conn));
so.TargetServerVersion = GetTargetServerVersion(srv);
var db = srv.Databases[database];
srv.SetDefaultInitFields(typeof (StoredProcedure), "IsSystemObject");
#region Tables
var objectDir = Path.Combine(directory, "Tables");
RemoveSqlFiles(objectDir);
foreach (Table t in db.Tables)
{
if (t.IsSystemObject) continue;
string fileName = null;
StringCollection sc = null;
if (_verbose)
Log.Info("Table: " + t.Name);
try
{
sc = t.Script(so);
}
catch (Exception e)
{
Log.ErrorFormat("Failed To Script Table: {0}",t.Name);
if (_verbose)
Log.Error(e);
}
try
{
fileName = Path.Combine(objectDir, t.Schema + "." + t.Name + ".sql");
}
catch (Exception e)
{
Log.ErrorFormat("Failed To Script Table: {0}", t.Name);
if (_verbose)
Log.Error(e);
}
WriteFile(sc, fileName, true);
}
#endregion
#region Stored Procedures
objectDir = Path.Combine(directory, "Sprocs");
RemoveSqlFiles(objectDir);
foreach (StoredProcedure sp in db.StoredProcedures)
{
string fileName = null;
StringCollection sc = null;
if (sp.IsSystemObject) continue;
if (_verbose)
Log.Info("Sproc: " + sp.Name);
try
{
sc = sp.Script(so);
}
catch (Exception e)
{
Log.ErrorFormat("Failed To Script Procedure: {0}", sp.Name);
if (_verbose)
Log.Error(e);
}
try
{
fileName = Path.Combine(objectDir, sp.Schema + "." + sp.Name + ".sql");
}
catch (Exception e)
{
Log.ErrorFormat("Failed To Script Procedure: {0}", sp.Name);
if (_verbose)
Log.Error(e);
}
WriteFile(sc, fileName, true);
}
#endregion
#region User-defined data types
//.........这里部分代码省略.........
示例10: ScriptFunctions
private void ScriptFunctions()
{
try
{
#region Options
ScriptingOptions so = new ScriptingOptions();
so.NoExecuteAs = true;
so.ScriptDrops = false;
so.SchemaQualify = true;
so.AllowSystemObjects = false;
#endregion
Server srv = new Server();
Database db = GetDatabase(ref srv);
srv.SetDefaultInitFields(typeof(View), "IsSystemObject");
UrnCollection urns = new UrnCollection();
foreach (UserDefinedFunction v in db.UserDefinedFunctions)
{
// exclude these objects
if (v.IsSystemObject) continue;
if (v.Name.StartsWith("aspnet_")) continue;
urns.Add(v.Urn);
}
string filepath = Path.Combine(ScriptPath, FunctionDirectory);
CreateDirectory(filepath);
StringCollection FileCollection = new StringCollection();
CreateDirectory(filepath);
if (urns.Count > 0)
{
DependencyWalker depwalker = new Microsoft.SqlServer.Management.Smo.DependencyWalker(srv);
DependencyTree tree = depwalker.DiscoverDependencies(urns, true);
DependencyCollection depcoll = depwalker.WalkDependencies(tree);
foreach (DependencyCollectionNode dep in depcoll)
{
if (dep.Urn.Type == "UserDefinedFunction")
{
foreach (UserDefinedFunction t in db.UserDefinedFunctions)
{
if (t.Name.ToString() == dep.Urn.GetAttribute("Name").ToString())
{
if (!t.IsEncrypted)
{
string functionFilePath = Path.Combine(filepath, t.Schema + "." + t.Name.ToString() + ".sql");
so.ScriptDrops = true;
StringCollection drop = t.Script(so);
so.ScriptDrops = false;
StringCollection create = t.Script();
StringCollection sc = new StringCollection();
sc.Add("IF EXISTS(SELECT * FROM SYSOBJECTS WHERE XTYPE='FN' AND NAME='" + t.Name.ToString() + "')\r\nBEGIN\r\n");
foreach (string s in drop)
{
sc.Add(s);
}
sc.Add("\r\nEND\r\nGO\r\n");
foreach (string s in create)
{
sc.Add(s);
sc.Add("GO\r\n");
}
WriteFile(functionFilePath, sc);
string relativeFunctionFilePath = this.BuildRelativeFilePath(functionFilePath);
FileCollection.Add(relativeFunctionFilePath); // We want a relative path here.
WriteStatus("File written: " + relativeFunctionFilePath);
break;
}
else
{
WriteStatus("WARNING: Function is NOT scripted. It was found to be encrypted and cannot be scripted. (" + t.Name + ")");
}
}
}
}
}
//string functionListFilePath = this.BuildScriptFilePath(FunctionDirectory,FunctionsFile);
//WriteFile(functionListFilePath, FileCollection);
//string relativeFunctionListFilePath = this.BuildRelativeFilePath(functionListFilePath);
//WriteStatus("File written: " + relativeFunctionListFilePath);
} //if urns.Count > 0
string functionListFilePath = this.BuildScriptFilePath(FunctionDirectory, FunctionsFile);
WriteFile(functionListFilePath, FileCollection);
string relativeFunctionListFilePath = this.BuildRelativeFilePath(functionListFilePath);
WriteStatus("File written: " + relativeFunctionListFilePath);
}
catch (Exception err)
{
WriteStatus(Thread.CurrentThread.ThreadState.ToString());
if (Thread.CurrentThread.ThreadState != ThreadState.AbortRequested)
{
WriteStatus("An error may have been encountered. Please check the log file for more details.");
MMDB.Core.MMDBLogFile.Log(err, "ScriptFunction");
throw new FunctionScriptingException("A function scripting exception has been found. Please review the log for more information.", err);
}
//.........这里部分代码省略.........
示例11: ScriptTriggers
private void ScriptTriggers()
{
try
{
#region Options
ScriptingOptions so = new ScriptingOptions();
so.NoExecuteAs = true;
so.ScriptDrops = false;
so.SchemaQualify = true;
so.AllowSystemObjects = false;
so.Triggers = true;
#endregion
Server srv = new Server();
Database db = GetDatabase(ref srv);
srv.SetDefaultInitFields(typeof(View), "IsSystemObject");
UrnCollection urns = new UrnCollection();
foreach (Table v in db.Tables)
{
foreach (Trigger t in v.Triggers)
{
// exclude these objects
if (t.IsSystemObject) continue;
if (t.Name.StartsWith("aspnet_")) continue;
urns.Add(t.Urn);
}
}
string filepath = this.BuildScriptFilePath(TriggerDirectory, null);
StringCollection FileCollection = new StringCollection();
CreateDirectory(filepath);
foreach (Table v in db.Tables)
{
foreach (Trigger t in v.Triggers)
{
if (!t.IsSystemObject)
{
string triggerFilePath = Path.Combine(filepath, v.Schema + "." + t.Name.ToString() + ".sql");
so.ScriptDrops = true;
StringCollection drop = t.Script(so);
so.ScriptDrops = false;
t.TextMode = false;
StringCollection create = t.Script();
StringCollection sc = new StringCollection();
if (t.IsEnabled)
{
sc.Add("IF EXISTS(SELECT * FROM SYSOBJECTS WHERE XTYPE='TR' AND NAME='" + t.Name.ToString() + "')\r\nBEGIN\r\n");
foreach (string s in drop)
{
sc.Add(s);
}
sc.Add("\r\nEND\r\nGO\r\n");
foreach (string s in create)
{
sc.Add(s);
sc.Add("GO\r\n");
}
WriteFile(triggerFilePath, sc);
string relativeTriggerFilePath = this.BuildRelativeFilePath(triggerFilePath);
FileCollection.Add(relativeTriggerFilePath); // We want a relative path here.
WriteStatus("File written: " + relativeTriggerFilePath);
}
}
else
{
WriteStatus("WARNING: is NOT scripted. It was found to be encrypted and cannot be scripted. (" + t.Name + ")");
}
}
}
string triggerListFilePath = this.BuildScriptFilePath(TriggerDirectory, TriggersFile);
WriteFile(triggerListFilePath, FileCollection);
string relativeTriggerListFilePath = this.BuildRelativeFilePath(triggerListFilePath);
WriteStatus("File written: " + relativeTriggerListFilePath);
}
catch (Exception err)
{
string name = "ScriptTriggers";
WriteStatus(name + "-" + Thread.CurrentThread.ThreadState.ToString());
if (Thread.CurrentThread.ThreadState != ThreadState.AbortRequested)
{
WriteStatus("An error may have been encountered. Please check the log file for more details.");
MMDB.Core.MMDBLogFile.Log(err, name);
throw new TriggerScriptingException("A trigger scripting exception has been found. Please review the log for more information.", err);
}
}
}
示例12: GetDatabase
private Database GetDatabase(ref Server srv)
{
try
{
Microsoft.SqlServer.Management.Common.ServerConnection conn = new Microsoft.SqlServer.Management.Common.ServerConnection(new System.Data.SqlClient.SqlConnection(GetConnectionString()));
Server s = new Server(conn);
s.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject");
s.SetDefaultInitFields(typeof(Table), "IsSystemObject");
s.SetDefaultInitFields(typeof(View), "IsSystemObject");
s.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject");
s.SetDefaultInitFields(typeof(Trigger), "IsSystemObject");
srv = s; //Return the server as well, in the evnet we are using dependency walkaer.
return s.Databases[Database];
}
catch (Exception err)
{
MMDB.Core.MMDBLogFile.Log(err);
return null;
}
}
示例13: Main
static void Main()
{
Server server;
System.Collections.Specialized.StringCollection checkIdentityStringCollection;
bool HasIdentity;
try
{
server = new Server();
server.ConnectionContext.Connect();
Console.WriteLine(DateTime.Now.ToString(Properties.Resources.TimeFormat,
System.Globalization.CultureInfo.CurrentCulture)
+ Properties.Resources.Starting);
// Limit the database properties returned to just those that we use
server.SetDefaultInitFields(typeof(Database),
new String[] { "Name", "IsSystemObject", "IsAccessible" });
server.SetDefaultInitFields(typeof(Table),
new String[] { "Schema", "Name" });
server.SetDefaultInitFields(typeof(Column),
new String[] { "Name", "Identity" });
foreach (Database db in server.Databases)
{
if (db.IsSystemObject == false && db.IsAccessible == true)
{
Console.WriteLine(Environment.NewLine
+ DateTime.Now.ToString(Properties.Resources.TimeFormat,
System.Globalization.CultureInfo.CurrentCulture)
+ Properties.Resources.Database + db.Name);
foreach (Table tbl in db.Tables)
{
if (db.IsSystemObject == false)
{
// Assume table has no identity column
HasIdentity = false;
foreach (Column col in tbl.Columns)
{
if (col.Identity == true)
{
HasIdentity = true;
break;
}
}
if (HasIdentity == true)
{
Console.WriteLine(DateTime.Now.ToString(Properties.Resources.TimeFormat,
System.Globalization.CultureInfo.CurrentCulture)
+ Properties.Resources.Table + tbl.ToString());
try
{
checkIdentityStringCollection = tbl.CheckIdentityValue();
foreach (string str in checkIdentityStringCollection)
{
Console.WriteLine(str);
}
}
catch (FailedOperationException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine(Environment.NewLine);
}
}
}
}
}
}
Console.WriteLine(Environment.NewLine
+ DateTime.Now.ToString(Properties.Resources.TimeFormat,
System.Globalization.CultureInfo.CurrentCulture)
+ Properties.Resources.Ending);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.WriteLine();
Console.WriteLine(Properties.Resources.Completed);
Console.ReadLine();
}
}
示例14: InitServer
private static Server InitServer(ServerConnection serverConnection)
{
var serv = new Server(serverConnection);
// set the default properties we want upon partial instantiation -
// smo is *really* slow if you don't do this
serv.SetDefaultInitFields(typeof(Table), "IsSystemObject", "Name");
serv.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject", "Name");
serv.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject", "Name");
serv.SetDefaultInitFields(typeof(View), "IsSystemObject", "Name");
serv.SetDefaultInitFields(typeof(Column), "Identity");
serv.SetDefaultInitFields(typeof(Index), "IndexKeyType");
return serv;
}
示例15: GenerateScripts
/// <summary>
/// does all the work.
/// </summary>
/// <param name="connStr"></param>
/// <param name="outputDirectory"></param>
/// <param name="dataScriptingFormat"></param>
/// <param name="verbose"></param>
/// <param name="scriptAllDatabases"></param>
/// <param name="purgeDirectory"></param>
/// <param name="scriptProperties"></param>
public void GenerateScripts(string outputDirectory,
bool scriptAllDatabases, bool purgeDirectory,
DataScriptingFormat dataScriptingFormat, bool verbose, bool scriptProperties)
{
var connection = new SqlConnection(ConnectionString);
var sc = new ServerConnection(connection);
var s = new Server(sc);
s.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(Table), "IsSystemObject");
s.SetDefaultInitFields(typeof(View), "IsSystemObject", "IsEncrypted");
s.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject", "IsEncrypted");
s.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql;
RunCommand(StartCommand, verbose, outputDirectory, s.Name, null);
// Purge at the Server level only when we're doing all databases
if (purgeDirectory && scriptAllDatabases && outputDirectory != null && Directory.Exists(outputDirectory))
{
if (verbose) Console.Error.Write("Purging directory...");
PurgeDirectory(outputDirectory, "*.sql");
if (verbose) Console.Error.WriteLine("Done");
}
if (scriptAllDatabases)
{
foreach (Database db in s.Databases)
{
try
{
RunCommand(PreScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
GenerateDatabaseScript(db, outputDirectory, purgeDirectory, dataScriptingFormat, verbose, scriptProperties, s);
RunCommand(PostScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
}
}
else
{
var db = s.Databases[connection.Database];
if(db == null)
{
throw new Exception(string.Format("Database '{0}' was not found", connection.Database));
}
RunCommand(PreScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
GenerateDatabaseScript(db, outputDirectory, purgeDirectory,
dataScriptingFormat, verbose, scriptProperties, s);
RunCommand(PostScriptingCommand, verbose, outputDirectory, s.Name, db.Name);
}
RunCommand(FinishCommand, verbose, outputDirectory, s.Name, null);
}