Пример #1
0
        private string Condicao(string pCampo, string pParametro, TpBanco pTipoBanco)
        {
            string strFormato = "";

            if (Operador == Operador.Igual || Operador == Operador.Nenhum)
            {
                strFormato = "{0} = {1}";
            }
            else if (Operador == Operador.Maior)
            {
                strFormato = "{0} > {1}";
            }
            else if (Operador == Operador.Menor)
            {
                strFormato = "{0} < {1}";
            }
            else if (Operador == Operador.MaiorIgual)
            {
                strFormato = "{0} >= {1}";
            }
            else if (Operador == Operador.MenorIgual)
            {
                strFormato = "{0} <= {1}";
            }
            else if (Operador == Operador.Diferente)
            {
                strFormato = "{0} <> {1}";
            }
            else if (Operador == Operador.Inicie)
            {
                strFormato = "{0} LIKE {1} + '%'";
            }
            else if (Operador == Operador.Termine)
            {
                strFormato = "{0} LIKE '%' + {1}";
            }
            else if (Operador == Operador.Contenha)
            {
                strFormato = "{0} LIKE '%' + {1} + '%'";
            }
            else if (Operador == Operador.Nulo)
            {
                strFormato = "{0} IS NULL";
            }
            else if (Operador == Operador.NaoNulo)
            {
                strFormato = "{0} IS NOT NULL";
            }
            else if (Operador == Operador.Vazio)
            {
                strFormato = "COALESCE({0}, '') = ''";
            }
            else if (Operador == Operador.DiferenteVazio)
            {
                strFormato = "COALESCE({0}, '') <> ''";
            }

            return(string.Format(strFormato, CampoTabela(pCampo, pTipoBanco), CampoVarivel(pCampo, pParametro, pTipoBanco)));
        }
Пример #2
0
        private string CampoTabela(string pCampo, TpBanco pTipoBanco)
        {
            string CampoTabela = string.Empty;

            if (TipoDados == DbType.Date)
            {
                switch (pTipoBanco)
                {
                case TpBanco.SqlServer:
                    CampoTabela = "CONVERT(DATE, [" + pCampo + "], 103)";
                    break;

                case TpBanco.Sqlite:
                    CampoTabela = "DATE(" + pCampo + ")";
                    break;

                case TpBanco.MySql:
                    CampoTabela = "CONVERT(" + pCampo + ", DATE)";
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else if (TipoDados == DbType.DateTime)
            {
                switch (pTipoBanco)
                {
                case TpBanco.SqlServer:
                    CampoTabela = "CONVERT(DATETIME, [" + pCampo + "], 120)";
                    break;

                case TpBanco.Sqlite:
                    CampoTabela = "DATETIME(" + pCampo + ")";
                    break;

                case TpBanco.MySql:
                    CampoTabela = "CONVERT(" + pCampo + ", DATETIME)";
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                CampoTabela = "[" + pCampo + "]";
            }
            return(CampoTabela);
        }
Пример #3
0
        private string CampoVarivel(string pCampo, string pParametro, TpBanco pTipoBanco)
        {
            string CampoVarivel = string.Empty;

            if (TipoDados == DbType.Date)
            {
                switch (pTipoBanco)
                {
                case TpBanco.SqlServer:
                    CampoVarivel = "CONVERT(DATE, " + pParametro + pCampo + ", 103)";
                    break;

                case TpBanco.Sqlite:
                    CampoVarivel = "DATE(" + pParametro + pCampo + ")";
                    break;

                case TpBanco.MySql:
                    CampoVarivel = $"STR_TO_DATE({pParametro}{pCampo},'%d-%m-%Y')";
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else if (TipoDados == DbType.DateTime)
            {
                switch (pTipoBanco)
                {
                case TpBanco.SqlServer:
                    CampoVarivel = "CONVERT(DATETIME, " + pParametro + pCampo + ", 120)";
                    break;

                case TpBanco.Sqlite:
                    CampoVarivel = "DATETIME(" + pParametro + pCampo + ")";
                    break;

                case TpBanco.MySql:
                    CampoVarivel = $"STR_TO_DATE({pParametro}{pCampo},'%Y-%m-%d %H:%i:%s')";
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                CampoVarivel = pParametro + pCampo;
            }
            return(CampoVarivel);
        }
Пример #4
0
        public string GetCondicao(string pParametro, TpBanco pTipoBanco)
        {
            string retorno = string.Empty;

            if (Valor.GetType().IsArray)
            {
                retorno = CampoTabela(Campo, pTipoBanco) + " IN (";
                for (int i = 0; i < ((Array)Valor).Length; i++)
                {
                    retorno += CampoVarivel(Campo + i, pParametro, pTipoBanco) + (i < ((Array)Valor).Length - 1 ? "," : string.Empty);
                }
                retorno += ")";
            }
            else
            {
                retorno = Condicao(Campo, pParametro, pTipoBanco);
            }
            return(retorno);
        }
Пример #5
0
        public static Tabela GetTabela(TpBanco pTpBanco, string pTabela, string pServidor, string pBanco, UserDB pUsuario, bool pQuery, string pComando)
        {
            Tabela tabela       = null;
            var    schemaTabela = pTabela.Split('.');
            string schema       = string.Empty;
            string tabelaNome   = pTabela;

            if (schemaTabela.Length > 1)
            {
                schema     = schemaTabela[0];
                tabelaNome = schemaTabela[1];
            }

            if (pQuery)
            {
                tabela = GetQueryInfo(pComando, pServidor, tabelaNome, pTpBanco, pUsuario, pBanco);
            }
            else
            {
                switch (pTpBanco)
                {
                case TpBanco.SqlServer:
                    tabela = DataBase.SqlServer.GetTabelaInfo(tabelaNome, pServidor, pBanco, pUsuario, schema);
                    break;

                case TpBanco.MySql:
                    tabela = DataBase.MySql.GetTabelaInfo(tabelaNome, pServidor, pBanco, pUsuario);
                    break;

                default:
                    throw new NotImplementedException();
                }
            }

            if (tabela == null)
            {
                throw new NotImplementedException();
            }

            return(tabela);
        }
Пример #6
0
        public static void GerarModel(string pPacote, string pTabela, string pServidor, string pBanco, TpBanco pTpBanco, UserDB pUsuario, bool pQuery = false, string pComando = null)
        {
            Tabela tabela = Util.GetTabela(pTpBanco, pTabela, pServidor, pBanco, pUsuario, pQuery, pComando);

            string nomeClasse = tabela.Nome;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("package " + pPacote + ";");
            sb.AppendLine("");
            if (tabela.Campos.Where(c => c.Tipo.Java.Contains("Date")).Count() > 0)
            {
                sb.AppendLine("import java.util.Date;");
                sb.AppendLine("");
            }
            sb.Append(Util.GetUser());
            sb.AppendLine();
            sb.AppendLine($"public class {nomeClasse} " + "{");
            foreach (Campos campo in tabela.Campos)
            {
                sb.AppendLine($"    private {campo.Tipo.Java} {campo.Nome}\";");
            }

            foreach (Campos campo in tabela.Campos)
            {
                sb.AppendLine();
                sb.AppendLine($"    public {campo.Tipo.Java} get{campo.Nome}()" + " {");
                sb.AppendLine("        return this." + campo.Nome + ";");
                sb.AppendLine("    }");
                sb.AppendLine("");
                sb.AppendLine("    public void set" + campo.Nome + "(" + campo.Tipo.Java + " " + campo.Nome + ") {");
                sb.AppendLine("        this." + campo.Nome + " = " + campo.Nome + ";");
                sb.AppendLine("    }");
            }
            sb.Append("}");

            Arquivos.Deletar();
            Arquivos.Gerar(sb.ToString(), nomeClasse);
        }
Пример #7
0
        public static void GerarModel(string pNamespace, string pTabela, string pServidor, string pBanco, TpBanco pTpBanco, UserDB pUsuario
                                      , bool pQuery = false, string pComando = null, bool pDataAnnotations = false, bool pChaveEstrangeira = false)
        {
            Tabela tabela = Util.GetTabela(pTpBanco, pTabela, pServidor, pBanco, pUsuario, pQuery, pComando);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("using System;");
            if (pDataAnnotations)
            {
                sb.AppendLine("using System.ComponentModel.DataAnnotations;");
                sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;");
            }
            if (pChaveEstrangeira)
            {
                sb.AppendLine("using System.Collections.Generic;");
            }
            sb.AppendLine();
            sb.AppendLine("namespace " + pNamespace);
            sb.AppendLine("{");
            if (pDataAnnotations)
            {
                sb.AppendLine($"    [Table(\"{tabela.Nome}\", Schema = \"{tabela.Schema}\")]");
            }
            sb.AppendLine($"    public partial class {tabela.Nome}");
            sb.AppendLine("    {");

            StringBuilder sbForeignKey = null;

            if (pChaveEstrangeira)
            {
                if (tabela.TabelasChaveEstrangeira?.Count > 0)
                {
                    sb.AppendLine($"        public {tabela.Nome}()");
                    sb.AppendLine("        {");
                    tabela.TabelasChaveEstrangeira.ForEach((chave) =>
                    {
                        if (sbForeignKey == null)
                        {
                            sbForeignKey = new StringBuilder();
                        }

                        sb.AppendLine($"            {chave} = new HashSet<{chave}>();");
                        sbForeignKey.AppendLine($"        public virtual ICollection<{chave}> {chave} {GetSet}");
                    });
                    sb.AppendLine("        }");
                }
            }

            int qtdChaves  = (tabela.Campos != null) ? tabela.Campos.Where(c => c.Chave).Count() : 0;
            int chaveIndex = 0;

            tabela.Campos?.ForEach((campo) =>
            {
                if (pDataAnnotations)
                {
                    if (campo.Chave)
                    {
                        sb.AppendLine("        [Key]");
                        if (qtdChaves > 1)
                        {
                            sb.AppendLine($"        [Column(Order = {chaveIndex++})]");
                            if (!campo.Identity)
                            {
                                sb.AppendLine("        [DatabaseGenerated(DatabaseGeneratedOption.None)]");
                            }
                        }
                    }
                    else if (campo.Identity)
                    {
                        sb.AppendLine("        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]");
                    }
                    else if (campo.NotNull)
                    {
                        sb.AppendLine("        [Required(ErrorMessage = \"*Campo obrigatório.\")]");
                    }
                    if (campo.Tipo.Banco.ToLower().Equals("date"))
                    {
                        sb.AppendLine("        [DisplayFormat(DataFormatString = \"{0:dd/MM/yyyy}\", ApplyFormatInEditMode = true)]");
                    }
                    if (campo.Tipo.Banco.ToLower().Equals("datetime"))
                    {
                        sb.AppendLine("        [DisplayFormat(DataFormatString = \"{0:d}\", ApplyFormatInEditMode = true)]");
                    }
                    else if (campo.Tipo.CSharp.ToLower().Equals("string") && campo.Tipo.Tamanho > 1 && campo.Tipo.Tamanho < 4000)
                    {
                        sb.AppendLine($"        [StringLength({campo.Tipo.Tamanho}, ErrorMessage = \"Você atingiu o limite máximo de {campo.Tipo.Tamanho} caracteres permitidos.\")]");
                    }
                }
                if (pChaveEstrangeira && campo.ChaveEstrangeira != null && campo.ChaveEstrangeira.Is)
                {
                    campo.ChaveEstrangeira.Tabelas?.ToList().ForEach((estrageira) =>
                    {
                        if (sbForeignKey == null)
                        {
                            sbForeignKey = new StringBuilder();
                        }

                        sbForeignKey.AppendLine($"        public virtual {estrageira} {estrageira} {GetSet}");
                        if (pDataAnnotations)
                        {
                            sb.AppendLine($"        [ForeignKey(\"{estrageira}\")]");
                        }
                    });
                }
                sb.AppendLine($"        public {campo.Tipo.CSharp} {campo.Nome} {GetSet}");
            });

            if (sbForeignKey != null)
            {
                sb.Append(sbForeignKey);
            }

            sb.AppendLine("    }");
            sb.Append("}");

            Arquivos.Deletar();
            Arquivos.Gerar(sb.ToString(), "Model " + tabela.Nome);
        }
Пример #8
0
        public static void GerarRepositoryEntity(string pNamespace, string pTabela, string pServidor, string pBanco, TpBanco pTpBanco, UserDB pUsuario
                                                 , bool pAspNetCore = false, bool pGerarInterface = false, bool pGerarDBContext = false, bool pGerarRepository = false, string pQuery = null)
        {
            Tabela tabela = Util.GetTabela(pTpBanco, pTabela, pServidor, pBanco, pUsuario, pQuery != null, pQuery);

            string classeNome    = $"{tabela.Nome}Repository";
            string interfaceNome = $"I{tabela.Nome}Repository";
            string model         = "modelBuilder";
            string classeDB      = "dbContext";

            Arquivos.Deletar();
            StringBuilder sb;

            #region interface
            if (pGerarInterface)
            {
                sb = new StringBuilder();
                sb.AppendLine("using System;");
                sb.AppendLine("using System.Collections.Generic;");
                sb.AppendLine("using System.Linq;");
                sb.AppendLine("using System.Text;");
                sb.AppendLine("using System.Threading.Tasks;");
                sb.AppendLine("using ufmt.autenticacao.api.Models.Resources;");
                sb.AppendLine("");
                sb.AppendLine($"namespace {pNamespace}");
                sb.AppendLine("{");
                sb.AppendLine($"    public interface {interfaceNome}: IRepository<{classeNome}>");
                sb.AppendLine("    {");
                sb.AppendLine("        //TODO métodos");
                sb.AppendLine("    }");
                sb.Append("}");
                Arquivos.Gerar(sb.ToString(), "interface " + tabela.Nome);
            }
            #endregion

            #region Repository
            if (pGerarRepository)
            {
                sb = new StringBuilder();
                sb.AppendLine($"namespace {pNamespace}");
                sb.AppendLine("{");
                sb.AppendLine($"    public partial class {classeNome} : Repository<{classeNome}>, {interfaceNome}");
                sb.AppendLine("    {");
                sb.AppendLine("    }");
                sb.Append("}");
                Arquivos.Gerar(sb.ToString(), "Repository " + tabela.Nome);
            }
            #endregion

            #region DbContext
            if (pGerarDBContext)
            {
                sb = new StringBuilder();
                if (pAspNetCore)
                {
                    sb.AppendLine("using Microsoft.EntityFrameworkCore;");
                }
                else
                {
                    sb.AppendLine("using System.Data.Entity;");
                }
                sb.AppendLine("");
                sb.AppendLine($"namespace {pNamespace}");
                sb.AppendLine("{");
                sb.AppendLine($"	public partial class {classeDB} : DbContext");
                sb.AppendLine("	{");
                if (pAspNetCore)
                {
                    sb.AppendLine($"		public {classeDB}()");
                    sb.AppendLine("		{");
                    sb.AppendLine("");
                    sb.AppendLine("		}");
                    sb.AppendLine("");
                    sb.AppendLine($"		public {classeDB}(DbContextOptions<{classeDB}> options) : base(options)");
                    sb.AppendLine("		{");
                    sb.AppendLine("");
                    sb.AppendLine("		}");
                }
                else
                {
                    sb.AppendLine($"		public {classeDB}() : base(\"name={classeDB}\")");
                    sb.AppendLine("		{");
                    sb.AppendLine("");
                    sb.AppendLine("		}");
                }
                sb.AppendLine("");
                sb.AppendLine($"		public virtual DbSet<{tabela.Nome}> {tabela.Nome} {GetSet}");
                sb.AppendLine("		");
                sb.AppendLine($"		protected override void OnModelCreating({((pAspNetCore) ? "ModelBuilder" : "DbModelBuilder")} {model})");
                sb.AppendLine("		{");
                if (pAspNetCore)
                {
                    sb.AppendLine($"			{model}.Entity<{tabela.Nome}>(entity =>");
                    sb.AppendLine("			{");
                    for (int i = 0; i < tabela.Campos.Count; i++)
                    {
                        if (i > 0)
                        {
                            sb.AppendLine();
                        }
                        if (tabela.Campos[i].Chave)
                        {
                            sb.AppendLine($"				entity.HasKey(e => e.{tabela.Campos[i].Nome});");
                            sb.AppendLine();
                        }
                        sb.AppendLine($"				entity.Property(e => e.{tabela.Campos[i].Nome})");
                        if (tabela.Campos[i].NotNull && !tabela.Campos[i].Chave)
                        {
                            sb.AppendLine("					.IsRequired()");
                        }
                        if (tabela.Campos[i].Tipo.CSharp.ToLower().Equals("string") && tabela.Campos[i].Tipo.Tamanho > 1 && tabela.Campos[i].Tipo.Tamanho < 4000)
                        {
                            sb.AppendLine($"					.HasMaxLength({tabela.Campos[i].Tipo.Tamanho})");
                        }
                        if (tabela.Campos[i].Tipo.Banco.ToLower().Contains("date"))
                        {
                            sb.AppendLine($"					.HasColumnType({tabela.Campos[i].Tipo.Banco})");
                        }
                        sb.AppendLine($"					.HasColumnName(\"{tabela.Campos[i].Nome}\");");
                    }
                    if (!tabela.ExisteChave && tabela.Campos.Count > 0)
                    {
                        sb.AppendLine();
                        sb.AppendLine($"				entity.HasKey(e => e.{tabela.Campos[0].Nome});");
                    }
                    sb.AppendLine("			});");
                }
                else
                {
                    for (int i = 0; i < tabela.Campos.Count; i++)
                    {
                        if (i > 0)
                        {
                            sb.AppendLine();
                        }
                        if (tabela.Campos[i].Chave)
                        {
                            sb.AppendLine($"			{model}.Entity<{tabela.Nome}>().HasKey<{tabela.Campos[i].Tipo.CSharp}>(s => s.{tabela.Campos[i].Nome});");
                            sb.AppendLine();
                        }
                        sb.AppendLine($"			{model}.Entity<{tabela.Nome}>()");
                        sb.AppendLine($"				.Property(p => p.{tabela.Campos[i].Nome})");
                        if (tabela.Campos[i].Tipo.CSharp.ToLower().Equals("string") && tabela.Campos[i].Tipo.Tamanho > 1 && tabela.Campos[i].Tipo.Tamanho < 4000)
                        {
                            sb.AppendLine($"				.HasMaxLength({tabela.Campos[i].Tipo.Tamanho})");
                        }
                        if (!tabela.Campos[i].Chave)
                        {
                            if (tabela.Campos[i].NotNull)
                            {
                                sb.AppendLine("				.IsRequired()");
                            }
                            else
                            {
                                sb.AppendLine("				.IsOptional()");
                            }
                        }
                        if (tabela.Campos[i].Tipo.Banco.ToLower().Contains("date"))
                        {
                            sb.AppendLine($"				.HasColumnType(\"{tabela.Campos[i].Tipo.Banco}\")");
                        }
                        sb.AppendLine($"				.HasColumnName(\"{tabela.Campos[i].Nome}\");");
                    }

                    tabela.TabelasChaveEstrangeira?.ForEach((chaves) =>
                    {
                        sb.AppendLine();
                        sb.AppendLine($"			{model}.Entity<{tabela.Nome}>()");
                        sb.AppendLine($"				.HasMany(e => e.{chaves})");
                        sb.AppendLine($"				.WithRequired(e => e.{tabela.Nome})");
                        sb.AppendLine("				.WillCascadeOnDelete(false);");
                    });

                    sb.AppendLine();
                    sb.AppendLine($"			{model}.Entity<{tabela.Nome}>().ToTable(\"{tabela.Nome}\");");
                }
                sb.AppendLine("		}");
                sb.AppendLine("");
                sb.AppendLine("	}");
                sb.Append("}");

                Arquivos.Gerar(sb.ToString(), $"OnModelCreating {tabela.Nome}");
            }
            #endregion
        }
Пример #9
0
        public static Tabela GetQueryInfo(string pQuery, string pServidor, string pTabela, TpBanco pTpBanco, UserDB pUsuario, string pBanco)
        {
            if (pQuery == null)
            {
                throw new Exception("Query não informada, Verifique");
            }

            DataTable dt = new DataTable();

            switch (pTpBanco)
            {
            case TpBanco.SqlServer:
                dt = DataBase.SqlServer.RetornaDB(pUsuario, pServidor, pBanco).ExecuteDataTable(pQuery);
                break;

            case TpBanco.MySql:
                dt = new DB.MySql(pServidor, pUsuario.Usuario, pUsuario.Senha).ExecuteDataTable(pQuery);
                break;
            }

            Tabela tabela = new Tabela {
                Nome = pTabela.Trim()
            };

            List <Campos> campos = new List <Campos>();

            foreach (DataColumn dc in dt.Columns)
            {
                var campo = new Campos
                {
                    Chave   = false,
                    Nome    = dc.ColumnName,
                    NotNull = false,
                    Tipo    = new TipoBanco(dc.DataType.ToString())
                };
                campos.Add(campo);
            }

            tabela.Campos = campos;

            return(tabela);
        }