Exemple #1
0
        /// <summary>
        /// Preenche o mapeamentos das colunas da entidade
        /// </summary>
        /// <param name="type">Tipo da entidade</param>
        /// <param name="modelMap">Mapeamento da entidade</param>
        public static void FillColumnMap(Type type, ModelMap modelMap)
        {
            foreach (System.Reflection.PropertyInfo property in type.GetProperties())
            {
                object[] att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Column), true);
                DataAnnotations.ERBridge.Column columnAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Column)att[0] : null;

                att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Reference), true);
                DataAnnotations.ERBridge.Reference referenceAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Reference)att[0] : null;

                att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.CollectionReference), true);
                DataAnnotations.ERBridge.CollectionReference collectionAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.CollectionReference)att[0] : null;

                att = property.GetCustomAttributes(typeof(KeyAttribute), true);
                KeyAttribute keyAtt = (att != null && att.Length > 0) ? (KeyAttribute)att[0] : null;

                if (columnAtt != null)
                {
                    ColumnMap columnMap = new ColumnMap(property.Name, columnAtt.Name, columnAtt.DataType, columnAtt.AutoIncremented, columnAtt.SequenceName, columnAtt.Required, (keyAtt != null), (referenceAtt != null), columnAtt.Length, columnAtt.Precision);
                    modelMap.ColumnsMap.Add(columnMap.Property, columnMap);

                    if (columnMap.IsReference)
                    {
                        ReferenceMapInfo referenceMap = new ReferenceMapInfo(property.Name, property.PropertyType, referenceAtt.ReferenceKey, referenceAtt.FetchType);
                        modelMap.ReferencesMap.Add(referenceMap.Property, referenceMap);
                        modelMap.Columns.Add(columnMap.Column, columnMap.Property + "." + referenceMap.ReferenceKey);
                        modelMap.ColumnsMap.Add(columnMap.Property + "." + referenceMap.ReferenceKey, columnMap);
                        if (columnMap.IsKey)
                        {
                            modelMap.Keys.Add(columnMap.Property + "." + referenceMap.ReferenceKey);
                        }
                    }
                    else
                    {
                        modelMap.Columns.Add(columnMap.Column, columnMap.Property);
                        if (columnMap.IsKey)
                        {
                            modelMap.Keys.Add(columnMap.Property);
                        }
                    }
                }

                if (collectionAtt != null)
                {
                    Type itemType = (property.PropertyType.IsGenericType) ? property.PropertyType.GetGenericArguments()[0] : null;
                    if (itemType != null)
                    {
                        CollectionReferenceMapInfo collectionMap = new CollectionReferenceMapInfo(property.Name, itemType, collectionAtt.ItemReferenceKey, collectionAtt.FetchType, collectionAtt.AssociationTableName, collectionAtt.MainColumnKey, collectionAtt.SecundaryColumnKey);
                        modelMap.CollectionsReferencesMap.Add(property.Name, collectionMap);
                    }
                }
            }
        }
Exemple #2
0
        private static ModelMap LoadModelAttributes(Type type)
        {
            object[] att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Table), true);
            DataAnnotations.ERBridge.Table tableAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Table)att[0] : null;
            ModelMap baseModelMap = GetModelMap(type.BaseType);

            if (tableAtt != null || baseModelMap != null)
            {
                ModelMap modelMap = new ModelMap();
                if (tableAtt != null)
                {
                    modelMap._table        = tableAtt.Name;
                    modelMap._databaseName = tableAtt.DatabaseName;
                    if (tableAtt.InheritanceMode == DataAnnotations.ERBridge.InheritanceMode.JoinTables && baseModelMap != null)
                    {
                        modelMap.InheritanceMode            = tableAtt.InheritanceMode;
                        modelMap.ParentTableReferenceColumn = tableAtt.ParentTableReferenceColumn;
                    }
                }

                FillColumnMap(type, modelMap);

                att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Procedure), true);
                if (att != null)
                {
                    foreach (DataAnnotations.ERBridge.Procedure proc in att)
                    {
                        if (!modelMap.ProceduresMap.ContainsKey(proc.ProcedureKey))
                        {
                            modelMap.ProceduresMap.Add(proc.ProcedureKey, new ProcedureMapInfo(proc.Name));
                        }
                    }
                }

                att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.ProcedureParameter), true);
                if (att != null)
                {
                    foreach (DataAnnotations.ERBridge.ProcedureParameter param in att)
                    {
                        if (!modelMap.ProceduresMap[param.ProcedureKey].Parameters.ContainsKey(param.Field))
                        {
                            modelMap.ProceduresMap[param.ProcedureKey].Parameters.Add(param.Field, new ProcedureParameter()
                            {
                                Name = param.Name, DataType = param.DataType, DefaultValue = param.DefaultValue, Direction = param.Direction, Size = param.Size
                            });
                        }
                    }
                }
                return(modelMap);
            }
            return(null);
        }
Exemple #3
0
        /// <summary>
        /// Retorna um mapeamento da entidade em questão
        /// </summary>
        /// <param name="type">Tipo da entidade a ser mapeada</param>
        /// <returns>Mapeamento da entidade</returns>
        public static ModelMap GetModelMap(Type type)
        {
            ModelMap modelMap = null;

            if (_modelsMap.ContainsKey(type))
            {
                modelMap = _modelsMap[type];
            }
            else
            {
                try
                {
                    modelMap = LoadModelXml(type);

                    if (modelMap == null)
                    {
                        modelMap = LoadModelAttributes(type);
                    }

                    if (modelMap != null)
                    {
                        modelMap._baseModelMap = GetModelMap(type.BaseType);
                        _modelsMap.Add(type, modelMap);

                        if (modelMap.InheritanceMode == DataAnnotations.ERBridge.InheritanceMode.UniqueTable)
                        {
                            if (modelMap._baseModelMap == null && type.BaseType.IsSubclassOf(typeof(Layers.Model)))
                            {
                                _modelsMap.Add(type.BaseType, modelMap);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Commons.Utilities.Logger.Error(ex);
                }
            }

            return(modelMap);
        }
Exemple #4
0
        public static Dictionary <string, object> GetModelValues <TModel>(TModel model)
        {
            //TODO:Tratar exceções
            Type     modelType = model.GetType();
            ModelMap modelMap  = ModelMap.GetModelMap(modelType);
            Dictionary <string, object> modelValues = new Dictionary <string, object>();

            foreach (string propertyName in modelMap.GetPropertiesNamesList())
            {
                try
                {
                    object value = modelType.GetProperty(propertyName).GetValue(model, null);
                    if (value != null && modelMap.GetColumnMap(propertyName).DataType == DataAnnotations.ERBridge.DataType.Xml)
                    {
                        XmlDocument xml = new XmlDocument();
                        xml.InnerXml = Commons.Utilities.ClassToXML.SerializeObject(value, propertyName);
                        value        = xml.FirstChild.InnerXml;
                    }
                    else if (modelMap.GetColumnMap(propertyName).DataType == DataAnnotations.ERBridge.DataType.DateTime && DateTime.MinValue.Equals(value))
                    {
                        value = null;
                    }

                    ReferenceMapInfo referenceMap = modelMap.GetReferencesMap(propertyName);
                    if (value != null && referenceMap != null)
                    {
                        object keyValue = value.GetType().GetProperty(referenceMap.ReferenceKey).GetValue(value, null);
                        modelValues.Add(propertyName + "." + referenceMap.ReferenceKey, keyValue);
                    }
                    else
                    {
                        modelValues.Add(propertyName, value);
                    }
                }
                catch (Exception ex) {
                    Commons.Utilities.Logger.Error(ex);
                }
            }
            return(modelValues);
        }
Exemple #5
0
        public ColumnMap GetMappedColumnMap(string propertyName)
        {
            ColumnMap mappedColumnMap = GetColumnMap(propertyName);

            if (mappedColumnMap == null)
            {
                string[] propertyParts = propertyName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                if (propertyParts.Length > 1)
                {
                    ReferenceMapInfo reference = GetReferencesMapList().FirstOrDefault(r => r.Property == propertyParts[0]);
                    if (reference != null)
                    {
                        ModelMap referenceModelMap = ModelMap.GetModelMap(reference.ReferencedModelType);
                        if (referenceModelMap != null)
                        {
                            mappedColumnMap = referenceModelMap.GetColumnMap(propertyName.Remove(0, (propertyParts[0] + ".").Length));
                        }
                    }
                }
            }
            return(mappedColumnMap);
        }
Exemple #6
0
        public string GetMappedPropertyName(string column)
        {
            string mappedPropertyName = GetPropertyName(column);

            if (string.IsNullOrEmpty(mappedPropertyName))
            {
                string[] columnParts = column.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                if (columnParts.Length > 1)
                {
                    foreach (ReferenceMapInfo reference in GetReferencesMapList())
                    {
                        ModelMap referenceModelMap = ModelMap.GetModelMap(reference.ReferencedModelType);
                        if (referenceModelMap != null && (referenceModelMap.Table == columnParts[0] || columnParts[0] == reference.Property))
                        {
                            mappedPropertyName  = reference.Property;
                            mappedPropertyName += "." + referenceModelMap.GetMappedPropertyName(column.Remove(0, (columnParts[0] + ".").Length));
                            break;
                        }
                    }
                }
            }
            return(mappedPropertyName);
        }
Exemple #7
0
        private static ModelMap LoadModelXml(Type type)
        {
            try
            {
                Config.Settings essentialsSettings = (Config.Settings)ConfigurationManager.GetSection("essentialsSettings");
                XmlDocument     xml = new XmlDocument();
                xml.Load(essentialsSettings.XmlModelsPath);
                XmlNode modelNode = xml.SelectSingleNode("/Models/Model[@type='" + type.FullName + "']");

                modelNode = (modelNode == null) ? xml.SelectSingleNode("/Models/Model[@baseModelType='" + type.FullName + "']") : modelNode;

                if (modelNode != null)
                {
                    ModelMap modelMap = new ModelMap(table: modelNode.Attributes["table"].Value);
                    if (modelNode.Attributes["dataBaseName"] != null)
                    {
                        modelMap._databaseName = modelNode.Attributes["dataBaseName"].Value;
                    }
                    if (modelNode.Attributes["inheritanceMode"] != null && modelNode.Attributes["inheritanceMode"].Value == "JoinTables")
                    {
                        modelMap.InheritanceMode            = DataAnnotations.ERBridge.InheritanceMode.JoinTables;
                        modelMap.ParentTableReferenceColumn = modelNode.Attributes["parentTableReferenceColumn"].Value;
                    }

                    //Colunas
                    foreach (XmlNode columnNode in modelNode.SelectNodes("ColumnMap"))
                    {
                        if (type.GetProperty(columnNode.Attributes["property"].Value) != null)
                        {
                            ColumnMap columnMap = new ColumnMap(
                                property: columnNode.Attributes["property"].Value,
                                column: columnNode.Attributes["column"].Value,
                                dataType: (DataAnnotations.ERBridge.DataType)Enum.Parse(typeof(DataAnnotations.ERBridge.DataType),
                                                                                        columnNode.Attributes["dbType"].Value),
                                isAutoIncremented: (columnNode.Attributes["isAutoIncremented"] != null ? bool.Parse(columnNode.Attributes["isAutoIncremented"].Value) : false),
                                sequenceName: (columnNode.Attributes["sequenceName"] != null ? columnNode.Attributes["sequenceName"].Value : null),
                                isRequired: (columnNode.Attributes["isRequired"] != null ? bool.Parse(columnNode.Attributes["isRequired"].Value) : false),
                                isKey: (columnNode.Attributes["isKey"] != null ? bool.Parse(columnNode.Attributes["isKey"].Value) : false),
                                isReference: (columnNode.Attributes["isReference"] != null ? bool.Parse(columnNode.Attributes["isReference"].Value) : false));

                            modelMap.ColumnsMap.Add(columnMap.Property, columnMap);

                            if (columnMap.IsKey)
                            {
                                modelMap.Keys.Add(columnMap.Property);
                            }

                            //Referências
                            if (columnMap.IsReference)
                            {
                                XmlNode          referenceNode = modelNode.SelectSingleNode("ReferenceMap[@property='" + columnMap.Property + "']");
                                ReferenceMapInfo referenceMap  = new ReferenceMapInfo(
                                    property: referenceNode.Attributes["property"].Value,
                                    referenceKey: referenceNode.Attributes["referenceKey"].Value,
                                    fetchType: columnNode.Attributes["fetchType"] != null ? (DataAnnotations.ERBridge.Fetch)Enum.Parse(typeof(DataAnnotations.ERBridge.Fetch), columnNode.Attributes["fetchType"].Value) : DataAnnotations.ERBridge.Fetch.LAZY,
                                    referencedModelType: type.GetProperty(referenceNode.Attributes["property"].Value).PropertyType
                                    );
                                modelMap.ReferencesMap.Add(referenceMap.Property, referenceMap);
                                modelMap.ColumnsMap.Add(columnMap.Property + "." + referenceMap.ReferenceKey, columnMap);
                                modelMap.Columns.Add(columnMap.Column, columnMap.Property + "." + referenceMap.ReferenceKey);
                            }
                            else
                            {
                                modelMap.Columns.Add(columnMap.Column, columnMap.Property);
                            }
                        }
                    }

                    //Coleções
                    foreach (XmlNode collectionNode in modelNode.SelectNodes("ColletionReferenceMap"))
                    {
                        if (type.GetProperty(collectionNode.Attributes["property"].Value) != null)
                        {
                            System.Reflection.PropertyInfo property = type.GetProperty(collectionNode.Attributes["property"].Value);
                            Type itemType = (property.PropertyType.IsGenericType) ? property.PropertyType.GetGenericArguments()[0] : null;
                            if (itemType != null)
                            {
                                CollectionReferenceMapInfo collectionMap = new CollectionReferenceMapInfo(
                                    property: property.Name,
                                    collectionItemType: itemType,
                                    itemReferenceKey: collectionNode.Attributes["itemReferenceKey"].Value,
                                    collectionFetchType: collectionNode.Attributes["fetchType"] != null ? (DataAnnotations.ERBridge.Fetch)Enum.Parse(typeof(DataAnnotations.ERBridge.Fetch), collectionNode.Attributes["fetchType"].Value) : DataAnnotations.ERBridge.Fetch.LAZY,
                                    associationTableName: (collectionNode.Attributes["associationTable"] != null ? collectionNode.Attributes["associationTable"].Value : null),
                                    mainColumnKey: (collectionNode.Attributes["mainColumnKey"] != null ? collectionNode.Attributes["mainColumnKey"].Value : null),
                                    secundaryColumnKey: (collectionNode.Attributes["secundaryColumnKey"] != null ? collectionNode.Attributes["secundaryColumnKey"].Value : null)
                                    );
                                modelMap.CollectionsReferencesMap.Add(property.Name, collectionMap);
                            }
                        }
                    }

                    //Procedures
                    foreach (XmlNode procedureNode in modelNode.SelectNodes("ProcedureMap"))
                    {
                        ProcedureMapInfo procedureMap = new ProcedureMapInfo(procedureNode.Attributes["name"].Value);
                        foreach (XmlNode parameterNode in procedureNode.SelectNodes("Parameter"))
                        {
                            ProcedureParameter parameter = new ProcedureParameter();
                            parameter.Name         = parameterNode.Attributes["name"].Value;
                            parameter.DataType     = (DataAnnotations.ERBridge.DataType)Enum.Parse(typeof(DataAnnotations.ERBridge.DataType), parameterNode.Attributes["dbType"].Value);
                            parameter.DefaultValue = parameterNode.Attributes["defaultValue"] != null ? parameterNode.Attributes["defaultValue"].Value : null;
                            parameter.Direction    = parameterNode.Attributes["direction"] != null ? (ParameterDirection)Enum.Parse(typeof(ParameterDirection), parameterNode.Attributes["direction"].Value): ParameterDirection.Input;
                            parameter.Size         = parameterNode.Attributes["size"] != null?int.Parse(parameterNode.Attributes["size"].Value) : 0;

                            procedureMap.Parameters.Add(parameterNode.Attributes["field"].Value, parameter);
                        }
                        modelMap.ProceduresMap.Add(procedureNode.Attributes["procedureKey"].Value, procedureMap);
                    }
                    return(modelMap);
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            return(null);
        }
Exemple #8
0
        /// <summary>
        /// Retorna um objeto da entidade montada a partir de um DataReader e do seu mapeamento
        /// </summary>
        /// <param name="dr">DataReader</param>
        /// <param name="modelType">Tipo da entidade</param>
        /// <returns>Objeto da entidade</returns>
        public TModel GetModelObjectByDataReader <TModel>(IDataReader dr, Type modelType = null)
            where TModel : class, Layers.IModel
        {
            if (modelType == null)
            {
                modelType = typeof(TModel);
            }
            //TODO:Tratar exceções
            TModel result = default(TModel);

            ModelMaps.ModelMap modelMap = ModelMaps.ModelMap.GetModelMap(modelType);
            if (modelMap != null)
            {
                XmlDocument docXml = new XmlDocument();
                docXml.AppendChild(docXml.CreateXmlDeclaration("1.0", null, null));
                XmlElement root = docXml.CreateElement(modelType.GetTypeName());
                docXml.AppendChild(root);
                bool isNullRow = true;
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    string propertyName = modelMap.GetMappedPropertyName(dr.GetName(i));
                    if (!string.IsNullOrEmpty(propertyName) && dr.GetValue(i) != DBNull.Value)
                    {
                        isNullRow = false;
                        XmlNode nodeToAppend = root;
                        string  mappedNode   = propertyName;

                        foreach (string nodeName in mappedNode.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (nodeToAppend.SelectSingleNode(nodeName) != null)
                            {
                                nodeToAppend = nodeToAppend.SelectSingleNode(nodeName);
                            }
                            else
                            {
                                nodeToAppend.AppendChild(docXml.CreateElement(nodeName));
                                nodeToAppend = nodeToAppend.LastChild;
                            }
                        }
                        string val = dr[i].ToString();
                        double num;
                        if (double.TryParse(val.ToString(), out num) && dr[i].GetType() != typeof(string))
                        {
                            val = num.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (dr[i].GetType() == typeof(DateTime))
                        {
                            val = dr.GetDateTime(i).ToString("yyyy-MM-ddTHH:mm:ss");
                        }
                        else if (dr[i].GetType() == typeof(bool))
                        {
                            val = val.ToLower();
                        }
                        else if (dr[i].GetType() == typeof(byte[]))
                        {
                            val = Commons.Utilities.ClassToXML.SerealizeBytes((dr[i] as Byte[]));
                        }
                        if (modelMap.GetMappedColumnMap(propertyName).DataType == DataAnnotations.ERBridge.DataType.Xml)
                        {
                            try
                            {
                                nodeToAppend.InnerXml = val;
                            }
                            catch
                            {
                                nodeToAppend.InnerText = val;
                            }
                        }
                        else
                        {
                            nodeToAppend.InnerText = val;
                        }
                    }
                }
                if (!isNullRow)
                {
                    result = (TModel)Commons.Utilities.ClassToXML.DeserializeXML(docXml.InnerXml, modelType);
                }
                result.IsReady = true;
            }
            return(result);
        }