Ejemplo n.º 1
0
        private static string GerarSolectNode(SqlTable sqlTable, SqlReference sref, int seq)
        {
            StringBuilder builder  = new StringBuilder();
            StringBuilder builder2 = new StringBuilder();
            SqlTable      table    = SqlTable.GetTable(sref.PkTable);

            if (seq == 0)
            {
                sref = sqlTable.References[1];
            }
            else
            {
                sref = sqlTable.References[0];
            }
            if (seq == 0)
            {
                if (sqlTable.Colunas[1].SqlDataType != "text")
                {
                    builder2.Append(sqlTable.Colunas[1].NetDataType + " " + sqlTable.Colunas[1].Name + "_, ");
                }
            }
            else
            {
                if (sqlTable.Colunas[0].SqlDataType != "text")
                {
                    builder2.Append(sqlTable.Colunas[0].NetDataType + " " + sqlTable.Colunas[0].Name + "_, ");
                }
            }
            builder.AppendLine(string.Concat(new object[] { "\t\t/// <summary>\n\t\t/// Busca os " + table.ClassBusinessNome + " na base atrav\x00e9s do parametro\n\t\t/// </summary>\n\t\tpublic DbDataReader Get_", table.ClassBusinessNome, "(", builder2.Remove(builder2.Length - 2, 2), ")" }));
            builder.AppendLine("\t\t{");
            builder.AppendLine("\t\t\ttry");
            builder.AppendLine("\t\t\t{");
            builder.AppendLine("\t\t\t\tcmd = new SqlCommand();");
            builder.AppendLine("\t\t\t\tcmd.CommandType = CommandType.StoredProcedure;");
            builder.AppendLine("\t\t\t\tcmd.CommandText = \"usp_" + Program.sulfixSelect + sqlTable.ProcNome + "\";");
            if (seq == 0)
            {
                if (sqlTable.Colunas[1].SqlDataType != "text")
                {
                    builder.AppendLine("\t\t\t\tcmd.Parameters.AddWithValue(\"@" + sref.FkColumnName + "\", " + sqlTable.Colunas[1].Name + "_);");
                }
            }
            else
            {
                if (sqlTable.Colunas[0].SqlDataType != "text")
                {
                    builder.AppendLine("\t\t\t\tcmd.Parameters.AddWithValue(\"@" + sref.FkColumnName + "\", " + sqlTable.Colunas[0].Name + "_);");
                }
            }
            builder.AppendLine();
            builder.AppendLine(Tab(4) + "OpenConnection();");
            builder.AppendLine("\t\t\t\treturn cmd.ExecuteReader(CommandBehavior.CloseConnection);");
            builder.AppendLine("\t\t\t}");
            builder.AppendLine("\t\t\tcatch (SqlException sex){ throw sex; }");
            builder.AppendLine("\t\t\tcatch (Exception ex){ throw ex; }");
            builder.AppendLine("\t\t}");
            return(builder.ToString());
        }
Ejemplo n.º 2
0
        private static string GerarSolectNode2(SqlTable sqlTable)
        {
            StringBuilder builder  = new StringBuilder();
            StringBuilder builder2 = new StringBuilder();
            SqlTable      table    = SqlTable.GetTable(sqlTable.References[0].PkTable);
            SqlTable      table2   = SqlTable.GetTable(sqlTable.References[1].PkTable);

            builder2.Append(table2.GetIdentityColumn().NetDataType + " " + table2.GetIdentityColumn().Name + "_, ");
            builder.AppendLine(string.Concat(new object[] { "\t\t/// <summary>\n\t\t/// Busca os " + table.ClassBusinessNome + " na base atrav\x00e9s do par\x00e2metro\n\t\t/// </summary>\n\t\tpublic DbDataReader Get_", table.ClassBusinessNome, "(", builder2.Remove(builder2.Length - 2, 2), ")" }));
            builder.AppendLine("\t\t{");
            builder.AppendLine("\t\t\ttry");
            builder.AppendLine("\t\t\t{");
            builder.AppendLine("\t\t\t\tcmd = new SqlCommand();");
            builder.AppendLine("\t\t\t\tcmd.CommandType = CommandType.StoredProcedure;");
            string str = "";

            str += "\t\t\t\tcmd.CommandText = \"usp_";
            str += Program.sulfixSelect;
            str += table.ClassBusinessNome;
            str += "By";
            str += table2.GetIdentityColumn().Name[0].ToString().ToUpper() + table2.GetIdentityColumn().Name.Substring(1);
            str += "\";";
            builder.AppendLine(str);
            builder.AppendLine("\t\t\t\tcmd.Parameters.AddWithValue(\"@" + table2.GetIdentityColumn().Name + "\", " + table2.GetIdentityColumn().Name + "_);");
            builder.AppendLine();
            builder.AppendLine(Tab(4) + "OpenConnection();");
            builder.AppendLine("\t\t\t\treturn cmd.ExecuteReader(CommandBehavior.CloseConnection);");
            builder.AppendLine("\t\t\t}");
            builder.AppendLine("\t\t\tcatch (SqlException sex){ throw sex; }");
            builder.AppendLine("\t\t\tcatch (Exception ex){ throw ex; }");
            builder.AppendLine("\t\t}");
            builder.AppendLine();
            builder.AppendLine();
            StringBuilder builder3 = new StringBuilder();

            builder3.Append(table.GetIdentityColumn().NetDataType + " " + table.GetIdentityColumn().Name + "_, ");
            builder.AppendLine(string.Concat(new object[] { "\t\t/// <summary>\n\t\t/// Busca os " + table2.ClassBusinessNome + " na base atrav\x00e9s do par\x00e2metro\n\t\t/// </summary>\n\t\tpublic DbDataReader Get_", table2.ClassBusinessNome, "(", builder3.Remove(builder3.Length - 2, 2), ")" }));
            builder.AppendLine("\t\t{");
            builder.AppendLine("\t\t\ttry");
            builder.AppendLine("\t\t\t{");
            builder.AppendLine("\t\t\t\tcmd = new SqlCommand();");
            builder.AppendLine("\t\t\t\tcmd.CommandType = CommandType.StoredProcedure;");
            builder.AppendLine("\t\t\t\tcmd.CommandText = \"usp_" + Program.sulfixSelect + table2.ClassBusinessNome + "By" + table.GetIdentityColumn().Name[0].ToString().ToUpper() + table.GetIdentityColumn().Name.Substring(1) + "\";");
            builder.AppendLine("\t\t\t\tcmd.Parameters.AddWithValue(\"@" + table.GetIdentityColumn().Name + "\", " + table.GetIdentityColumn().Name + "_);");
            builder.AppendLine();
            builder.AppendLine(Tab(4) + "OpenConnection();");
            builder.AppendLine("\t\t\t\treturn cmd.ExecuteReader(CommandBehavior.CloseConnection);");
            builder.AppendLine("\t\t\t}");
            builder.AppendLine("\t\t\tcatch (SqlException sex){ throw sex; }");
            builder.AppendLine("\t\t\tcatch (Exception ex){ throw ex; }");
            builder.AppendLine("\t\t}");
            return(builder.ToString());
        }
Ejemplo n.º 3
0
        private void CarregarCombosColumns()
        {
            SqlTable table  = null;
            SqlTable table2 = null;

            if (this.cmbPkt.SelectedItem != null)
            {
                table = SqlTable.GetTable(this.cmbPkt.SelectedItem.ToString());
                this.cmbPKColumn.DisplayMember = "Name";
                this.cmbPKColumn.DataSource    = table.Colunas;
            }
            if (this.cmbFkT.SelectedItem != null)
            {
                table2 = SqlTable.GetTable(this.cmbFkT.SelectedItem.ToString());
                this.cmbFKColumn.DisplayMember = "Name";
                this.cmbFKColumn.DataSource    = table2.Colunas;
            }
        }
Ejemplo n.º 4
0
        public static string GerarSelect(SqlTable sqlTable)
        {
            string str = "";

            if (!sqlTable.IsTableNo)
            {
                str = str + string.Format("-- *****************************************************\n-- *** Criado em ........ {0}\n-- *** Criado por ....... CSGen\n-- *** Descricao ........ Procedure criada para {1} registros na tabela {2}\n-- *** Alterado em ......\n-- *** Alterado por .....\n-- *** Motivo alteracao .\n-- *****************************************************\n\n", string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.Now), "selecionar", sqlTable.Nome);
                str = str + string.Format("IF EXISTS (SELECT * FROM sysobjects \nWHERE name = N'{0}'\nAND type = 'P')\nDROP PROCEDURE {0} \n#go#\n\n", string.Format("usp_{1}{0}", sqlTable.ProcNome, Program.sulfixSelect)) + string.Format("create proc usp_{1}{0}\n", sqlTable.ProcNome, Program.sulfixSelect) + GerarParametros(sqlTable.Colunas) + "set nocount on\n";
                string str2 = "";
                foreach (SqlColumn column in sqlTable.Colunas)
                {
                    str2 = str2 + "" + column.Name + ", ";
                }
                if (str2 != string.Empty)
                {
                    str2 = str2.Remove(str2.Length - 2, 1);
                }
                string str3 = str;
                str = str3 + "select " + str2 + " from " + sqlTable.Nome + " where \n";
                foreach (SqlColumn column2 in sqlTable.Colunas)
                {
                    if (column2.SqlDataType != "text")
                    {
                        string str11 = str;
                        str = str11 + "(" + column2.Name + " = @" + column2.Name + " or @" + column2.Name + " is null) and \n";
                    }
                }
                return(str.Substring(0, str.Length - 6));
            }
            List <SqlTable> list = new List <SqlTable>();

            foreach (SqlReference reference in sqlTable.References)
            {
                list.Add(SqlTable.GetTable(reference.PkTable));
            }
            for (int i = 0; i < list.Count; i++)
            {
                string str4;
                string str5;
                char   ch;
                str = str + string.Format("-- *****************************************************\n-- *** Criado em ........ {0}\n-- *** Criado por ....... CSGen\n-- *** Descricao ........ Procedure criada para {1} registros na tabela {2}\n-- *** Alterado em ......\n-- *** Alterado por .....\n-- *** Motivo alteracao .\n-- *****************************************************\n\n", string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.Now), "selecionar ", sqlTable.Nome + " & " + list[i].Nome);
                if (list.Count > 1)
                {
                    if (i == 0)
                    {
                        ch   = list[1].Colunas[0].Name[0];
                        str4 = SqlTable.GetBusinessClassName(sqlTable.References[0].PkTable) + "By" + ch.ToString().ToUpper() + list[1].Colunas[0].Name.Substring(1);
                        str5 = string.Format("IF EXISTS (SELECT * FROM sysobjects WHERE name = N'{0}' AND type = 'P') DROP PROCEDURE {0} \n#go#\n\n", string.Format("usp_{1}{0}", str4, Program.sulfixSelect));
                        string str6 = str + str5 + string.Format("create proc usp_{1}{0}", str4 + "\n", Program.sulfixSelect);
                        str = str6 + "@" + list[1].Colunas[0].Name + " " + list[1].Colunas[0].SqlDataType;
                    }
                    else
                    {
                        ch   = list[0].Colunas[0].Name[0];
                        str4 = SqlTable.GetBusinessClassName(sqlTable.References[1].PkTable) + "By" + ch.ToString().ToUpper() + list[0].Colunas[0].Name.Substring(1);
                        str5 = string.Format("IF EXISTS (SELECT * FROM sysobjects WHERE name = N'{0}' AND type = 'P') DROP PROCEDURE {0} \n#go#\n\n", string.Format("usp_{1}{0}", str4, Program.sulfixSelect));
                        string str7 = str + str5 + string.Format("create proc usp_{1}{0}", str4 + "\n", Program.sulfixSelect);
                        str = str7 + "@" + list[0].Colunas[0].Name + " " + list[0].Colunas[0].SqlDataType;
                    }
                }
                else if (list.Count == 1)
                {
                    ch   = list[0].Colunas[0].Name[0];
                    str4 = SqlTable.GetBusinessClassName(sqlTable.References[0].PkTable) + "By" + ch.ToString().ToUpper() + list[0].Colunas[0].Name.Substring(1);
                    str5 = string.Format("IF EXISTS (SELECT * FROM sysobjects WHERE name = N'{0}' AND type = 'P') DROP PROCEDURE {0} \n#go#\n\n", string.Format("usp_{1}{0}", str4, Program.sulfixSelect));
                    string str7 = str + str5 + string.Format("create proc usp_{1}{0}", str4 + "\n", Program.sulfixSelect);
                    str = str7 + "@" + list[0].Colunas[0].Name + " " + list[0].Colunas[0].SqlDataType;
                }

                str = str + "\nas\nset nocount on\nselect ";
                foreach (SqlColumn column3 in list[i].Colunas)
                {
                    str = str + column3.Name + ", ";
                }
                str = str.Remove(str.Length - 2, 2);
                if (list.Count > 1)
                {
                    switch (i)
                    {
                    case 0:
                    {
                        string str8 = str;
                        str = str8 + " from " + list[i].Nome + " \nwhere " + list[0].Colunas[0].Name + " in \n(\n\tselect " + sqlTable.References[0].PkColumnName + " from " + sqlTable.Nome + " \n\twhere " + sqlTable.References[1].PkColumnName + " = @" + list[1].Colunas[0].Name + "\n)";
                        break;
                    }

                    case 1:
                    {
                        string str9 = str;
                        str = str9 + " from " + list[i].Nome + " \nwhere " + list[1].Colunas[0].Name + " in \n(\n\tselect " + sqlTable.References[1].PkColumnName + " from " + sqlTable.Nome + " \n\twhere " + sqlTable.References[0].PkColumnName + " = @" + list[0].Colunas[0].Name + "\n)";
                        break;
                    }
                    }
                }
                else if (list.Count == 1)
                {
                    string str9 = str;
                    str = str9 + " from " + list[0].Nome + " \nwhere " + list[0].Colunas[0].Name + " in \n(\n\tselect " + sqlTable.References[0].PkColumnName + " from " + sqlTable.Nome + " \n\twhere " + sqlTable.References[0].PkColumnName + " = @" + list[0].Colunas[0].Name + "\n)";
                    break;
                }
                str = str + "\n\n#go#\n\n\n";
            }
            return(str);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates ot updates the database.
        /// </summary>
        /// <param name="create"></param>
        /// <param name="checkOnly"></param>
        // mbr - 28-09-2007 - case 814 - added args.
        private DatabaseUpdateCheckResults CreateUpdateDatabase(IOperationItem operation, bool create, bool checkOnly,
                                                                DatabaseUpdateArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            // operation...
            if (operation == null)
            {
                operation = new OperationItem();
            }

            // set...
            operation.Status = "Loading existing schema...";

            // database...
            SqlSchema databaseSchema = null;

            if (create)
            {
                databaseSchema = new SqlSchema();
            }
            else
            {
                if (args.Trace)
                {
                    this.LogInfo(() => "Loading schema...");
                }

                // mbr - 28-09-2007 - case 814 - defer to a method that can limit the types...
//				databaseSchema = Database.GetSchema();fic
                databaseSchema = this.GetSchema(args);
                if (databaseSchema == null)
                {
                    throw new InvalidOperationException("databaseSchema is null.");
                }
            }

            // Create an entity schema
            SqlSchema entitySchema = new SqlSchema();

            // Load all the entity types from the path
            ArrayList entityTypes = new ArrayList();

            // mbr - 02-10-2007 - for c7 - changed so that we can limit the entity types...
            if (args.LimitEntityTypes.Count == 0)
            {
                // mbr - 04-10-2007 - case 851 - do not do this behaviour (oddly both of these statements are
                // actually identical),
//				entityTypes.AddRange(EntityType.GetAllEntityTypes());
//				this.MergeEntityTypes(entityTypes, EntityType.LoadFromAttributes(AssemblyPath));
//				foreach(Assembly asm in this.Assemblies)
//					this.MergeEntityTypes(entityTypes, EntityType.LoadFromAttributes(asm));

                // load...
                this.MergeEntityTypes(entityTypes, EntityType.GetEntityTypes());
            }
            else
            {
                this.MergeEntityTypes(entityTypes, args.LimitEntityTypes);
            }

            // log...
            if (args.Trace)
            {
                this.LogInfo(() => string.Format("Found '{0}' entity types.", entityTypes.Count));
            }

            // steps...
            DatabaseUpdateStepCollection steps = new DatabaseUpdateStepCollection();

            if (args.AddArrayParameterUdts)
            {
                steps.Add(new AddArrayParameterUdtsUpdateStep());
            }

            SyncSchemaDatabaseUpdateStep syncStep = new SyncSchemaDatabaseUpdateStep();

            steps.Add(syncStep);

            // mbr - 02-03-2006 - we can have update steps that don't have an entity type...
            TypeFinder finder = new TypeFinder(typeof(DatabaseUpdateStep));

            finder.AddAttributeSpecification(typeof(DatabaseUpdateStepAttribute), false);
            Type[] stepTypes = finder.GetTypes();
            if (stepTypes == null)
            {
                throw new InvalidOperationException("stepTypes is null.");
            }

            // mbr - 02-10-2007 - for c7...
            if (Database.ExtensibilityProvider == null)
            {
                throw new InvalidOperationException("Database.ExtensibilityProvider is null.");
            }

            // Walk each entity type and add to entitySchema
            foreach (EntityType entityType in entityTypes)
            {
                // mbr - 14-12-2005 - should we do it?
                bool skip = entityType.Type.IsDefined(typeof(SkipDatabaseUpdateAttribute), false);

                // mbr - 2010-01-29 - changed the log here to allow db update to do named databases...
//				if(!(skip) && entityType.UsesDefaultDatabase)
                bool ok = false;
                if (!(skip))
                {
                    // no named database, and entity has no named database...
                    if (!(args.HasDatabaseName) && entityType.UsesDefaultDatabase)
                    {
                        ok = true;
                    }
                    else if (args.HasDatabaseName && string.Compare(entityType.DatabaseName, args.DatabaseName, true, Cultures.System) == 0)
                    {
                        ok = true;
                    }
                }
                else
                {
                    ok = false;
                }

                // do we do it?
                if (ok)
                {
                    if (args.Trace)
                    {
                        this.LogInfo(() => string.Format("Touching '{0}' ({1})...", entityType.Name, entityType.Type.Assembly.GetName().Name));
                    }

                    // add the base table...
                    SqlTable coreTable = SqlTable.GetTable(entitySchema, entityType);
                    if (coreTable == null)
                    {
                        throw new InvalidOperationException("coreTable is null.");
                    }
                    entitySchema.Tables.Add(coreTable);

                    // type...
                    Type type = entityType.Type;
                    if (type == null)
                    {
                        throw new InvalidOperationException("type is null.");
                    }

                    // reload it - something weird happens with these and they can't be used with the metadata so reload it so that we're
                    // certain we have the right ones...
                    type = Type.GetType(type.AssemblyQualifiedName, true, true);
                    if (type == null)
                    {
                        throw new InvalidOperationException("type is null.");
                    }

                    // mbr - 02-10-2007 - for c7 - add other tables that we need...
                    Database.ExtensibilityProvider.AddSchemaTables(entityType, type, coreTable, entitySchema);

                    // add the custom units...
                    foreach (Type stepType in stepTypes)
                    {
                        // get the attribute...
                        DatabaseUpdateStepAttribute[] attrs = (DatabaseUpdateStepAttribute[])stepType.GetCustomAttributes(typeof(DatabaseUpdateStepAttribute), true);
                        if (attrs == null)
                        {
                            throw new InvalidOperationException("attrs is null.");
                        }

                        // walk...
                        foreach (DatabaseUpdateStepAttribute attr in attrs)
                        {
                            if (attr.EntityType != null && attr.EntityType.IsAssignableFrom(type))
                            {
                                // create...
                                DatabaseUpdateStep step = (DatabaseUpdateStep)Activator.CreateInstance(stepType, new object[] { type });
                                if (step == null)
                                {
                                    throw new InvalidOperationException("step is null.");
                                }

                                // add..
                                steps.Add(step);
                            }
                        }
                    }
                }
                else
                {
                    if (args.Trace)
                    {
                        this.LogInfo(() => string.Format("Skipping '{0}'.", entityType.Name));
                    }
                }
            }

            // mbr - 02-10-2007 - for c7 - don't do custom steps if we're limiting entity types...
            if (args.LimitEntityTypes.Count == 0)
            {
                // do the ones that don't have entity types...
                foreach (Type stepType in stepTypes)
                {
                    // get the attribute...
                    DatabaseUpdateStepAttribute[] attrs = (DatabaseUpdateStepAttribute[])stepType.GetCustomAttributes(typeof(DatabaseUpdateStepAttribute), true);
                    if (attrs == null)
                    {
                        throw new InvalidOperationException("attrs is null.");
                    }

                    // walk...
                    foreach (DatabaseUpdateStepAttribute attr in attrs)
                    {
                        if (attr.EntityType == null)
                        {
                            // create...
                            DatabaseUpdateStep step = (DatabaseUpdateStep)Activator.CreateInstance(stepType);
                            if (step == null)
                            {
                                throw new InvalidOperationException("step is null.");
                            }

                            // add..
                            steps.Add(step);
                        }
                    }
                }
            }

            // get the work units...
            operation.Status = "Creating schema delta...";

            // mbr - 02-10-2007 - for c7 - changed to deferral.
//			syncStep.WorkUnits.AddRange(entitySchema.GetSchemaWorkUnits(databaseSchema, operation));
            syncStep.Initialize(entitySchema, databaseSchema);

            // run...
            if (!(checkOnly))
            {
                if (args.Trace)
                {
                    this.LogInfo(() => string.Format("Applying '{0}' steps...", steps.Count));
                }

                // context...
                DatabaseUpdateContext context = new DatabaseUpdateContext(operation, args.Trace);

                // mbr - 21-12-2005 - run the steps...
                foreach (DatabaseUpdateStep step in steps)
                {
                    try
                    {
                        if (args.Trace)
                        {
                            this.LogInfo(() => string.Format("Applying step: {0}", step));
                        }

                        // set...
                        operation.Status = string.Format("Running step '{0}'...", step);
                        step.Execute(context);
                    }
                    catch (Exception ex)
                    {
                        // log...
                        string message = string.Format("Failed database update when running step '{0}'.", step);
                        if (this.Log.IsErrorEnabled)
                        {
                            this.Log.Error(message, ex);
                        }

                        // throw...
                        throw new InvalidOperationException(message, ex);
                    }
                }
            }
            else
            {
                if (args.Trace)
                {
                    this.LogInfo(() => "Checking only -- not doing work.");
                }
            }

            if (args.Trace)
            {
                this.LogInfo(() => "Database update finished.");
            }

            this.OnUpdated();

            // return...
            return(new DatabaseUpdateCheckResults(steps));
        }