Пример #1
0
        /// <summary>
        /// EF实体映射业务实体
        /// </summary>
        /// <typeparam name="T">业务实体类型</typeparam>
        /// <param name="entity">EF实体对象</param>
        /// <returns></returns>
        public static T  ToDataObject <T>(this IBaseModel entity) where T : BaseDataObject, new()
        {
            var o = new T();

            AutoMapper.Mapper.DynamicMap(entity, o, entity.GetType(), typeof(T));
            return(o);
        }
Пример #2
0
        /// <summary>
        /// Validiert ein Property
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private string ValidateProperty(string propertyName, IMethodInvocation input)
        {
            if (!_isChangeNotificationActive)
            {
                return(string.Empty);
            }

            IBaseModel model = (IBaseModel)input.Target;

            ValidationSummary validationSummary = Validator.Validate(model);

            string result = null;

            IList <ValidationEntry> validationEntries = validationSummary.Where(d => d.FieldName == propertyName).ToList();

            if (validationEntries.Any())
            {
                validationEntries.ForEach(d =>
                {
                    if (result != null)
                    {
                        result += ", ";
                    }

                    result += d.Message;
                });
            }

            model.GetType().GetProperty("IsValid").SetValue(input.Target, validationSummary.IsValid);

            return(result);
        }
Пример #3
0
            internal static IEnumerable <MyHierarchicalType> GetModels(IBaseModel model)
            {
                Type type = model.GetType();
                int  i    = 0;

                for (var current = type; current != null &&
                     !current.FullName.Equals(typeof(System.Object).FullName);
                     current = current.BaseType)
                {
                    yield return new MyHierarchicalType()
                           {
                               Order = i++,
                               Type  = current
                           }
                }
                ;
            }
Пример #4
0
        public void BuildSqlCommand(SqlCommand command, IBaseModel newEntity, CrudAction crudAction)
        {
            if (command == null || newEntity == null)
            {
                return;
            }

            var entityType = newEntity.GetType();
            var entityName = entityType.FullName;
            CommandDefinition commandDefinition = GetStoredProcedureConfiguration(entityName, crudAction);

            SetCommandText(commandDefinition, command, newEntity, crudAction);

            SetCommandType(commandDefinition, command);

            AddParameters(commandDefinition, command, newEntity, crudAction);

            SetupConnection(commandDefinition, command);
        }
Пример #5
0
        /// <summary>
        /// Exclui um registro da base de dados
        /// </summary>
        /// <param name="id">identificador do registro</param>
        public static void Delete(IID id, IBaseModel model)
        {
            try
            {
                model.Connection = DbContext.CreateConnection();
                model.Connection.BeginTransaction();

                //Validar
                model.ValidateDelete();

                TableDefinitionAttribute tableDefinition = FindTableDefinition(model);

                CommandFactory cf = new CommandFactory(model.Connection,
                                                       model.Connection.Transaction,
                                                       model.GetType(), model, null);

                using (Command command = cf.CreateCommandDelete(tableDefinition, id))
                {
                    command.ExecuteNonQuery();
                }

                model.Connection.CommitTransaction();
            }
            catch
            {
                model.Connection.RollbackTransaction();
                throw;
            }
            finally
            {
                if (model.Connection != null)
                {
                    model.Connection.Close();
                }
            }
        }
Пример #6
0
        private string GetCommandText(CommandDefinition commandDefinition, IBaseModel entityType, CrudAction crudAction)
        {
            var entityName = entityType?.GetType()?.Name;

            if (!string.IsNullOrWhiteSpace(commandDefinition?.Command) || !string.IsNullOrWhiteSpace(commandDefinition?.QueryFilePath))
            {
                return(!string.IsNullOrWhiteSpace(commandDefinition.Command) ? commandDefinition.Command : fileService.GetFileContent(commandDefinition.QueryFilePath));
            }

            string commandText = "";
            var    tableName   = entityName?.Pluralize();

            if (crudAction == CrudAction.Delete)
            {
                commandText = $"DELETE FROM {tableName}";
            }
            else if (crudAction == CrudAction.Insert)
            {
                commandText = $"INSERT INTO {tableName}";
            }
            else if (crudAction == CrudAction.Select)
            {
                commandText = $"SELECT * FROM {tableName}";
            }
            else if (crudAction == CrudAction.Update)
            {
                commandText = $"UPDATE {tableName}";
            }

            var parameters = GetPropertiesWithValues(entityType)?.ToList();

            if (crudAction == CrudAction.Delete ||
                crudAction == CrudAction.Select)
            {
                var whereClause = "";
                if ((parameters?.Count ?? 0) > 0)
                {
                    whereClause = string.Join(" AND ", parameters.Select(p => $"{p.Name} = @{p.Name}"));
                    if ((whereClause?.Length ?? 0) > 0)
                    {
                        whereClause = $" WHERE {whereClause}";
                    }
                }
                commandText = $"{commandText} {whereClause}".Trim();
            }
            else if (crudAction == CrudAction.Insert)
            {
                var parameterNames = string.Join(", ", parameters?.Select(p => $"@{p.Name}")?.ToList() ?? Enumerable.Empty <string>());
                var columns        = string.Join(", ", parameters?.Select(p => p.Name)?.ToList() ?? Enumerable.Empty <string>());
                commandText = $"{commandText} ({columns}) VALUES ({parameterNames})";

                var identityProperty = GetIdentityProperty(entityType)?.FirstOrDefault();
                if (identityProperty != null)
                {
                    commandText = $"{commandText} SELECT * FROM {tableName} WHERE {identityProperty.Name} = SCOPE_IDENTITY()";
                }
                else
                {
                    commandText = $"{commandText} {GetCommandText(commandDefinition, entityType, CrudAction.Select)}";
                }
            }
            else if (crudAction == CrudAction.Update)
            {
                var primaryKeyColumnNames = GetPrimaryKeyProperties(entityType)?.Select(p => p.Name)?.ToArray();
                var columnNames           = entityType.GetPropertyNames()?.Where(c => Array.IndexOf(primaryKeyColumnNames, c) == -1)?.ToList();
                var updateClause          = string.Join(",", columnNames?.Select(c => $"{c} = {ParameterPrefix}{c}")?.ToList() ?? Enumerable.Empty <string>());
                var whereClause           = string.Join(",", primaryKeyColumnNames?.Select(c => $"{c} = {ParameterPrefix}{c}")?.ToList() ?? Enumerable.Empty <string>());
                commandText = $"SET {updateClause} {whereClause}";
            }

            return(commandText);
        }
Пример #7
0
        /// <summary>
        /// Salva o registro na base de dados
        /// </summary>
        /// <param name="model"></param>
        public static IID Save(IBaseModel model)
        {
            IID         result      = null;
            bool        oldNew      = model.New;
            IID         fk          = null;
            ForeignKeys foreignKeys = new ForeignKeys();
            bool        inserting   = false;
            IEnumerable <MyHierarchicalType> models          = null;
            TableDefinitionAttribute         tableDefinition = null;

            try
            {
                //se este model for do tipo IChildModel
                //deve-se usar a conexão do Parent e cria uma foreignKey
                if (model.IsChildModel())
                {
                    dynamic m = model;

                    if (m.Parent != null)
                    {
                        model.Connection = m.Parent.Connection;

                        models = Utilities.DbUtils.GetModels(m.Parent as IBaseModel);

                        foreach (var modelType in models)
                        {
                            if (modelType.Type.GetCustomAttributes(typeof(TableDefinitionAttribute), false).Count() > 0)
                            {
                                tableDefinition = modelType.Type.GetCustomAttributes(typeof(TableDefinitionAttribute), false)[0] as TableDefinitionAttribute;

                                fk = Utilities.DbUtils.GetPrimaryKeyValue(m);

                                //adicionar o foreign key, se necessário usar no command
                                foreignKeys.Add(tableDefinition.TableName, fk);
                            }
                        }
                    }
                }

                model.Connection.Open();
                model.Connection.BeginTransaction();

                //Detectar se é uma inserção
                //se o modelo é marcado como não atualizável, deverá sempre sofrer insert
                object[] notUpdatable = model.GetType().GetCustomAttributes(typeof(NotUpdatableAttribute), true);

                inserting = notUpdatable.Count() > 0 || model.New;

                //Validar
                model.Validate(!inserting);
                model.BeforeSave(!inserting);

                //revalidar o insert, pois pode ter sido modificado pelo Validate e BeforeSave
                inserting = notUpdatable.Count() > 0 || model.New;

                models = Utilities.DbUtils.GetModels(model);

                //para todos os modelos retornados, iremos buscar as tabelas que compoe estes modelos
                foreach (var modelType in models.OrderByDescending(o => o.Order))
                {
                    if (modelType.Type.GetCustomAttributes(typeof(TableDefinitionAttribute), false).Count() > 0)
                    {
                        tableDefinition = modelType.Type.GetCustomAttributes(typeof(TableDefinitionAttribute), false)[0] as TableDefinitionAttribute;

                        CommandFactory cf = new CommandFactory(model.Connection,
                                                               model.Connection.Transaction,
                                                               modelType.Type, model, foreignKeys);

                        using (Command command = cf.CreateCommand(inserting))
                        {
                            //Preparar o comando antes de executar
                            model.PrepareCommand(command, !inserting);

                            //executar o comando
                            command.ExecuteNonQuery();

                            //se esta tabela possuir GUID, deverá ser armazenada para referência como chave estrangeira
                            if (Utilities.DbUtils.Tables[tableDefinition.TableName].Fields.Contains(tableDefinition.PrimaryKey))
                            {
                                fk = Utilities.DbUtils.GetPrimaryKeyValue(model);
                            }

                            if (!result.IsValid())
                            {
                                result = fk;
                            }

                            //adicionar o foreign key, se necessário usar no command
                            foreignKeys.Add(tableDefinition.TableName, fk);
                        }
                    }
                }

                model.AfterSave(!inserting);
                model.Connection.CommitTransaction();
                model.New = false;
            }
            catch
            {
                model.Connection.RollbackTransaction();
                model.New = oldNew;
                throw;
            }
            finally
            {
                model.Connection.Close();
            }

            model.New = false;
            return(result);
        }
Пример #8
0
            public DictionaryTreeNode GetTreeNode(IBaseModel wrapper)
            {
                DictionaryTreeNode _ret = null;

                if (wrapper is ViewDesign)
                {
                    _ret = new ViewDesignTreeNodeControl((ViewDesign)wrapper);
                }
                else if (wrapper is VariableTypeDesign)
                {
                    _ret = new VariableTypeDesignTreeNodeControl((VariableTypeDesign)wrapper);
                }
                else if (wrapper is VariableDesign)
                {
                    _ret = new VariableDesignTreeNodeControl((VariableDesign)wrapper);
                }
                else if (wrapper is SolutionTreeNode)
                {
                    _ret = new SolutionTreeNodeControl((SolutionTreeNode)wrapper);
                }
                else if (wrapper is ReferenceTypeDesign)
                {
                    _ret = new ReferenceTypeDesignTreeNodeControl((ReferenceTypeDesign)wrapper);
                }
                else if (wrapper is ReferencesFolder)
                {
                    _ret = new ReferencesFolderTreeNodeControl((ReferencesFolder)wrapper);
                }
                else if (wrapper is Reference)
                {
                    _ret = new ReferenceTreeNodeControl((Reference)wrapper);
                }
                else if (wrapper is PropertyDesign)
                {
                    _ret = new PropertyDesignTreeNodeControl((PropertyDesign)wrapper);
                }
                else if (wrapper is ProjectTreeNode)
                {
                    _ret = new ProjectTreeNodeControl((ProjectTreeNode)wrapper);
                }
                else if (wrapper is ParametersFolder)
                {
                    _ret = new ParametersFolderTreeNodeControl((ParametersFolder)wrapper);
                }
                else if (wrapper is Parameter)
                {
                    _ret = new ParameterTreeNodeControl((Parameter)wrapper);
                }
                else if (wrapper is ObjectTypeDesign)
                {
                    _ret = new ObjectTypeDesignTreeNodeControl((ObjectTypeDesign)wrapper);
                }
                else if (wrapper is ObjectDesign)
                {
                    _ret = new ObjectDesignTreeNodeControl((ObjectDesign)wrapper);
                }
                else if (wrapper is NamespacesFolder)
                {
                    _ret = new NamespacesFolderTreeNodeControl((NamespacesFolder)wrapper);
                }
                else if (wrapper is Namespace)
                {
                    _ret = new NamespaceTreeNodeControl((Namespace)wrapper);
                }
                else if (wrapper is ModelDesign)
                {
                    _ret = new ModelDesignTreeNodeControl((ModelDesign)wrapper);
                }
                else if (wrapper is MethodDesign)
                {
                    _ret = new MethodDesignTreeNodeControl((MethodDesign)wrapper);
                }
                else if (wrapper is EncodingsFolder)
                {
                    _ret = new EncodingsFolderTreeNodeControl((EncodingsFolder)wrapper);
                }
                else if (wrapper is DictionaryDesign)
                {
                    _ret = new DictionaryDesignTreeNodeControl((DictionaryDesign)wrapper);
                }
                else if (wrapper is DataTypeDesign)
                {
                    _ret = new DataTypeDesignTreeNodeControl((DataTypeDesign)wrapper);
                }
                else if (wrapper is EncodingDesign)
                {
                    _ret = new EncodingDesignTreeNodeControl((EncodingDesign)wrapper);
                }
                else if (wrapper is ChildrenFolder)
                {
                    _ret = new ChildrenFolderTreeNodeControl((ChildrenFolder)wrapper);
                }
                else if (wrapper is NamespacesFolder)
                {
                    _ret = new NamespacesFolderTreeNodeControl((NamespacesFolder)wrapper);
                }
                else if (wrapper is ModelDesign)
                {
                    _ret = new ModelDesignTreeNodeControl((ModelDesign)wrapper);
                }
                else
                {
                    throw new System.ArgumentOutOfRangeException($"{nameof(GetTreeNode)} cannot factory object for {wrapper.GetType().FullName}");
                }
                return(_ret);
            }
Пример #9
0
 public CommandFactory(IBaseModel model)
 {
     this.currentType = model.GetType();
     this.model       = model;
 }
Пример #10
0
        internal void PrepareCommandSelect(TableDefinitionAttribute tableDefinition,
                                           Where where, OrderBy order, IEnumerable <DbParameter> whereParameters, ref Command command)
        {
            #region Variáveis
            string sqlWhere = "";
            var    props    = model.GetType().GetProperties();

            //-------------------------------------------------------------------------
            // Salva os campos que já foram adicionados para não adicionar novamente
            //-------------------------------------------------------------------------
            Dictionary <string, SelectField> fields = new Dictionary <string, SelectField>();

            string commandText  = "";
            string selectFields = "";

            commandText = @"SELECT {selectFields} {from} {where} {limit}";

            if (where == null)
            {
                where = new Where();
            }
            #endregion

            #region Select

            foreach (MyHierarchicalType hType in Utilities.DbUtils.GetModels(model).OrderByDescending(o => o.Order))
            {
                //recuperar todos os selectedsFields
                IList <SelectField> selectList = GetSelectAux(hType.Type);

                if (selectList != null)
                {
                    foreach (SelectField item in selectList)
                    {
                        if (!fields.ContainsKey(item.FieldAlias))
                        {
                            selectFields += item.ToString() + ",";
                            fields.Add(item.FieldAlias, item);
                        }
                    }
                }
            }

            if (BeforePrepareSelectAction != null)
            {
                BeforePrepareSelectAction(command, selectFields);
            }

            selectFields = selectFields.Trim();

            if (!string.IsNullOrEmpty(selectFields))
            {
                selectFields = selectFields.Substring(0, selectFields.Length - 1);
            }

            #region where
            if (whereParameters != null && whereParameters.Count() > 0)
            {
                foreach (Parameter item in whereParameters)
                {
                    command.Parameters.Add(item);
                }
            }

            model.PrepareReader(command, where);

            if (where.Count > 0)
            {
                sqlWhere = " WHERE " + where.ToString();

                foreach (Parameter p in where.Parameters)
                {
                    command.Parameters.Add(p);
                }
            }
            #endregion

            #endregion

            #region Return
            commandText = commandText.Replace("{from}", GetFrom())
                          .Replace("{selectFields}", selectFields)
                          .Replace("{where}", sqlWhere)
                          .Replace("{limit}", where.Limit.ToString());

            command.CommandText = commandText;
            #endregion
        }
Пример #11
0
 /// <summary>
 /// Converte um modelo no tipo de arquivo esperado
 /// </summary>
 /// <param name="tipo">tipo de arquivo qualquer</param>
 /// <param name="model">modelo esperado</param>
 /// <returns></returns>
 public static TipoArquivo ModelToEnum(this TipoArquivo tipo, IBaseModel model)
 {
     if(model is Model.Arquivo.Registro.IRegistro01)
         return TipoArquivo.MapaResumo;
     else if (model is Model.Cadastro.Item.Produto.IProdutoArvore)
         return TipoArquivo.ArvoreProduto;
     else if (model is Model.Cadastro.Pessoa.ICliente)
         return TipoArquivo.Cliente;
     else if (model is Model.Cadastro.Pessoa.IContador)
         return TipoArquivo.Contador;
     else if (model is Model.Faturamento.Lancamento.Movimento.VendaCF.IVendaCF)
         return TipoArquivo.CupomFiscal;
     else if (model is Model.Faturamento.Lancamento.Movimento.DAV.IDAV)
         return TipoArquivo.DAV;
     else if (model is Model.Cadastro.Pessoa.IEmpresa)
         return TipoArquivo.Empresa;
     else if (model is Model.Cadastro.Pessoa.IFabricante)
         return TipoArquivo.Fabricante;
     else if (model is Model.Cadastro.IFormaPagamento)
         return TipoArquivo.FormaPagamento;
     else if (model is Model.Cadastro.Item.IGrupoItem)
         return TipoArquivo.GrupoItem;
     else if (model is Model.FrenteCaixa.Cadastro.IPDV)
         return TipoArquivo.PDV;
     else if (model is Model.Faturamento.Lancamento.Movimento.PreVenda.IPreVenda)
         return TipoArquivo.PreVenda;
     else if (model is Model.Cadastro.Item.Produto.IProduto)
         return TipoArquivo.Produto;
     else if (model is Model.Cadastro.TabelaPreco.ITabelaPreco)
         return TipoArquivo.TabelaPreco;
     else if (model is Model.Cadastro.IUnidade)
         return TipoArquivo.UnidadeMedida;
     else if (model is Model.Cadastro.Pessoa.IUsuario)
         return TipoArquivo.Usuario;
     else if (model is Model.Cadastro.Pessoa.IVendedor)
         return TipoArquivo.Vendedor;
     else if (model is Model.Cadastro.Pessoa.IFornecedor)
         return TipoArquivo.Fornecedor;
     else if (model is OpenPOS.Model.Faturamento.Lancamento.Cancelamento.ICancelamento)
         return TipoArquivo.Cancelamento;
     else if (model is Model.Financeiro.Lancamento.IContaReceber ||
             model is Model.Financeiro.Lancamento.IContaPagar ||
             model is Model.Financeiro.Lancamento.ILancamento ||
             model is Model.FrenteCaixa.Lancamento.IContaCorrenteCaixa)
         return TipoArquivo.NaoDefinido;
     else
         throw new NotImplementedException("Tipo não implementado. Tipo: " + model == null ? "null" : Unimake.Convert.ToString(model.GetType()));
 }