Inheritance: INHydrateGenerator, IXMLable
Exemplo n.º 1
0
		private static void LoadStoredProcedures(nHydrateGeneratorProject project, string connectionString)
		{
			try
			{
				var root = (ModelRoot)project.RootController.Object;
				var dsSP = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForStoredProcedures((project.Model as ModelRoot).StoredProcedurePrefix));
				var dsSPColumn = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForStoredProceduresParameters((project.Model as ModelRoot).StoredProcedurePrefix));

				//Add the Stored Procedures
				foreach (DataRow rowSP in dsSP.Tables[0].Rows)
				{
					var id = (int)rowSP["id"];
					var name = (string)rowSP["name"];
					var customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == name);
					if (customStoredProcedure == null)
					{
						customStoredProcedure = ((ModelRoot)project.RootController.Object).Database.CustomStoredProcedures.Add();
						customStoredProcedure.Name = name;
						customStoredProcedure.SQL = GetSqlForStoredProceduresBody(name, connectionString);
					}

				}

				////Add the columns
				//foreach (DataRow rowSP in dsSPColumn.Tables[0].Rows)
				//{
				//  int id = (int)rowSP["id"];
				//  string spName = (string)rowSP["name"];
				//  string name = (string)rowSP["ColName"];
				//  string typeName = (string)rowSP["ColType"];
				//  CustomStoredProcedure customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == spName);
				//  if (customStoredProcedure != null)
				//  {
				//    CustomStoredProcedureColumn column = root.Database.CustomStoredProcedureColumns.Add();
				//    column.Name = name;
				//    column.DataType = DatabaseHelper.GetSQLDataType(typeName);
				//    customStoredProcedure.Columns.Add(column.CreateRef());
				//    column.ParentRef = customStoredProcedure.CreateRef();
				//  }
				//}

				//Add the parameters
				foreach (DataRow rowSP in dsSPColumn.Tables[0].Rows)
				{
					var id = (int)rowSP["id"];
					var spName = (string)rowSP["name"];
					var name = (string)rowSP["ColName"];
					var typeName = (string)rowSP["ColType"];
					var length = int.Parse(rowSP["length"].ToString());
					var customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == spName);
					if (customStoredProcedure != null)
					{
						var parameter = root.Database.CustomRetrieveRuleParameters.Add();
						parameter.Name = name.Replace("@", string.Empty);
						parameter.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(rowSP["xtype"].ToString()));
						parameter.Length = length;
						customStoredProcedure.Parameters.Add(parameter.CreateRef());
						parameter.ParentTableRef = customStoredProcedure.CreateRef();
					}
				}

			}
			catch (Exception ex)
			{
				throw;
			}
		}
Exemplo n.º 2
0
		public static void LoadRelations(nHydrateGeneratorProject project, bool assumeInheritance, string connectionString)
		{
			var root = (ModelRoot)project.RootController.Object;
			var dsRelationship = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForRelationships());
			foreach (DataRow rowRelationship in dsRelationship.Tables[0].Rows)
			{
				var constraintName = rowRelationship["FK_CONSTRAINT_NAME"].ToString();
				var parentTableName = (string)rowRelationship["UQ_TABLE_NAME"];
				var childTableName = (string)rowRelationship["FK_TABLE_NAME"];
				var parentTable = root.Database.Tables[parentTableName];
				var childTable = root.Database.Tables[childTableName];

				if ((parentTable != null) && (childTable != null))
				{
					Relation relation = null;
					var isAdd = false;
					if (!root.Database.Relations.Contains(constraintName))
					{
						var roleName = string.Empty;
						relation = root.Database.Relations.Add();
						relation.ParentTableRef = parentTable.CreateRef();
						relation.ChildTableRef = childTable.CreateRef();
						relation.ConstraintName = constraintName;
						var search = ("_" + childTable.DatabaseName + "_" + parentTable.DatabaseName).ToLower();
						roleName = constraintName.ToLower().Replace(search, string.Empty);
						if (roleName.Length >= 3) roleName = roleName.Remove(0, 3);
						var v = roleName.ToLower();
						if (v != "fk") relation.RoleName = v;
						isAdd = true;
					}
					else
					{
						relation = root.Database.Relations.GetByName(constraintName);
					}

					//add the column relationship to the relation
					var columnRelationship = new ColumnRelationship(relation.Root);
					var parentColumnName = (string)rowRelationship["UQ_COLUMN_NAME"];
					var childColumnName = (string)rowRelationship["FK_COLUMN_NAME"];
					var parentColumns = parentTable.GetColumns().ToList();
					var childColumns = childTable.GetColumns().ToList();
					if (parentColumns.Count(x => x.Name == parentColumnName) == 1 && (childColumns.Count(x => x.Name == childColumnName) == 1))
					{
						var parentColumn = parentTable.Columns[parentColumnName].Object as Column;
						var childColumn = childTable.Columns[childColumnName].Object as Column;
						columnRelationship.ParentColumnRef = parentColumn.CreateRef();
						columnRelationship.ChildColumnRef = childColumn.CreateRef();
						relation.ColumnRelationships.Add(columnRelationship);

						//ONLY ADD THIS RELATION IF ALL WENT WELL
						if (isAdd)
							parentTable.Relationships.Add(relation.CreateRef());
					}
					else
					{
						System.Diagnostics.Debug.Write(string.Empty);
					}
				} //Not Contains constraint

			}

			//Map parent tables if there is 1-1 relation and PK match
			//Make sure we have choosen to assume inheritance
			if (assumeInheritance)
			{
				foreach (Relation relation in root.Database.Relations)
				{
					if (relation.IsOneToOne)
					{
						var parentTable = (Table)relation.ParentTableRef.Object;
						var childTable = (Table)relation.ChildTableRef.Object;
						if (parentTable.PrimaryKeyColumns.Count == childTable.PrimaryKeyColumns.Count)
						{
							var pkMatch = true;
							foreach (var k in parentTable.PrimaryKeyColumns)
							{
								pkMatch |= (childTable.PrimaryKeyColumns.Count(x => x.Name == k.Name) == 1);
							}

							if (pkMatch && childTable.CanInherit(parentTable))
							{
								childTable.ParentTable = parentTable;
							}

						}
					}
				}
			}

			//Check for associative tables
			foreach (Relation relation in root.Database.Relations)
			{
				var parentTable = (Table)relation.ParentTableRef.Object;
				var childTable = (Table)relation.ChildTableRef.Object;
				//If there are 2 PK in the child table and that is all the columns
				//and it is a base table
				if ((childTable.PrimaryKeyColumns.Count == 2) &&
					(childTable.Columns.Count == 2) &&
					childTable.ParentTable == null)
				{
					//If child table has 2 relations comming in
					var allRelations = childTable.GetRelationsWhereChild();
					if (allRelations.Count() == 2)
					{
						//Relation relation2 = allRelations.FirstOrDefault(x => x != relation);
						//Table parentTable2 = (Table)relation2.ParentTableRef.Object;
						childTable.AssociativeTable = true;
					}
				}
			}

		}
Exemplo n.º 3
0
		private static void LoadViews(nHydrateGeneratorProject project, string connectionString)
		{
			var root = (ModelRoot)project.RootController.Object;
			var dsView = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForViews());
			var dsViewColumn = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForViewsColumns());

			//Add the Views
			if (dsView.Tables.Count > 0)
			{
				foreach (DataRow rowView in dsView.Tables[0].Rows)
				{
					var name = (string)rowView["name"];
					var sql = (string)rowView["definition"];
					var customView = root.Database.CustomViews.FirstOrDefault(x => x.Name == name);
					if (customView == null)
					{
						customView = ((ModelRoot)project.RootController.Object).Database.CustomViews.Add();
						customView.Name = name;
						var regEx = new Regex(@"CREATE VIEW.*[\r\n]*AS.*[\r\n]*([\s\S\r\n]*)");
						var match = regEx.Match(sql);
						if (match != null && match.Groups != null && match.Groups.Count == 2)
							sql = match.Groups[1].Value;

						customView.SQL = sql;
					}
				}
			}

			//Add the columns
			if (dsViewColumn.Tables.Count > 0)
			{
				foreach (DataRow rowView in dsViewColumn.Tables[0].Rows)
				{
					var viewName = (string)rowView["viewname"];
					var columnName = (string)rowView["columnname"];
					var length = int.Parse(rowView["max_length"].ToString());
					var customView = root.Database.CustomViews.FirstOrDefault(x => x.Name == viewName);
					if (customView != null)
					{
						var column = root.Database.CustomViewColumns.Add();
						column.Name = columnName;
						column.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(rowView["system_type_id"].ToString()));
						column.Length = length;
						column.Scale = int.Parse(rowView["scale"].ToString());
						customView.Columns.Add(column.CreateRef());
						column.ParentViewRef = customView.CreateRef();
					}
				}
			}

		}
Exemplo n.º 4
0
		/// <summary>
		/// Load a database schema
		/// </summary>
		/// <param name="project">The project object to load from database</param>
		/// <param name="refreshModel">Determines whether to load all model controllers and other UI components</param>
		public static bool GetProjectFromSqlSchema(nHydrateGeneratorProject project, string connectionString, bool refreshModel, bool assumeInheritance)
		{
			try
			{
				if (!IsValidConnectionString(connectionString))
				{
					//this.OnProgress(new ProgressEventArgs() { PercentDone = 100 });
					GenerationHelper.ShowError("The SQL Server engine could not be found.");
					return false;
				}

				if (!IsSupportedSQLVersion(connectionString))
				{
					//this.OnProgress(new ProgressEventArgs() { PercentDone = 100 });
					GenerationHelper.ShowError("The current version of SQL is not supported.");
					return false;
				}

				var root = project.RootController.Object as ModelRoot;
				SetupNewProject(project, connectionString);
				var databaseCollation = GetDatabaseCollation(connectionString);

				//var root = project.RootController.Object as ModelRoot;
				//var companyName = GetCompanyName(connectionString);
				//var projectName = GetProjectName(connectionString);
				//var databaseName = GetDatabaseName(connectionString);
				//var databaseCollation = GetDatabaseCollation(connectionString);
				
				//if (!string.IsNullOrEmpty(companyName))
				//  root.CompanyName = companyName;
				//if (!string.IsNullOrEmpty(projectName))
				//  root.ProjectName = projectName;
				//if (!string.IsNullOrEmpty(databaseName))
				//  root.Database.DatabaseName = databaseName;
				//root.Version = "0.0.0.0";
				//root.SQLServerType = GetSQLVersion(connectionString);

				//root.Database.Columns.Clear();
				//root.Database.Relations.Clear();
				//root.Database.Tables.Clear();

				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 0, Text = "Loading..." });

				var tableCount = GetTableCount(connectionString);
				var tableIndex = 1;

				#region Tables

				var tableReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlDatabaseTables());
				while (tableReader.Read())
				{
					var startTime1 = DateTime.Now;

					var currentTable = root.Database.Tables.Add(tableReader["name"].ToString());
					currentTable.DBSchema = tableReader["schema"].ToString();

					////Progress
					//this.OnProgress(new ProgressEventArgs()
					//{
					//  PercentDone = (int)(tableIndex * 100.0 / tableCount),
					//  Text = currentTable.Name
					//});

					if (!ValidationHelper.ValidDatabaseIdenitifer(currentTable.Name))
					{
						currentTable.CodeFacade = ValidationHelper.MakeDatabaseIdentifier(currentTable.Name);
					}

					//If single field table with identity then mark it immutable
					if ((currentTable.Columns.Count == 1) && (currentTable.GetColumns().First().Identity == IdentityTypeConstants.Database))
					{
						currentTable.Immutable = true;
					}

					//Default to false when importing
					currentTable.AllowCreateAudit = false;
					currentTable.AllowModifiedAudit = false;
					currentTable.AllowTimestamp = false;

					#region Table Attributes
					if (CanUseExtendedProperty(connectionString))
					{
						var tableAttributeReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT name, value FROM  ::fn_listextendedproperty (default,'user', 'dbo', 'table', '" + currentTable.Name + "', default, default)");
						while (tableAttributeReader.Read())
						{
							var attribName = string.Empty;
							attribName = tableAttributeReader["name"].ToString();
							if (attribName.ToLower().Equals("ms_description"))
							{
								currentTable.Description = tableAttributeReader["value"].ToString();
							}
							else if (attribName.ToLower().Equals("generated"))
							{
								currentTable.Generated = bool.Parse(tableAttributeReader["value"].ToString());
							}
							else if (attribName.ToLower().Equals("associative"))
							{
								currentTable.AssociativeTable = bool.Parse(tableAttributeReader["value"].ToString());
							}
							else if (attribName.ToLower().Equals("hasHistory"))
							{
								currentTable.HasHistory = bool.Parse(tableAttributeReader["value"].ToString());
							}
							System.Windows.Forms.Application.DoEvents();
						}
						tableAttributeReader.Close();
					}
					#endregion

					//System.Windows.Forms.Application.DoEvents();

					var endTime1 = DateTime.Now;
					//System.Diagnostics.Debug.WriteLine("Table '" + currentTable.Name + "': " + endTime1.Subtract(startTime1).TotalMilliseconds.ToString("###,###,###"));

					if (currentTable.Name == "sysdiagrams" ||
						currentTable.Name == "__nhydrateschema")
					{
						root.Database.Tables.Remove(currentTable);
					}
					tableIndex++;

				}
				tableReader.Close();

				#region Columns

					var startTime2 = DateTime.Now;
					var columnReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlColumnsForTable());
					while (columnReader.Read())
					{
						var columnName = columnReader["columnName"].ToString();
						var tableName = columnReader["tableName"].ToString();

						var currentTable = root.Database.Tables.FirstOrDefault(x => x.Name == tableName);
						if (currentTable != null)
						{
							if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.CreatedByColumnName) ||
								StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.CreatedDateColumnName))
							{
								currentTable.AllowCreateAudit = true;
							}
							else if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.ModifiedByColumnName) ||
								StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.ModifiedDateColumnName) ||
								StringHelper.Match(columnName, "updated_by") || StringHelper.Match(columnName, "updated_date"))
							{
								currentTable.AllowModifiedAudit = true;
							}
							else if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.TimestampColumnName))
							{
								currentTable.AllowTimestamp = true;
							}
							else
							{
								var currentColumn = root.Database.Columns.Add(columnName);

								if (!ValidationHelper.ValidDatabaseIdenitifer(currentColumn.Name))
								{
									currentColumn.CodeFacade = ValidationHelper.MakeDatabaseIdentifier(currentColumn.Name);
								}

								currentColumn.ParentTableRef = currentTable.CreateRef();
								currentColumn.AllowNull = bool.Parse(columnReader["allowNull"].ToString());
								if (bool.Parse(columnReader["isIdentity"].ToString()))
									currentColumn.Identity = IdentityTypeConstants.Database;
								else
									currentColumn.Identity = IdentityTypeConstants.None;

								if (columnReader["isPrimaryKey"] != System.DBNull.Value)
									currentColumn.PrimaryKey = true;

								//currentColumn.PrimaryKey = bool.Parse(columnReader["isPrimaryKey"].ToString());
								try
								{
									//string columnTypename = columnReader["datatype"].ToString();
									//if (StringHelper.Match(columnTypename, "numeric", true))
									//  currentColumn.DataType = SqlDbType.Decimal;
									//else
									//  currentColumn.DataType = (SqlDbType)Enum.Parse(typeof(SqlDbType), columnTypename, true);
									currentColumn.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(columnReader["xtype"].ToString()));
								}
								catch { }

								var defaultvalue = columnReader["defaultValue"].ToString();
								SetupDefault(currentColumn, defaultvalue);

								currentColumn.Length = (int)columnReader["length"];

								//Decimals are a little different
								if (currentColumn.DataType == SqlDbType.Decimal)
								{
									currentColumn.Length = (byte)columnReader["precision"];
									currentColumn.Scale = (int)columnReader["scale"];
								}

								if (columnReader["collation"] != System.DBNull.Value)
								{
									if (databaseCollation != (string)columnReader["collation"])
										currentColumn.Collate = (string)columnReader["collation"];
								}

								currentTable.Columns.Add(currentColumn.CreateRef());
							} //Create New Column
						}
					}
					columnReader.Close();
					var endTime2 = DateTime.Now;
					//System.Diagnostics.Debug.WriteLine("Table '" + currentTable.Name + "' Load Columns: " + endTime2.Subtract(startTime2).TotalMilliseconds.ToString("###,###,###"));

					if (CanUseExtendedProperty(connectionString))
					{
						foreach (Table table in root.Database.Tables)
						{
							foreach (var column in table.GetColumns())
							{
								var startTime3 = DateTime.Now;
								var columnAttributeReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT name, value FROM  ::fn_listextendedproperty (default,'user', 'dbo', 'table', '" + table.Name + "', 'column', '" + column.Name + "')");
								while (columnAttributeReader.Read())
								{
									var attribName = string.Empty;
									attribName = columnAttributeReader["name"].ToString();
									if (attribName.ToLower().Equals("ms_description"))
									{
										column.Description = columnAttributeReader["value"].ToString();
									}
								}
								columnAttributeReader.Close();
								var endTime3 = DateTime.Now;
								//System.Diagnostics.Debug.WriteLine("Time 3: " + endTime3.Subtract(startTime3).TotalMilliseconds.ToString("###,###,###"));
							}
						}
					}

				#endregion

				#region Columns Extra Info

				columnReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlColumnInfoAuxForTable());
				while (columnReader.Read())
				{
					var columnName = columnReader["columnname"].ToString();
					var tableName = columnReader["tablename"].ToString();
					var currentTable = root.Database.Tables.First(x => x.Name == tableName);

					var currentColumn = root.Database.Columns[columnName];
					if (currentColumn != null)
					{
						currentColumn.ComputedColumn = true;
						currentColumn.Formula = columnReader["definition"].ToString();
					}
				}
				columnReader.Close();

				#endregion

				#region Indexes

				var indexReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlIndexesForTable());
				while (indexReader.Read())
				{
					var indexName = indexReader["indexname"].ToString();
					var columnName = indexReader["columnname"].ToString();
					var tableName = indexReader["tableName"].ToString();
					var currentTable = root.Database.Tables.FirstOrDefault(x => x.Name == tableName);
					if (currentTable != null)
					{
						var pk = bool.Parse(indexReader["is_primary_key"].ToString());
						var column = currentTable.GetColumns().FirstOrDefault(x => x.Name == columnName);
						if (column != null && !pk)
							column.IsIndexed = true;
					}
				}

				#endregion

				#endregion

				#region Relations

				var startTimeRelation = DateTime.Now;
				LoadRelations(project, assumeInheritance, connectionString);
				var endTimeRelation = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Relations: " + endTimeRelation.Subtract(startTimeRelation).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				#region Views

				var startTimeV = DateTime.Now;
				LoadViews(project, connectionString);
				var endTimeV = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Views: " + endTimeV.Subtract(startTimeV).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				#region Stored Procedures

				var startTimeSP = DateTime.Now;
				LoadStoredProcedures(project, connectionString);
				var endTimeSP = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Stored Procedures: " + endTimeSP.Subtract(startTimeSP).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				//Refresh the tree
				if (refreshModel)
				{
					//project.RootController.Node.RefreshDeep();
					//Thread t = new Thread(new ThreadStart(project.RootController.Node.RefreshDeep));
					//t.Start();
				}

				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 100, Text = "Complete" });
				return true;
			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 100, Text = "Complete" });
			}
		}
Exemplo n.º 5
0
		//private string _connectString;
		//private bool _assumeInheritance = true;

		#endregion

		#region Constructors

		//public SqlSchemaToModel(string connectString, bool assumeInheritance)
		//{
		//  this._connectString = connectString;
		//  _assumeInheritance = assumeInheritance;
		//}

		#endregion

		//#region Events

		//public event EventHandler<ProgressEventArgs> Progress;

		//protected virtual void OnProgress(ProgressEventArgs e)
		//{
		//  if (this.Progress != null)
		//    this.Progress(this, e);
		//}

		//#endregion

		///// <summary>
		///// Load a database schema
		///// </summary>
		///// <param name="project">The project object to load from database</param>
		//public bool GetProjectFromSqlSchema(nHydrateGeneratorProject project)
		//{
		//  return this.GetProjectFromSqlSchema(project, true);
		//}

		public static void SetupNewProject(nHydrateGeneratorProject project, string connectionString)
		{
			var root = project.RootController.Object as ModelRoot;
			var companyName = GetCompanyName(connectionString);
			var projectName = GetProjectName(connectionString);
			var databaseName = GetDatabaseName(connectionString);
			var databaseCollation = GetDatabaseCollation(connectionString);

			if (!string.IsNullOrEmpty(companyName))
				root.CompanyName = companyName;
			if (!string.IsNullOrEmpty(projectName))
				root.ProjectName = projectName;
			if (!string.IsNullOrEmpty(databaseName))
				root.Database.DatabaseName = databaseName;
			root.Version = "0.0.0.0";
			root.SQLServerType = GetSQLVersion(connectionString);

			root.Database.Columns.Clear();
			root.Database.Relations.Clear();
			root.Database.Tables.Clear();
		}
Exemplo n.º 6
0
        private static void ProcessRenamed(string lastGenFile, ModelRoot root)
        {
            if (!File.Exists(lastGenFile)) return;

            var genProjectLast = new nHydrateGeneratorProject();
            var xDoc = new XmlDocument();
            xDoc.Load(lastGenFile);
            genProjectLast.XmlLoad(xDoc.DocumentElement);

            var oldRoot = (genProjectLast.RootController.Object as nHydrate.Generator.Models.ModelRoot);
            foreach (nHydrate.Generator.Models.Table t in root.Database.Tables)
            {
                //Find renamed tables
                {
                    var renamedItem = oldRoot.Database.Tables.FirstOrDefault(x => x.Key == t.Key && x.PascalName.ToLower() != t.PascalName.ToLower());
                    if (renamedItem != null)
                        root.RemovedTables.Add(renamedItem.Name);
                }

                //Find renamed views
                {
                    var renamedItem = oldRoot.Database.CustomViews.FirstOrDefault(x => x.Key == t.Key && x.PascalName.ToLower() != t.PascalName.ToLower());
                    if (renamedItem != null)
                        root.RemovedViews.Add(renamedItem.Name);
                }

                //Find renamed stored procedures
                {
                    var renamedItem = oldRoot.Database.CustomStoredProcedures.FirstOrDefault(x => x.Key == t.Key && x.PascalName.ToLower() != t.PascalName.ToLower());
                    if (renamedItem != null)
                        root.RemovedStoredProcedures.Add(renamedItem.Name);
                }

                //Find renamed functions
                {
                    var renamedItem = oldRoot.Database.Functions.FirstOrDefault(x => x.Key == t.Key && x.PascalName.ToLower() != t.PascalName.ToLower());
                    if (renamedItem != null)
                        root.RemovedFunctions.Add(renamedItem.Name);
                }

            }

        }
Exemplo n.º 7
0
        private List<nHydrateGeneratorProject> BuildModelList(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
        {
            var genList = new List<nHydrateGeneratorProject>();

            if (model.UseModules)
            {
                foreach (var module in model.Modules)
                {
                    var genProject = new nHydrateGeneratorProject();
                    genList.Add(genProject);
                    var root = CreatePOCOModel(model, diagram, module);
                    root.SetKey(module.Id.ToString());
                    root.GeneratorProject = genProject;
                    genProject.RootController.Object = root;
                    var fi = new System.IO.FileInfo(docData.FileName);
                    genProject.FileName = docData.FileName + "." + module.Name + ".generating";
                    var document = new System.Xml.XmlDocument();
                    document.LoadXml("<modelRoot guid=\"" + module.Id + "\" type=\"nHydrate.Generator.nHydrateGeneratorProject\" assembly=\"nHydrate.Generator.dll\"><ModelRoot></ModelRoot></modelRoot>");
                    ((nHydrate.Generator.Common.GeneratorFramework.IXMLable)root).XmlAppend(document.DocumentElement.ChildNodes[0]);
                    System.IO.File.WriteAllText(genProject.FileName, document.ToIndentedString());

                    ProcessRenamed(genProject.FileName + ".sql.lastgen", root);

                    root.RemovedTables.AddRange(model.RemovedTables);
                    root.RemovedViews.AddRange(model.RemovedViews);
                    root.RemovedStoredProcedures.AddRange(model.RemovedStoredProcedures);
                    root.RemovedFunctions.AddRange(model.RemovedFunctions);

                    //Remove associative tables since they cause issues if they exist
                    root.RemovedTables.AddRange(model.Entities.Where(x => x.IsAssociative && x.IsGenerated).Select(x => x.Name));
                    //Remove non-generated items from the project
                    root.RemovedTables.AddRange(model.Entities.Where(x => !x.IsGenerated).Select(x => x.Name));
                    root.RemovedTables.AddRange(model.Views.Where(x => !x.IsGenerated).Select(x => x.Name));
                    root.RemovedTables.AddRange(model.StoredProcedures.Where(x => !x.IsGenerated).Select(x => x.Name));
                    root.RemovedTables.AddRange(model.Functions.Where(x => !x.IsGenerated).Select(x => x.Name));
                    //Remove EnumOnly type-tables from the project
                    root.RemovedTables.AddRange(model.Entities.Where(x => x.TypedEntity == TypedEntityConstants.EnumOnly && x.IsGenerated).Select(x => x.Name));
                }
            }
            else
            {
                var genProject = new nHydrateGeneratorProject();
                genList.Add(genProject);
                var root = CreatePOCOModel(model, diagram, null);
                root.SetKey(model.Id.ToString());
                root.GeneratorProject = genProject;
                genProject.RootController.Object = root;
                var fi = new System.IO.FileInfo(docData.FileName);
                genProject.FileName = docData.FileName + ".generating";
                var document = new System.Xml.XmlDocument();
                document.LoadXml("<modelRoot guid=\"" + model.Id + "\" type=\"nHydrate.Generator.nHydrateGeneratorProject\" assembly=\"nHydrate.Generator.dll\"><ModelRoot></ModelRoot></modelRoot>");
                ((nHydrate.Generator.Common.GeneratorFramework.IXMLable)root).XmlAppend(document.DocumentElement.ChildNodes[0]);
                System.IO.File.WriteAllText(genProject.FileName, document.ToIndentedString());

                ProcessRenamed(genProject.FileName + ".sql.lastgen", root);

                root.RemovedTables.AddRange(model.RemovedTables);
                root.RemovedViews.AddRange(model.RemovedViews);
                root.RemovedStoredProcedures.AddRange(model.RemovedStoredProcedures);
                root.RemovedFunctions.AddRange(model.RemovedFunctions);

                //Remove associative tables since they cause issues if they exist
                root.RemovedTables.AddRange(model.Entities.Where(x => x.IsAssociative && x.IsGenerated).Select(x => x.Name));
                //Remove non-generated items from the project
                root.RemovedTables.AddRange(model.Entities.Where(x => !x.IsGenerated).Select(x => x.Name));
                root.RemovedTables.AddRange(model.Views.Where(x => !x.IsGenerated).Select(x => x.Name));
                root.RemovedTables.AddRange(model.StoredProcedures.Where(x => !x.IsGenerated).Select(x => x.Name));
                root.RemovedTables.AddRange(model.Functions.Where(x => !x.IsGenerated).Select(x => x.Name));
                //Remove EnumOnly type-tables from the project
                root.RemovedTables.AddRange(model.Entities.Where(x => x.TypedEntity == TypedEntityConstants.EnumOnly && x.IsGenerated).Select(x => x.Name));

            }

            return genList;
        }