private void ListViewContextMenuStrip_Opening(object sender, CancelEventArgs e) { foreach (ToolStripMenuItem mnuItem in this.ListViewContextMenuStrip.Items) { mnuItem.Enabled = false; } if (this.ListView.SelectedItems.Count == 0) { return; } SqlSmoObject smoObject = (SqlSmoObject)this.ListView.SelectedItems[0].Tag; IScriptable scriptableObject = smoObject as IScriptable; if (scriptableObject != null) { this.scriptToolStripMenuItem.Enabled = true; } if (scriptableObject != null && !(smoObject is Database)) { this.scriptwithDependenciesToolStripMenuItem.Enabled = true; this.dependenciesToolStripMenuItem.Enabled = true; } }
private void objectBrowserTreeView_AfterExpand(object sender, TreeViewEventArgs e) { // Remove dummy node e.Node.Nodes.RemoveAt(0); SqlSmoObject smoObj = null; Urn urnNode = (Urn)e.Node.Tag; try { smoObj = server.GetSmoObject(urnNode); AddCollections(e, smoObj); } catch (UnsupportedVersionException) { // Right now don't do anything... but you might change the // Icon so it will emphasize the version issue } catch (SmoException) { try { AddItemInCollection(e, server); } catch (Exception except) { ExceptionMessageBox emb = new ExceptionMessageBox(except); emb.Show(this); } } catch (ApplicationException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } }
public SqlSmoObject GetSmoObject(SqlObject obj) { SqlSmoObject smoObj = null; switch (obj.Type) { case SqlObjectType.Table: smoObj = Database.Tables[obj.Name, obj.Schema]; break; case SqlObjectType.View: smoObj = Database.Views[obj.Name, obj.Schema]; break; case SqlObjectType.Function: smoObj = Database.UserDefinedFunctions[obj.Name, obj.Schema]; break; case SqlObjectType.StoredProcedure: smoObj = Database.StoredProcedures[obj.Name, obj.Schema]; break; } if (smoObj == null) { throw new InvalidOperationException($"{obj} can't be found"); } return(smoObj); }
public IEnumerable <DependencyCollectionNode> GetDependencies(SqlSmoObject smo) { var dependencyWalker = new DependencyWalker(_server); var depTree = dependencyWalker.DiscoverDependencies(new[] { smo }, true); return(dependencyWalker.WalkDependencies(depTree)); }
private void ShowDependenciesmenuItem_Click(object sender, EventArgs e) { Table table; DependencyTree deps; Scripter scripter; SqlSmoObject[] smoObjects = new SqlSmoObject[1]; DependencyForm form = new DependencyForm(); // Just make sure something is selected if (this.TableListView.SelectedIndices.Count == 0) { return; } // It's the first one as we only allow one selection table = (Table)(this.TableListView.SelectedItems[0].Tag); // Declare and instantiate new Scripter object scripter = new Scripter(table.Parent.Parent); // Declare array of SqlSmoObjects smoObjects[0] = table; // Discover dependencies deps = scripter.DiscoverDependencies(smoObjects, true); // Show dependencies form.ShowDependencies(table.Parent.Parent, deps); form.Show(); }
/// <summary> /// read a log on the server to a local file. This method is only supported on /// pre 9.0 servers /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string ReadLogToFile(string fileName) { ServerConnection connection = this.dataContainer.ServerConnection; string query = string.Format(CultureInfo.InvariantCulture , "EXECUTE master.dbo.xp_readerrorlog -1, {0}" , SqlSmoObject.MakeSqlString(fileName)); DataSet data = connection.ExecuteWithResults(query); if (data.Tables.Count > 0) { DataTable table = data.Tables[0]; string tempFileName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}", Path.GetTempPath(), "JobSR.StepOutput(Path.GetFileName(fileName))"); StreamWriter writer = new StreamWriter(tempFileName, false, Encoding.Unicode); foreach (DataRow row in table.Rows) { writer.Write(row[0].ToString()); if ((byte)row[1] == 0) { writer.WriteLine(); } } writer.Close(); return(tempFileName); } return(string.Empty); }
/// <summary> /// Генерирует скрипты создания ролей и пишет их в <code>output</code> /// </summary> /// <param name="output">Дескриптор файла, в который записываются хранимые процедуры</param> /// <param name="server">Сервер, на котором хранится база данных</param> /// <param name="database">Контролируемая база данных</param> private static void GenerateRoleScripts(XmlWriter output, Server server, Database database) { // Создали открывающийся тег output.WriteStartElement("Roles"); foreach (DatabaseRole role in database.Roles) { if (role.Name == "public") { continue; } output.WriteElementString("Header", role.Name); StringCollection strCollection = new StringCollection(); SqlSmoObject[] smoObj = new SqlSmoObject[1]; smoObj[0] = role; Scripter scriptor = new Scripter(server); scriptor.Options.AllowSystemObjects = false; strCollection = scriptor.Script(smoObj); output.WriteStartElement("script"); output.WriteString("\n"); foreach (string s in strCollection) { output.WriteString(s.Trim() + "\n"); } output.WriteEndElement(); } output.WriteEndElement(); }
/// <summary> /// Генерирует скрипты создания хранимых процедур и пишет их в <code>output</code> /// </summary> /// <param name="output">Дескриптор файла, в который записываются хранимые процедуры</param> /// <param name="server">Сервер, на котором хранится база данных</param> /// <param name="database">Контролируемая база данных</param> private static void GenerateStoredProcScripts(XmlWriter output, Server server, Database database) { // Создали открывающийся тег output.WriteStartElement("Stored-Procedures"); foreach (StoredProcedure proc in database.StoredProcedures) { if ((proc.Schema != "sys") && ((proc.Schema != "dbo") || (proc.Name.Substring(0, 2) != "sp"))) { output.WriteElementString("Header", proc.Name); StringCollection strCollection = new StringCollection(); SqlSmoObject[] smoObj = new SqlSmoObject[1]; smoObj[0] = proc; Scripter scriptor = new Scripter(server); scriptor.Options.AllowSystemObjects = false; scriptor.Options.Indexes = true; scriptor.Options.DriAll = true; scriptor.Options.Default = true; scriptor.Options.WithDependencies = true; scriptor.Options.ScriptSchema = true; strCollection = scriptor.Script(smoObj); output.WriteStartElement("script"); output.WriteString("\n"); foreach (string s in strCollection) { output.WriteString(s.Trim() + "\n"); } output.WriteEndElement(); } } output.WriteEndElement(); }
/// <summary> /// Генерирует скрипты создания индексов и пишет их в <code>output</code> /// </summary> /// <param name="output">Дескриптор файла, в который записываются хранимые процедуры</param> /// <param name="server">Сервер, на котором хранится база данных</param> /// <param name="database">Контролируемая база данных</param> private static void GenerateIndexScripts(XmlWriter output, Database database) { // Создали открывающийся тег output.WriteStartElement("Indexes"); foreach (Table table in database.Tables) { foreach (Index index in table.Indexes) { output.WriteElementString("Header", index.Name); StringCollection strCollection = new StringCollection(); SqlSmoObject[] smoObj = new SqlSmoObject[1]; smoObj[0] = index; Scripter scriptor = new Scripter(database.Parent); scriptor.Options.AllowSystemObjects = false; scriptor.Options.DriAll = true; scriptor.Options.Default = true; scriptor.Options.WithDependencies = false; scriptor.Options.ScriptSchema = true; strCollection = scriptor.Script(smoObj); output.WriteStartElement("script"); output.WriteString("\n"); foreach (string s in strCollection) { output.WriteString(s.Trim() + "\n"); } output.WriteEndElement(); } } output.WriteEndElement(); }
public static bool InSameDatabase(this SqlSmoObject sqlSmoObject, DependencyNode x) { return(0 == string.Compare( x.Urn.GetNameForType(Const.Database), sqlSmoObject.Urn.GetNameForType(Const.Database), StringComparison.InvariantCultureIgnoreCase)); }
// Scripts an item in right window if it is scriptable private void DependenciesTreeView_AfterSelect(object sender, TreeViewEventArgs e) { this.ScriptTextBox.Clear(); if (e.Node.Tag == null) { return; } // Script an object SqlSmoObject o = this.sqlServerSelection.GetSmoObject((Urn)e.Node.Tag); ScriptingOptions so = new ScriptingOptions(); so.DriAll = true; so.Indexes = true; so.IncludeHeaders = true; so.Permissions = true; so.PrimaryObject = true; so.SchemaQualify = true; so.Triggers = true; IScriptable scriptableObject = o as IScriptable; if (scriptableObject != null) { StringBuilder sb = new StringBuilder(); foreach (string s in scriptableObject.Script(so)) { sb.Append(s); sb.Append(Environment.NewLine); } this.ScriptTextBox.Text = sb.ToString(); } }
/// <summary> /// Scripts the SqlSmoObject using defined handler, or generic Script method /// </summary> /// <param name="sqlSmoObject">The SqlSmoObject to script.</param> private void ScriptObject(SqlSmoObject sqlSmoObject) { // Don't script excluded objects if (IsExcludedObject(sqlSmoObject)) { return; } // Urn urn = new Urn(sqlSmoObject.Urn); Urn urn = sqlSmoObject.Urn; // Setup scripting options ScriptingOptions scriptingOptions = new ScriptingOptions(); this.ConfigureScriptingOptions(scriptingOptions, urn); StringCollection objectStatements; if (this.customScriptMethods.ContainsKey(sqlSmoObject.GetType())) { objectStatements = this.customScriptMethods[sqlSmoObject.GetType()](sqlSmoObject, urn, scriptingOptions); } else { try { // Call the "Script" method of sqlSmoObject (which may or may not exist) object[] invokeMemberArgs = { scriptingOptions }; objectStatements = sqlSmoObject.GetType().InvokeMember( "Script", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, sqlSmoObject, invokeMemberArgs) as StringCollection; } catch (MissingMethodException) { this.logger.Debug("Object doesn't provide Script method:" + urn.Type + ", " + sqlSmoObject); return; } } // Clean if foreign key CleanupTableCreation(objectStatements); // The output script string objectScript = CleanStatements(objectStatements); // Get object Name (Remove SchemaQualify if needed) string name = this.ObjectName(sqlSmoObject); // Write script to output if (objectScript.Length != 0) { this.WriteScript(urn.Type, name, objectScript); } }
public void CopyFunction(string functionName) { Logger.WriteLine("Copying function {0}", functionName); SqlSmoObject function = _sourceDatabase.UserDefinedFunctions[functionName]; CopySqlSmoObject(function); }
public void DeleteStoredProcedure(string storedProcName) { Logger.WriteLine("Deleting stored procedure {0}", storedProcName); SqlSmoObject sourceProcedure = _sourceDatabase.StoredProcedures[storedProcName]; DeleteSqlSmoObject(sourceProcedure); }
public void DeleteView(string viewName) { Logger.WriteLine("Deleting view {0}", viewName); SqlSmoObject sourceView = _sourceDatabase.Views[viewName]; DeleteSqlSmoObject(sourceView); }
public void DeleteTable(string tableName) { Logger.WriteLine("Deleting table {0}", tableName); SqlSmoObject sourceTable = _sourceDatabase.Tables[tableName]; DeleteSqlSmoObject(sourceTable); }
public void CopyView(string viewName) { Logger.WriteLine("Copying view {0}", viewName); SqlSmoObject sourceView = _sourceDatabase.Views[viewName]; CopySqlSmoObject(sourceView); }
public void CopyTable(string tableName) { Logger.WriteLine("Copying table {0}", tableName); SqlSmoObject table = _sourceDatabase.Tables[tableName]; CopySqlSmoObject(table); }
public void DeleteFunction(string functionName) { Logger.WriteLine("Deleting function {0}", functionName); SqlSmoObject function = _sourceDatabase.UserDefinedFunctions[functionName]; DeleteSqlSmoObject(function); }
public DefaultSQL2008AttributeTypeProvider(SqlSmoObject parent) { if (parent == null) { throw new ArgumentNullException("parent"); } _parent = parent; }
private static void check_oi(SqlSmoObject obj, obj_info oi) { if (null == obj) { throw new ScripterException( string.Format("cannot find {0}: {2} {1}", oi.type, oi.name, oi.schema) ); } }
public virtual bool IsConnectionOpen(SmoObjectBase smoObj) { SqlSmoObject sqlObj = smoObj as SqlSmoObject; return(sqlObj != null && sqlObj.ExecutionManager != null && sqlObj.ExecutionManager.ConnectionContext != null && sqlObj.ExecutionManager.ConnectionContext.IsOpen); }
/// <summary> /// Custom Script method for table objects. /// </summary> /// <param name="sqlSmoObject">The table.</param> /// <param name="urn">The urn.</param> /// <param name="scriptingOptions">The scripting options.</param> /// <returns>Table creation statements</returns> private StringCollection ScriptTable(SqlSmoObject sqlSmoObject, Urn urn, ScriptingOptions scriptingOptions) { Table table = sqlSmoObject as Table; if (this.config.scriptForeignKeysSeparately) { // Don't script foreign keys scriptingOptions.DriAll = false; scriptingOptions.DriAllConstraints = false; scriptingOptions.DriAllKeys = false; scriptingOptions.DriChecks = true; scriptingOptions.DriClustered = true; scriptingOptions.DriDefaults = true; scriptingOptions.DriForeignKeys = false; scriptingOptions.DriIncludeSystemNames = true; scriptingOptions.DriIndexes = true; scriptingOptions.DriNonClustered = true; scriptingOptions.DriPrimaryKey = true; scriptingOptions.DriUniqueKeys = true; // scriptingOptions.DriWithNoCheck = true; // Queue foreign keys for later scripting foreach (ForeignKey fk in table.ForeignKeys) { this.independentObjectsLast.Add(fk); } } StringCollection tableStatements = table.Script(scriptingOptions); CleanupTableCreation(tableStatements); // WORKAROUND: Script extended properties for primary key index (missed by SMO - Index.ExtendedProperties doesn't include the INDEX, only the CONSTRAINT extended properties) if (this.config.scriptExtendedProperties) { foreach (Index index in table.Indexes) { if (index.IndexKeyType == IndexKeyType.DriPrimaryKey) { DataSet ds = table.Parent.ExecuteWithResults(string.Format("SELECT name, value FROM fn_listextendedproperty(NULL, 'schema', '{0}', 'table', '{1}', 'index', '{2}')", table.Schema, table.Name, index.Name)); if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { tableStatements.Add(string.Format("EXEC sys.sp_addextendedproperty @name=N'{3}', @value=N'{4}' , @level0type=N'SCHEMA',@level0name=N'{0}', @level1type=N'TABLE',@level1name=N'{1}', @level2type=N'INDEX',@level2name=N'{2}'", EscapeSQLText(table.Schema), EscapeSQLText(table.Name), EscapeSQLText(index.Name), EscapeSQLText(row["Name"].ToString()), EscapeSQLText(row["Value"].ToString()))); } } } } } return(tableStatements); }
public virtual void OpenConnection(SmoObjectBase smoObj) { SqlSmoObject sqlObj = smoObj as SqlSmoObject; if (sqlObj != null && sqlObj.ExecutionManager != null && sqlObj.ExecutionManager.ConnectionContext != null) { sqlObj.ExecutionManager.ConnectionContext.Connect(); } }
private void ShowDetails(TreeNode node) { SqlSmoObject smoObject = null; SmoCollectionBase smoCollection = null; this.ListView.Items.Clear(); if (node == null) { return; } switch (node.Tag.GetType().Name) { case "DatabaseCollection": case "TableCollection": case "ViewCollection": case "StoredProcedureCollection": case "ColumnCollection": case "SqlAssemblyCollection": // Load the items of a collection, if not already loaded LoadTreeViewItems(node); // Update the TreeView smoCollection = (SmoCollectionBase)node.Tag; UpdateListViewWithCollection(smoCollection); break; case "Server": smoObject = ((Server)node.Tag).Information; UpdateListView(smoObject, true, "Information"); smoObject = ((Server)node.Tag).Settings; UpdateListView(smoObject, false, "Settings"); break; case "Database": case "Table": case "View": case "StoredProcedure": case "Column": case "SqlAssembly": smoObject = (SqlSmoObject)node.Tag; UpdateListView(smoObject, true, null); break; default: throw new Exception(Properties.Resources.UnrecognizedType + node.Tag.GetType().ToString()); } }
private void DeleteSqlSmoObject(SqlSmoObject smoObject) { try { IEnumerable <DependencyCollectionNode> dependencies = GetDependencies(smoObject, Location.Target); DeleteDependencies(dependencies); } catch { Logger.WriteLine("Failed to delete {0}", smoObject.Urn); } }
// Update the list view for a property list private void UpdateListView(SqlSmoObject smoObject, bool clear, string group) { smoObject.Initialize(true); if (clear == true) { this.ListView.Columns.Clear(); this.ListView.Groups.Clear(); ColumnHeader colHeader = new ColumnHeader(); colHeader.Text = Properties.Resources.PropertyName; this.ListView.Columns.Add(colHeader); colHeader = new ColumnHeader(); colHeader.Text = Properties.Resources.Value; this.ListView.Columns.Add(colHeader); } ListViewGroup lvGroup = null; if (group != null) { lvGroup = new ListViewGroup(group); this.ListView.Groups.Add(lvGroup); } ListViewItem lvi = new ListViewItem(); lvi.Text = Properties.Resources.Urn; lvi.Name = Properties.Resources.Urn; lvi.Group = lvGroup; lvi.SubItems.Add(smoObject.Urn); this.ListView.Items.Add(lvi); foreach (Property prop in smoObject.Properties) { if (prop.Value != null) { ListViewItem lvItem = new ListViewItem(); lvItem.Text = prop.Name; lvItem.Name = prop.Name; lvItem.Group = lvGroup; lvItem.SubItems.Add(prop.Value.ToString()); this.ListView.Items.Add(lvItem); } } this.ListView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.ListView.Sort(); this.ListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); this.ListView.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); }
private void CopySqlSmoObject(SqlSmoObject smoObject) { try { IEnumerable <DependencyCollectionNode> dependencies = GetDependencies(smoObject, Location.Source); ScriptDependencies(dependencies); } catch { Logger.WriteLine("Failed to copy {0}", smoObject.Urn); } }
private static void AddItemInCollection(System.Windows.Forms.TreeViewEventArgs node, Server sqlServer) { Urn urnNode = (Urn)node.Node.Tag; SqlSmoObject smoObj = sqlServer.GetSmoObject(urnNode.Parent); TreeNode tn; NamedSmoObject namedObj; PropertyInfo p = smoObj.GetType().GetProperty(node.Node.Text); if (p != null) { ICollection iColl = p.GetValue(smoObj, null) as ICollection; if (iColl != null) { IEnumerator enum1 = iColl.GetEnumerator(); while (enum1.MoveNext()) { tn = new TreeNode(); namedObj = enum1.Current as NamedSmoObject; if (namedObj != null) { tn.Text = namedObj.Name; } else { tn.Text = ((SqlSmoObject)enum1.Current).Urn; } tn.Tag = ((SqlSmoObject)enum1.Current).Urn; node.Node.Nodes.Add(tn); AddDummyNode(tn); } } else { Console.WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.PropertyNotICollection, p.Name)); } } else { Console.WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.PropertyNotFound, node.Node.Text)); } }
/// <summary> /// Custom Script method for database objects. /// </summary> /// <param name="sqlSmoObject">The database.</param> /// <param name="urn">The urn.</param> /// <param name="scriptingOptions">The scripting options.</param> /// <returns>Empty string collection (no residual statements)</returns> private StringCollection ScriptDatabase(SqlSmoObject sqlSmoObject, Urn urn, ScriptingOptions scriptingOptions) { Database database = sqlSmoObject as Database; StringCollection databaseStatements = database.Script(scriptingOptions); this.WriteScript(urn.Type, sqlSmoObject.ToString(), databaseStatements.ToString()); foreach (DatabaseDdlTrigger databaseDdlTrigger in database.Triggers) { StringCollection databaseDdlTriggerStatements = databaseDdlTrigger.Script(scriptingOptions); this.WriteScript(databaseDdlTrigger.Urn.Type, databaseDdlTrigger.ToString(), CleanStatements(databaseDdlTriggerStatements)); } // Return empty collection return(new StringCollection()); }
public ScriptingForm(Server srvr, SqlSmoObject smoObject) { InitializeComponent(); this.sqlServerSelection = srvr; this.smoScripter = new Scripter(srvr); // Generate the dependency tree this.dependTree = this.smoScripter.DiscoverDependencies(new SqlSmoObject[] { smoObject }, true); UpdateTree(); UpdateListAndScript(); if (Phase1TreeView.Nodes.Count > 0) { Phase1TreeView.Nodes[0].ExpandAll(); } }
/// <summary> /// Adds children to the current node. basically all collection of a SqlSmoObject object /// </summary> /// <param name="node"></param> /// <param name="smoObj"></param> private static void AddCollections(System.Windows.Forms.TreeViewEventArgs node, SqlSmoObject smoObj) { TreeNode tn; Type t = smoObj.GetType(); foreach (System.Reflection.PropertyInfo p in t.GetProperties()) { if (p.Name != "SystemMessages" && p.Name != "UserDefinedMessages") { // If it is collection we create a node for it if (p.PropertyType.IsSubclassOf(typeof(AbstractCollectionBase))) { tn = new TreeNode(); tn.Text = p.Name; tn.Tag = new Urn(smoObj.Urn + @"/" + p.Name); node.Node.Nodes.Add(tn); AddDummyNode(tn); } } } // Verify if we are at the server level and add the JobServer too if (smoObj is Server) { tn = new TreeNode(); tn.Text = Properties.Resources.JobServer; tn.Tag = new Urn(smoObj.Urn + @"/" + Properties.Resources.JobServer); node.Node.Nodes.Add(tn); AddDummyNode(tn); } smoObj = null; }
private void Setup(Urn urn1, Urn urn2) { if (serverName1 == null || serverName2 == null) { throw new ApplicationException( Properties.Resources.ServerPropertiesCannotBeNull); } server1 = new Server(serverName1); server2 = new Server(serverName2); if (loginName1 == null || loginName1.Length == 0) { server1.ConnectionContext.LoginSecure = true; } else { server1.ConnectionContext.LoginSecure = false; server1.ConnectionContext.Login = loginName1; server1.ConnectionContext.Password = password1; } if (loginName2 == null || loginName2.Length == 0) { server2.ConnectionContext.LoginSecure = true; } else { server2.ConnectionContext.LoginSecure = false; server2.ConnectionContext.Login = loginName2; server2.ConnectionContext.Password = password2; } try { smoObject1 = server1.GetSmoObject(urn1); } catch (ApplicationException ex) { WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ErrorCreatingFirstObject, ex)); throw new ApplicationException( Properties.Resources.ErrorCreatingFirstObjectException, ex); } try { smoObject2 = server2.GetSmoObject(urn2); } catch (ApplicationException ex) { WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ErrorCreatingSecondObject, ex)); throw new ApplicationException( Properties.Resources.ErrorCreatingSecondObjectException, ex); } if (smoObject1 == null) { throw new ApplicationException(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectNotCreated, urn1)); } if (smoObject2 == null) { throw new ApplicationException(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectNotCreated, urn2)); } }
private static bool IsInPropBag(PropertyInfo propInfo1, SqlSmoObject object1) { return object1.Properties.Contains(propInfo1.Name); }
private static bool IsAutoCreated(SqlSmoObject obj) { PropertyInfo pi = obj.GetType().GetProperty("IsAutoCreated", Type.GetType("System.Boolean")); if (pi != null) return (bool)pi.GetValue(obj, null); else return false; }
private bool IterateProps(SqlSmoObject object1, SqlSmoObject object2, PropertyInfo[] pi1, PropertyInfo[] pi2) { PropertyInfo propInfo1; PropertyInfo propInfo2; // Iterate through all properties for (int k = 0; k < pi1.Length; k++) { try { propInfo1 = pi1[k]; propInfo2 = pi2[k]; currentPropertyName = propInfo1.Name; if (ShouldIgnore(propInfo1)) continue; if (ShouldIgnore(propInfo1.Name, object1.Urn) || ShouldIgnore(propInfo2.Name, object2.Urn)) continue; if (ShouldIgnore(propInfo1.Name, object1.GetType().Name)) continue; if (ShouldIgnore(propInfo1.PropertyType.Name)) continue; // RULE: We'll not compare property Name for the initial // Objects smoObject1 and smoObject2 entered by the user if (propInfo1.Name == "Name" && level == 1) continue; // Check to see if the current prop is collection if (propInfo1.PropertyType.GetInterface("ICollection", true) != null) { AnalyzeCollection(propInfo1, propInfo2, object1, object2); continue; } // NB: This test must be AFTER the prior tests // Make sure you do not disturb this order!!! if (!IsInPropBag(propInfo1, object1)) continue; if (propInfo1.PropertyType.BaseType != null) { if (propInfo1.PropertyType.BaseType.FullName == "System.ValueType" && propInfo2.PropertyType.BaseType.FullName == "System.ValueType") { returnVal &= CompareValueTypes( propInfo1, propInfo2, object1, object2); continue; } } else { if (propInfo1.PropertyType.FullName == "System.ValueType" && propInfo2.PropertyType.FullName == "System.ValueType") { returnVal &= CompareValueTypes( propInfo1, propInfo2, object1, object2); continue; } } if (propInfo1.PropertyType.FullName == "System.String" && propInfo2.PropertyType.FullName == "System.String") { returnVal &= CompareStringTypes( propInfo1, propInfo2, object1, object2); continue; } if (propInfo1.PropertyType.IsEnum && propInfo2.PropertyType.IsEnum) { returnVal &= CompareEnumTypes( propInfo1, propInfo2, object1, object2); continue; } else { // The property Type is something other than "System.Types" returnVal &= CompareAnyTypes( propInfo1, propInfo2, object1, object2); } } catch (CollectionNotAvailableException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } catch (InvalidVersionEnumeratorException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } catch (UnsupportedVersionException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } catch (UnknownPropertyException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } catch (PropertyCannotBeRetrievedException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } catch (InternalEnumeratorException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); if (ex.Message.IndexOf("version") != -1 && ex.Message.IndexOf("is not supported") != -1) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } returnVal &= false; WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.Exception, ex), MessageType.Error); WriteLine(separatorLine); } catch (ApplicationException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn)); WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ReadingProperty, currentPropertyName)); if (ex.InnerException != null) { if (ex.InnerException is CollectionNotAvailableException) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } if (ex.InnerException is InvalidVersionEnumeratorException) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } if (ex.InnerException is UnsupportedVersionException) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } if (ex.InnerException is UnknownPropertyException) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } if (ex.InnerException is PropertyCannotBeRetrievedException) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } if (ex.InnerException is InternalEnumeratorException) { if (ex.Message.IndexOf("version") != -1 && ex.Message.IndexOf("is not supported") != -1) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.IgnoredException, ex), MessageType.Warning); WriteLine(separatorLine); continue; } } } returnVal &= false; WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.Exception, ex), MessageType.Error); WriteLine(separatorLine); } } return returnVal; }
private static string GetNeeds(IServer server, SqlSmoObject sqlSmoObject, DatabaseObjectTypes requestedDependencyTypes) { var dependencyTypeList = requestedDependencyTypes.GetDependencyTypeList(); var dependencies = server.GetDependencies(sqlSmoObject) .Where(x => x.IsRootNode == false && dependencyTypeList.Contains(x.Urn.Type) && sqlSmoObject.InSameDatabase(x) ) .Select(x => x.Urn.GetAttribute("Schema") + '.' + x.Urn.GetNameForType(x.Urn.Type) ) .ToList(); if (dependencies.Count == 0) return string.Empty; return "--:: need " + string.Join(", ", dependencies) + Environment.NewLine; }
private bool CompareEnumTypes(PropertyInfo propInfo1, PropertyInfo propInfo2, SqlSmoObject object1, SqlSmoObject object2) { Enum s1 = (Enum)propInfo1.GetValue(object1, null); Enum s2 = (Enum)propInfo2.GetValue(object2, null); bool ReturnValueLoc = s1.CompareTo(s2) == 0 ? true : false; if (!ReturnValueLoc) { DifferentProperties temp = new DifferentProperties(); temp.Urn1 = object1.Urn; temp.Urn2 = object2.Urn; temp.PropertyName = propInfo1.Name; temp.ObjectValue1 = propInfo1.GetValue(object1, null).ToString(); temp.ObjectValue2 = propInfo2.GetValue(object2, null).ToString(); DiffProps.Add(temp); } return ReturnValueLoc; }
private bool CompareAnyTypes(PropertyInfo propInfo1, PropertyInfo propInfo2, SqlSmoObject object1, SqlSmoObject object2) { bool ReturnValueLoc = true; object objTemp1 = propInfo1.GetValue(object1, null); object objTemp2 = propInfo2.GetValue(object2, null); if (objTemp1 == null && objTemp2 == null) { // (i.e. DefaultConstraint) if (!CanBeNull(propInfo1.Name, object1.GetType().Name)) { throw new ApplicationException(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.NullReferenceException, object1.Urn, object2.Urn, propInfo1.Name, propInfo2.Name)); } // On else branch we do nothing; both props are null and they // are accepted with null values return true; } if (objTemp1.GetType().IsSubclassOf(typeof(SqlSmoObject)) && objTemp2.GetType().IsSubclassOf(typeof(SqlSmoObject))) { ReturnValueLoc &= Compare((SqlSmoObject)objTemp1, (SqlSmoObject)objTemp2); return ReturnValueLoc; } if (objTemp1.GetType().FullName == "Microsoft.SqlServer.Management.Smo.DataType" && objTemp2.GetType().FullName == "Microsoft.SqlServer.Management.Smo.DataType") { DataType dt1 = objTemp1 as DataType; DataType dt2 = objTemp2 as DataType; ReturnValueLoc &= dt1.SqlDataType == dt2.SqlDataType ? true : false; if (!ReturnValueLoc) { DifferentProperties temp = new DifferentProperties(); temp.Urn1 = object1.Urn; temp.Urn2 = object2.Urn; temp.PropertyName = propInfo1.Name; // Here we store all the prop and values for DataType string objectValue1 = string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectValue, dt1.MaximumLength, dt1.Name, dt1.NumericPrecision, dt1.NumericScale, dt1.Schema, dt1.SqlDataType); string objectValue2 = string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectValue, dt2.MaximumLength, dt2.Name, dt2.NumericPrecision, dt2.NumericScale, dt2.Schema, dt2.SqlDataType); temp.ObjectValue1 = objectValue1; temp.ObjectValue2 = objectValue2; DiffProps.Add(temp); } return ReturnValueLoc; } ReturnValueLoc &= objTemp1.Equals(objTemp2); return ReturnValueLoc; }
private void AnalyzeCollection(PropertyInfo propInfo1, PropertyInfo propInfo2, SqlSmoObject object1, SqlSmoObject object2) { ICollection iColl1 = propInfo1.GetValue(object1, null) as ICollection; ICollection iColl2 = propInfo2.GetValue(object2, null) as ICollection; IEnumerator enum1 = iColl1.GetEnumerator(); IEnumerator enum2 = iColl2.GetEnumerator(); // Populate the ChildrenOfObject1 and ChildrenOfObject2 Populate1(enum1, enum2); Populate2(enum2, enum1); }
public IEnumerable<DependencyCollectionNode> GetDependencies(SqlSmoObject smo) { var dependencyWalker = new DependencyWalker(_server); var depTree = dependencyWalker.DiscoverDependencies(new[] { smo }, true); return dependencyWalker.WalkDependencies(depTree); }
private void ScriptTableButton_Click(System.Object sender, System.EventArgs e) { Cursor csr = null; Database db; StringCollection strColl; Scripter scrptr; SqlSmoObject[] smoObjects; Table tbl; Int32 count; try { csr = this.Cursor; // Save the old cursor this.Cursor = Cursors.WaitCursor; // Display the waiting cursor // Use the selected database db = (Database)DatabasesComboBox.SelectedItem; if (db.Name.Length == 0) { ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = Properties.Resources.NoDatabaseSelected; emb.Show(this); return; } // Create scripter object scrptr = new Scripter(SqlServerSelection); if (ScriptDropCheckBox.CheckState == CheckState.Checked) { scrptr.Options.ScriptDrops = true; } else { scrptr.Options.ScriptDrops = false; } scrptr.DiscoveryProgress += new ProgressReportEventHandler( this.ScriptTable_DiscoveryProgressReport); scrptr.ScriptingProgress += new ProgressReportEventHandler( this.ScriptTable_ScriptingProgressReport); if (TablesComboBox.SelectedIndex >= 0) { // Get selected table smoObjects = new SqlSmoObject[1]; tbl = (Table)TablesComboBox.SelectedItem; if (tbl.IsSystemObject == false) { smoObjects[0] = tbl; } if (DependenciesCheckBox.CheckState == CheckState.Checked) { scrptr.Options.WithDependencies = true; } else { scrptr.Options.WithDependencies = false; } strColl = scrptr.Script(smoObjects); // Clear control ScriptTextBox.Clear(); count = 0; foreach (String str in strColl) { count++; sbrStatus.Text = string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.AppendingScript, count, strColl.Count); ScriptTextBox.AppendText(str); ScriptTextBox.AppendText(Properties.Resources.Go); } } else { ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = Properties.Resources.ChooseTable; emb.Show(this); } } catch (SmoException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } finally { // Clean up sbrStatus.Text = Properties.Resources.Done; // Restore the original cursor this.Cursor = csr; } }
private void dependenciesToolStripMenuItem_Click(object sender, EventArgs e) { if (this.ListView.SelectedItems.Count == 0) { return; } object selectedObject = this.ListView.SelectedItems[0].Tag; IScriptable scriptableObject = selectedObject as IScriptable; if (scriptableObject != null && !(selectedObject is Database)) { SqlSmoObject[] smoObjects = new SqlSmoObject[1]; smoObjects[0] = (SqlSmoObject)selectedObject; Scripter scripter = new Scripter(this.sqlServerSelection); DependenciesForm frm = new DependenciesForm(this.sqlServerSelection, scripter.DiscoverDependencies(smoObjects, DependencyType.Parents)); frm.ShowDialog(this); } }
private bool Compare(SqlSmoObject object1, SqlSmoObject object2) { try { level++; // Invariant: the objects have the same Type!!! if (object1.GetType().Name != object2.GetType().Name) { LogError(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectsHaveDifferentTypes, object1.GetType().Name, object2.GetType().Name)); level--; Write(Environment.NewLine); throw new ApplicationException(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ObjectsHaveDifferentTypes, object1.GetType().Name, object2.GetType().Name)); } if (IsFromIndexCreation(object1) || IsFromIndexCreation(object2)) { level--; Write(Environment.NewLine); return true; } if (IsSystemNamed(object1) || IsSystemNamed(object2)) { level--; Write(Environment.NewLine); return true; } // Removed to facilitate comparisons of system objects. //if (IsSystemObject(object1) || IsSystemObject(object2)) //{ // level--; // Write(Environment.NewLine); // return true; //} if (ShouldIgnoreSchema(object1.Urn.GetAttribute("Schema")) || ShouldIgnoreSchema(object2.Urn.GetAttribute("Schema"))) { level--; Write(Environment.NewLine); return true; } if (ShouldIgnore(object1.GetType().Name)) { level--; Write(Environment.NewLine); return true; } if (IsAutoCreated(object1) || IsAutoCreated(object2)) { level--; Write(Environment.NewLine); return true; } // See if at least one of the object is in the ignore list; this way if the user wants to // Ignore an object (let's say Col1) is enough to enter Col1 of the first obj in the RED list // Not both Col1 from both object (smoObject1 and smoObject2) if (ShouldIgnore(object1.Urn) || ShouldIgnore(object2.Urn)) { level--; Write(Environment.NewLine); return true; } // Iterate through all properties and ignore those from red list PropertyInfo[] pi1 = object1.GetType().GetProperties(); PropertyInfo[] pi2 = object2.GetType().GetProperties(); // Sort these two arrays based on the property names Array.Sort(pi1, comparer); Array.Sort(pi2, comparer); // Let's see if the number of properties are the same; // If not that means we play with diferent types... // Which it shouldn't happen at this level... if (pi1.Length != pi2.Length) { // This case is almost impossible // But stuff happens hence extra tests applied :) level--; Write(Environment.NewLine); throw new ApplicationException(string.Format( System.Threading.Thread.CurrentThread.CurrentCulture, Properties.Resources.DifferentNumberProperties, object1.Urn, object2.Urn, pi1.Length, pi2.Length)); } returnVal &= IterateProps(object1, object2, pi1, pi2); level--; Write(Environment.NewLine); return returnVal; } catch (ApplicationException ex) { WriteLine(string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.ExceptionWhileComparing, object1.Urn, object2.Urn), MessageType.Error); WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.Exception, ex)); level--; Write(Environment.NewLine); return false; } }
private bool CompareStringTypes(PropertyInfo propInfo1, PropertyInfo propInfo2, SqlSmoObject object1, SqlSmoObject object2) { bool ReturnValueLoc = false; if (propInfo1.Name == "TextBody") { ReturnValueLoc = (((string)propInfo1.GetValue(object1, null))) .TrimEnd() == (((string)propInfo2.GetValue(object2, null))) .TrimEnd() ? true : false; } else { ReturnValueLoc = ((string)propInfo1.GetValue(object1, null)) == ((string)propInfo2.GetValue(object2, null)) ? true : false; } if (!ReturnValueLoc) { DifferentProperties temp = new DifferentProperties(); temp.Urn1 = object1.Urn; temp.Urn2 = object2.Urn; temp.PropertyName = propInfo1.Name; temp.ObjectValue1 = propInfo1.GetValue(object1, null).ToString(); temp.ObjectValue2 = propInfo2.GetValue(object2, null).ToString(); DiffProps.Add(temp); } return ReturnValueLoc; }
private bool CompareValueTypes(PropertyInfo propInfo1, PropertyInfo propInfo2, SqlSmoObject object1, SqlSmoObject object2) { object obj1 = propInfo1.GetValue(object1, null); object obj2 = propInfo2.GetValue(object2, null); bool ReturnValueLoc = obj1.Equals(obj2); if (!ReturnValueLoc) { DifferentProperties temp = new DifferentProperties(); temp.Urn1 = object1.Urn; temp.Urn2 = object2.Urn; temp.PropertyName = propInfo1.Name; temp.ObjectValue1 = propInfo1.GetValue(object1, null).ToString(); temp.ObjectValue2 = propInfo2.GetValue(object2, null).ToString(); DiffProps.Add(temp); } return ReturnValueLoc; }