Пример #1
0
        private StringBuilder AppendJoinToSelect(StringBuilder originalBuilder, params Expression <Func <TEntity, object> >[] includes)
        {
            var joinsBuilder = new StringBuilder();

            foreach (var include in includes)
            {
                var propertyName = ExpressionHelper.GetPropertyName(include);
                var joinProperty = AllProperties.First(x => x.Name == propertyName);
                var attrJoin     = joinProperty.GetCustomAttribute <JoinAttributeBase>();
                if (attrJoin != null)
                {
                    var joinString = "";
                    if (attrJoin is LeftJoinAttribute)
                    {
                        joinString = "LEFT JOIN ";
                    }
                    else if (attrJoin is InnerJoinAttribute)
                    {
                        joinString = "INNER JOIN ";
                    }
                    else if (attrJoin is RightJoinAttribute)
                    {
                        joinString = "RIGHT JOIN ";
                    }

                    var joinType = joinProperty.PropertyType.IsGenericType() ? joinProperty.PropertyType.GenericTypeArguments[0] : joinProperty.PropertyType;

                    var properties = joinType.GetProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                    var props      = properties.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new PropertyMetadata(p));
                    originalBuilder.Append(", " + GetFieldsSelect(attrJoin.TableName, props));


                    joinsBuilder.Append($"{joinString} {attrJoin.TableName} ON {TableName}.{attrJoin.Key} = {attrJoin.TableName}.{attrJoin.ExternalKey} ");
                }
            }
            return(joinsBuilder);
        }
        private void InitProperties()
        {
            var entityType     = typeof(TEntity);
            var entityTypeInfo = entityType.GetTypeInfo();
            var tableAttribute = entityTypeInfo.GetCustomAttribute <TableAttribute>();

            TableName = MicroOrmConfig.TablePrefix + (tableAttribute != null ? tableAttribute.Name : entityTypeInfo.Name);

            TableSchema = tableAttribute != null ? tableAttribute.Schema : string.Empty;

            AllProperties = entityType.FindClassProperties().Where(q => q.CanWrite).ToArray();

            var props = entityType.FindClassPrimitiveProperties();

            var joinProperties = AllProperties.Where(p => p.GetCustomAttributes <JoinAttributeBase>().Any()).ToArray();

            SqlJoinProperties = GetJoinPropertyMetadata(joinProperties);

            // Filter the non stored properties
            SqlProperties = props.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            // Filter key properties
            KeySqlProperties = props.Where(p => p.GetCustomAttributes <KeyAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            // Use identity as key pattern
            var identityProperty = props.FirstOrDefault(p => p.GetCustomAttributes <IdentityAttribute>().Any());

            IdentitySqlProperty = identityProperty != null ? new SqlPropertyMetadata(identityProperty) : null;

            var dateChangedProperty = props.FirstOrDefault(p => p.GetCustomAttributes <UpdatedAtAttribute>().Any());

            if (dateChangedProperty != null && (dateChangedProperty.PropertyType == typeof(DateTime) || dateChangedProperty.PropertyType == typeof(DateTime?)))
            {
                UpdatedAtProperty         = dateChangedProperty;
                UpdatedAtPropertyMetadata = new SqlPropertyMetadata(UpdatedAtProperty);
            }
        }
        private void InitLogicalDeleted()
        {
            var statusProperty =
                SqlProperties.FirstOrDefault(x => x.PropertyInfo.GetCustomAttributes <StatusAttribute>().Any());

            if (statusProperty == null)
            {
                return;
            }
            StatusPropertyName = statusProperty.ColumnName;

            if (statusProperty.PropertyInfo.PropertyType.IsBool())
            {
                var deleteProperty = AllProperties.FirstOrDefault(p => p.GetCustomAttributes <DeletedAttribute>().Any());
                if (deleteProperty == null)
                {
                    return;
                }

                LogicalDelete      = true;
                LogicalDeleteValue = 1; // true
            }
            else if (statusProperty.PropertyInfo.PropertyType.IsEnum())
            {
                var deleteOption = statusProperty.PropertyInfo.PropertyType.GetFields().FirstOrDefault(f => f.GetCustomAttribute <DeletedAttribute>() != null);

                if (deleteOption == null)
                {
                    return;
                }

                var enumValue = Enum.Parse(statusProperty.PropertyInfo.PropertyType, deleteOption.Name);
                LogicalDeleteValue = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(statusProperty.PropertyInfo.PropertyType));

                LogicalDelete = true;
            }
        }
Пример #4
0
        /// <summary>
        /// Removes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public bool Remove(Property item)
        {
            if ((item == null) || string.IsNullOrWhiteSpace(item.PropertyName))
            {
                return(false);
            }
            bool res = false;

            if (PrimaryKey != null)
            {
                if (PrimaryKey.Keys.Contains(item.PropertyName))
                {
                    PrimaryKey.Keys.Remove(item.PropertyName);
                    res = true;
                }
            }

            if (Properties.Contains(item.PropertyName))
            {
                Properties.Remove(item.PropertyName);
                res = true;
            }
            else if (Relations.Contains(item.PropertyName))
            {
                Relations.Remove(item.PropertyName);
                res = true;
            }

            if (AllProperties.Contains(item.PropertyName))
            {
                AllProperties.Remove(item.PropertyName);
                res = true;
            }

            return(res);
        }
    /// <summary>
    /// Creates a new instance of the <see cref="TypeCacheResolver"/> class.
    /// </summary>
    /// <param name="type">Type of the cached properties.</param>
    /// <param name="nameMatchResolver">Name match resolver.</param>
    /// <param name="dynamicType">Whether the cached type is dynamic.</param>
    /// <param name="dynamicContainerName">Dynamic container name.</param>
    public TypeCacheResolver(
        Type type,
        INameMatchResolver nameMatchResolver,
        bool dynamicType            = false,
        string dynamicContainerName = "DynamicProperties")
    {
        _nameMatchResolver = nameMatchResolver;

        Type                      = type;
        DerivedTypes              = type.DerivedTypes().ToList();
        IsDynamicType             = dynamicType;
        DynamicPropertiesName     = dynamicContainerName;
        TypeInfo                  = type.GetTypeInfo();
        AllProperties             = type.GetAllProperties().ToList();
        DeclaredProperties        = type.GetDeclaredProperties().ToList();
        AllFields                 = type.GetAllFields().ToList();
        DeclaredFields            = type.GetDeclaredFields().ToList();
        MappedName                = type.GetMappedName();
        MappedProperties          = type.GetMappedProperties().ToList();
        MappedPropertiesWithNames = type.GetMappedPropertiesWithNames().ToList();

        IsAnonymousType     = type.IsAnonymousType();
        AnnotationsProperty = AllProperties.FirstOrDefault(x => x.PropertyType == typeof(ODataEntryAnnotations));
    }
Пример #6
0
        public SqlGenerator(ESqlConnector sqlConnector)
        {
            SqlConnector = sqlConnector;
            var entityType     = typeof(TEntity);
            var entityTypeInfo = entityType.GetTypeInfo();
            var aliasAttribute = entityTypeInfo.GetCustomAttribute <TableAttribute>();

            this.TableName = aliasAttribute != null ? aliasAttribute.Name : entityTypeInfo.Name;
            AllProperties  = entityType.GetProperties();
            //Load all the "primitive" entity properties
            var props = AllProperties.Where(ExpressionHelper.GetPrimitivePropertiesPredicate()).ToArray();

            //Filter the non stored properties
            this.BaseProperties = props.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new PropertyMetadata(p));

            //Filter key properties
            this.KeyProperties = props.Where(p => p.GetCustomAttributes <KeyAttribute>().Any()).Select(p => new PropertyMetadata(p));

            //Use identity as key pattern
            var identityProperty = props.FirstOrDefault(p => p.GetCustomAttributes <IdentityAttribute>().Any());

            this.IdentityProperty = identityProperty != null ? new PropertyMetadata(identityProperty) : null;

            //Status property (if exists, and if it does, it must be an enumeration)
            var statusProperty = props.FirstOrDefault(p => p.GetCustomAttributes <StatusAttribute>().Any());

            if (statusProperty == null)
            {
                return;
            }
            StatusProperty = new PropertyMetadata(statusProperty);

            if (statusProperty.PropertyType.IsBool())
            {
                var deleteProperty = props.FirstOrDefault(p => p.GetCustomAttributes <DeletedAttribute>().Any());
                if (deleteProperty == null)
                {
                    return;
                }

                LogicalDelete      = true;
                LogicalDeleteValue = 1; // true
            }
            else if (statusProperty.PropertyType.IsEnum())
            {
                var deleteOption =
                    statusProperty.PropertyType.GetFields()
                    .FirstOrDefault(f => f.GetCustomAttribute <DeletedAttribute>() != null);

                if (deleteOption == null)
                {
                    return;
                }

                var enumValue = Enum.Parse(statusProperty.PropertyType, deleteOption.Name);

                if (enumValue != null)
                {
                    LogicalDeleteValue = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(statusProperty.PropertyType));
                }

                LogicalDelete = true;
            }
        }
Пример #7
0
        private string AppendJoinToSelect(SqlQuery originalBuilder, params Expression <Func <TEntity, object> >[] includes)
        {
            var joinBuilder = new StringBuilder();

            foreach (var include in includes)
            {
                var joinProperty = AllProperties.First(q => q.Name == ExpressionHelper.GetPropertyName(include));
                var attrJoin     = joinProperty.GetCustomAttribute <JoinAttributeBase>();

                if (attrJoin == null)
                {
                    continue;
                }

                var declaringType  = joinProperty.DeclaringType.GetTypeInfo();
                var tableAttribute = declaringType.GetCustomAttribute <TableAttribute>();
                var tableName      = tableAttribute != null ? tableAttribute.Name : declaringType.Name;

                var joinString = "";
                switch (attrJoin)
                {
                case LeftJoinAttribute _:
                    joinString = "LEFT JOIN";
                    break;

                case InnerJoinAttribute _:
                    joinString = "INNER JOIN";
                    break;

                case RightJoinAttribute _ when Config.SqlProvider == SqlProvider.SQLite:
                    throw new NotSupportedException("SQLite doesn't support RIGHT JOIN");

                case RightJoinAttribute _:
                    joinString = "RIGHT JOIN";
                    break;

                case CrossJoinAttribute _:
                    joinString = "CROSS JOIN";
                    break;
                }

                var joinType   = joinProperty.PropertyType.IsGenericType ? joinProperty.PropertyType.GenericTypeArguments[0] : joinProperty.PropertyType;
                var properties = joinType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                var props      = properties.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

                if (Config.UseQuotationMarks)
                {
                    switch (Config.SqlProvider)
                    {
                    case SqlProvider.MSSQL:
                        tableName            = "[" + tableName + "]";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "[", "]");
                        attrJoin.Key         = "[" + attrJoin.Key + "]";
                        attrJoin.ExternalKey = "[" + attrJoin.ExternalKey + "]";
                        attrJoin.TableAlias  = "[" + attrJoin.TableAlias + "]";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "[" + prop.ColumnName + "]";
                        }
                        break;

                    case SqlProvider.MySQL:
                        tableName            = "`" + tableName + "`";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "`", "`");
                        attrJoin.Key         = "`" + attrJoin.Key + "`";
                        attrJoin.ExternalKey = "`" + attrJoin.ExternalKey + "`";
                        attrJoin.TableAlias  = "`" + attrJoin.TableAlias + "`";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "`" + prop.ColumnName + "`";
                        }
                        break;

                    case SqlProvider.SQLite:
                        break;

                    case SqlProvider.PostgreSQL:
                        tableName            = "\"" + tableName + "\"";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "\"", "\"");
                        attrJoin.Key         = "\"" + attrJoin.Key + "\"";
                        attrJoin.ExternalKey = "\"" + attrJoin.ExternalKey + "\"";
                        attrJoin.TableAlias  = "\"" + attrJoin.TableAlias + "\"";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "\"" + prop.ColumnName + "\"";
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(Config.SqlProvider));
                    }
                }
                else
                {
                    attrJoin.TableName = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema);
                }

                originalBuilder.SqlBuilder.Append($", {GetFieldsSelect(attrJoin.TableAlias, props)}");
                joinBuilder.Append(
                    attrJoin is CrossJoinAttribute
                        ? $"{joinString} {attrJoin.TableName} AS {attrJoin.TableAlias}"
                        : $"{joinString} {attrJoin.TableName} AS {attrJoin.TableAlias} ON {tableName}.{attrJoin.Key} = {attrJoin.TableAlias}.{attrJoin.ExternalKey} ");
            }

            return(joinBuilder.ToString());
        }
Пример #8
0
 private PropertyDescriptor FindPropertyDescriptor(ColumnId columnId)
 {
     return(AllProperties.FirstOrDefault(pd => Equals(columnId, ColumnId.GetColumnId(pd))));
 }
        private string AppendJoinToSelect(SqlQuery originalBuilder, params Expression <Func <TEntity, object> >[] includes)
        {
            var joinSql = "";

            var joinedProperties = new List <PropertyInfo>();

            foreach (var include in includes)
            {
                var propertyName = ExpressionHelper.GetFullPropertyName(include);
                var joinProperty = AllProperties.Concat(joinedProperties).First(x =>
                {
                    if (x.DeclaringType != null)
                    {
                        return(x.DeclaringType.FullName + "." + x.Name == propertyName);
                    }
                    return(false);
                });

                var tableName = GetTableNameOrAlias(joinProperty.DeclaringType);

                var attrJoin = joinProperty.GetCustomAttribute <JoinAttributeBase>();

                if (attrJoin == null)
                {
                    continue;
                }

                var joinString = "";
                if (attrJoin is LeftJoinAttribute)
                {
                    joinString = "LEFT JOIN";
                }
                else if (attrJoin is InnerJoinAttribute)
                {
                    joinString = "INNER JOIN";
                }
                else if (attrJoin is RightJoinAttribute)
                {
                    joinString = "RIGHT JOIN";
                }

                var joinType = joinProperty.PropertyType.IsGenericType() ? joinProperty.PropertyType.GenericTypeArguments[0] : joinProperty.PropertyType;
                joinedProperties.AddRange(joinType.GetProperties().Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()));
                var properties = joinType.GetProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                var props      = properties.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

                switch (SqlConnector)
                {
                case ESqlConnector.MSSQL:
                    tableName            = "[" + tableName + "]";
                    attrJoin.TableName   = "[" + attrJoin.TableName + "]";
                    attrJoin.Key         = "[" + attrJoin.Key + "]";
                    attrJoin.ExternalKey = "[" + attrJoin.ExternalKey + "]";
                    foreach (var prop in props)
                    {
                        prop.ColumnName = "[" + prop.ColumnName + "]";
                    }
                    break;

                case ESqlConnector.MySQL:
                    tableName            = "`" + tableName + "`";
                    attrJoin.TableName   = "`" + attrJoin.TableName + "`";
                    attrJoin.Key         = "`" + attrJoin.Key + "`";
                    attrJoin.ExternalKey = "`" + attrJoin.ExternalKey + "`";
                    foreach (var prop in props)
                    {
                        prop.ColumnName = "`" + prop.ColumnName + "`";
                    }
                    break;

                case ESqlConnector.PostgreSQL:
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(SqlConnector));
                }

                originalBuilder.SqlBuilder.Append(", " + GetFieldsSelect(attrJoin.TableName, props));
                joinSql += joinString + " " + attrJoin.TableName + " ON " + tableName + "." + attrJoin.Key + " = " + attrJoin.TableName + "." + attrJoin.ExternalKey + " ";
            }
            return(joinSql);
        }
Пример #10
0
        public void PopulateSystemProperties()
        {
            IPropertyDescriptionList propertyDescriptionList = null;
            IPropertyDescription     propertyDescription     = null;
            Guid guid = new Guid(ShellIIDGuid.IPropertyDescriptionList);

            try
            {
                int hr = PropertySystemNativeMethods.PSEnumeratePropertyDescriptions(PropertySystemNativeMethods.PropDescEnumFilter.PDEF_ALL, ref guid, out propertyDescriptionList);
                if (hr >= 0)
                {
                    uint count;
                    propertyDescriptionList.GetCount(out count);
                    guid = new Guid(ShellIIDGuid.IPropertyDescription);
                    Dictionary <string, List <string> > dict = new Dictionary <string, List <string> >();

                    for (uint i = 0; i < count; i++)
                    {
                        propertyDescriptionList.GetAt(i, ref guid, out propertyDescription);

                        string propName;
                        propertyDescription.GetCanonicalName(out propName);

                        List <string> names = null;
                        string[]      parts = propName.Split('.');
                        if (parts.Count() == 2)
                        {
                            // System.Foo
                            if (!dict.TryGetValue(parts[0], out names))
                            {
                                names = new List <string>();
                                dict.Add(parts[0], names);
                            }
                            names.Add(parts[1]);
                        }
                        else if (parts.Count() == 3)
                        {
                            // System.Bar.Baz
                            if (!dict.TryGetValue(parts[1], out names))
                            {
                                names = new List <string>();
                                dict.Add(parts[1], names);
                            }
                            names.Add(parts[2]);
                        }

                        // If we ever need it:
                        // ShellPropertyDescription desc = new ShellPropertyDescription(propertyDescription);

                        if (propertyDescription != null)
                        {
                            Marshal.ReleaseComObject(propertyDescription);
                            propertyDescription = null;
                        }
                    }

                    // build tree
                    foreach (string cat in dict.Keys)
                    {
                        TreeItem main = new TreeItem(cat, PropType.Group);
                        foreach (string name in dict[cat])
                        {
                            main.AddChild(new TreeItem(name, PropType.Normal));
                        }

                        if (cat == "System")
                        {
                            AllProperties.Insert(0, main);
                        }
                        else if (cat == "PropGroup")
                        {
                            foreach (TreeItem ti in main.Children)
                            {
                                GroupProperties.Add(ti.Name);
                            }
                        }
                        else
                        {
                            AllProperties.Add(main);
                        }
                    }
                }
            }
            finally
            {
                if (propertyDescriptionList != null)
                {
                    Marshal.ReleaseComObject(propertyDescriptionList);
                }
                if (propertyDescription != null)
                {
                    Marshal.ReleaseComObject(propertyDescription);
                }
            }
        }
Пример #11
0
 /// <summary>
 /// Returns true if this property has been specified.
 /// </summary>
 /// <param name="propertyToCheck"></param>
 /// <returns></returns>
 bool IsPropertySet(AllProperties propertyToCheck)
 {
     if (isPropertySet.ContainsKey(propertyToCheck))
         return isPropertySet[propertyToCheck];
     else
         return false;
 }
Пример #12
0
 /// <summary>
 /// Determines whether [contains] [the specified item].
 /// </summary>
 /// <param name="item">The item.</param>
 /// <returns>
 ///     <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
 /// </returns>
 public bool Contains(Property item)
 {
     return(AllProperties.Contains(item));
 }
Пример #13
0
 /// <summary>
 /// Copies to.
 /// </summary>
 /// <param name="array">The array.</param>
 /// <param name="arrayIndex">Index of the array.</param>
 public void CopyTo(Property[] array, int arrayIndex)
 {
     AllProperties.CopyTo(array, arrayIndex);
 }
Пример #14
0
 /// <summary>
 /// Gets the enumerator.
 /// </summary>
 /// <returns></returns>
 public IEnumerator <Property> GetEnumerator()
 {
     return(AllProperties.GetEnumerator());
 }
Пример #15
0
 /// <summary>
 /// Determines whether the specified property name contains property.
 /// </summary>
 /// <param name="propertyName">Name of the property.</param>
 /// <returns>
 ///     <c>true</c> if the specified property name contains property; otherwise, <c>false</c>.
 /// </returns>
 public bool ContainsProperty(string propertyName)
 {
     return(AllProperties.Contains(propertyName));
 }
Пример #16
0
        public void PopulateSystemProperties()
        {
            List <SystemProperty>    systemProperties        = new List <SystemProperty>();
            IPropertyDescriptionList propertyDescriptionList = null;
            IPropertyDescription     propertyDescription     = null;
            Guid guid = new Guid(ShellIIDGuid.IPropertyDescriptionList);

            try
            {
                int hr = PropertySystemNativeMethods.PSEnumeratePropertyDescriptions(PropertySystemNativeMethods.PropDescEnumFilter.PDEF_ALL, ref guid, out propertyDescriptionList);
                if (hr >= 0)
                {
                    uint count;
                    propertyDescriptionList.GetCount(out count);
                    guid = new Guid(ShellIIDGuid.IPropertyDescription);

                    for (uint i = 0; i < count; i++)
                    {
                        propertyDescriptionList.GetAt(i, ref guid, out propertyDescription);

                        string propName;
                        propertyDescription.GetCanonicalName(out propName);
                        IntPtr displayNamePtr;
                        string displayName = null;
                        propertyDescription.GetDisplayName(out displayNamePtr);
                        if (displayNamePtr != IntPtr.Zero)
                        {
                            displayName = Marshal.PtrToStringAuto(displayNamePtr);
                        }
                        SystemProperty sp = new SystemProperty {
                            FullName = propName, DisplayName = displayName
                        };

                        systemProperties.Add(sp);

                        // If we ever need it:
                        // ShellPropertyDescription desc = new ShellPropertyDescription(propertyDescription);

                        if (propertyDescription != null)
                        {
                            Marshal.ReleaseComObject(propertyDescription);
                            propertyDescription = null;
                        }
                    }

                    Dictionary <string, TreeItem> dict = new Dictionary <string, TreeItem>();
                    List <TreeItem> roots = new List <TreeItem>();

                    // Build tree based on property names
                    foreach (SystemProperty sp in systemProperties)
                    {
                        AddTreeItem(dict, roots, sp);
                    }

                    // Wire trees to tree controls, tweaking the structure as we go
                    TreeItem propGroup = null;
                    foreach (TreeItem root in roots)
                    {
                        if (root.Name == "System")
                        {
                            AllProperties.Insert(0, root);

                            // Move property groups from root to their own list
                            propGroup = root.Children.Where(x => x.Name == "PropGroup").FirstOrDefault();
                            if (propGroup != null)
                            {
                                foreach (TreeItem ti in propGroup.Children)
                                {
                                    GroupProperties.Add(ti.Name);
                                }
                                root.RemoveChild(propGroup);
                            }

                            // Make remaining children of System that are parents into roots
                            List <TreeItem> movers = new List <TreeItem>(root.Children.Where(x => x.Children.Count() > 0));
                            foreach (TreeItem ti in movers)
                            {
                                root.RemoveChild(ti);
                                AllProperties.Add(ti);
                            }
                        }
                        else
                        {
                            AllProperties.Add(root);
                        }
                    }
                }
            }
            finally
            {
                if (propertyDescriptionList != null)
                {
                    Marshal.ReleaseComObject(propertyDescriptionList);
                }
                if (propertyDescription != null)
                {
                    Marshal.ReleaseComObject(propertyDescription);
                }
            }
        }
Пример #17
0
        private void InitProperties()
        {
            var entityType     = typeof(TEntity);
            var entityTypeInfo = entityType.GetTypeInfo();
            var tableAttribute = entityTypeInfo.GetCustomAttribute <TableAttribute>();

            TableName   = tableAttribute != null ? tableAttribute.Name : entityTypeInfo.Name;
            TableSchema = tableAttribute != null ? tableAttribute.Schema : string.Empty;

            AllProperties = entityType.FindClassProperties().Where(q => q.CanWrite).ToArray();

            var props = AllProperties.Where(ExpressionHelper.GetPrimitivePropertiesPredicate()).ToArray();

            var joinProperties = AllProperties.Where(p => p.GetCustomAttributes <JoinAttributeBase>().Any()).ToArray();

            SqlJoinProperties = GetJoinPropertyMetadata(joinProperties);

            // Filter the non stored properties
            SqlProperties = props.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            KeyUpsertSqlProperties =
                props.Where(e => e.GetCustomAttributes <UpsertKeyAttribute>().Any())
                .Select(p => new SqlPropertyMetadata(p))
                .ToArray();

            // Filter key properties
            KeySqlProperties = props.Where(p => p.GetCustomAttributes <KeyAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            if (!KeySqlProperties.Any())
            {
                var prop = props.SingleOrDefault(p => p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase));
                //skip adding key if prop is null, which means the model doesn't have Id property....
                if (prop != null)
                {
                    KeySqlProperties    = new SqlPropertyMetadata[1];
                    KeySqlProperties[0] = new SqlPropertyMetadata(prop);
                }
            }

            // Use identity as key pattern
            var identityProperty = props.FirstOrDefault(p => p.GetCustomAttributes <IdentityAttribute>().Any());

            IdentitySqlProperty = identityProperty != null ? new SqlPropertyMetadata(identityProperty) : null;

            var dateChangedProperty = props.FirstOrDefault(p => p.GetCustomAttributes <UpdatedAtAttribute>().Count() == 1);

            if (dateChangedProperty != null && (dateChangedProperty.PropertyType == typeof(DateTime) || dateChangedProperty.PropertyType == typeof(DateTime?)))
            {
                UpdatedAtProperty         = props.FirstOrDefault(p => p.GetCustomAttributes <UpdatedAtAttribute>().Any());
                UpdatedAtPropertyMetadata = new SqlPropertyMetadata(UpdatedAtProperty);
            }

            var modifiedDateProperty = props.FirstOrDefault(p => p.GetCustomAttributes <ModifiedAtAttribute>().Count() == 1);

            if (modifiedDateProperty != null &&
                (modifiedDateProperty.PropertyType == typeof(DateTime) ||
                 modifiedDateProperty.PropertyType == typeof(DateTime?)))
            {
                ModifiedAtProperty         = props.FirstOrDefault(p => p.GetCustomAttributes <ModifiedAtAttribute>().Any());
                ModifiedAtPropertyMetadata = new SqlPropertyMetadata(ModifiedAtProperty);
            }
        }
 public IClassNetCacheProperty GetProperty(int id)
 {
     return(AllProperties.Where(x => x.Id == id).Single());
 }
Пример #19
0
        private string AppendJoinToSelect(SqlQuery originalBuilder, params Expression <Func <TEntity, object> >[] includes)
        {
            var joinBuilder = new StringBuilder();

            foreach (var include in includes)
            {
                var joinProperty   = AllProperties.First(q => q.Name == ExpressionHelper.GetPropertyName(include));
                var declaringType  = joinProperty.DeclaringType.GetTypeInfo();
                var tableAttribute = declaringType.GetCustomAttribute <TableAttribute>();
                var tableName      = tableAttribute != null ? tableAttribute.Name : declaringType.Name;

                var attrJoin = joinProperty.GetCustomAttribute <JoinAttributeBase>();

                if (attrJoin == null)
                {
                    continue;
                }

                var joinString = "";
                if (attrJoin is LeftJoinAttribute)
                {
                    joinString = "LEFT JOIN";
                }
                else if (attrJoin is InnerJoinAttribute)
                {
                    joinString = "INNER JOIN";
                }
                else if (attrJoin is RightJoinAttribute)
                {
                    joinString = "RIGHT JOIN";
                }

                var joinType   = joinProperty.PropertyType.IsGenericType() ? joinProperty.PropertyType.GenericTypeArguments[0] : joinProperty.PropertyType;
                var properties = joinType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                var props      = properties.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

                if (Config.UseQuotationMarks)
                {
                    switch (Config.SqlConnector)
                    {
                    case ESqlConnector.MSSQL:
                        tableName            = "[" + tableName + "]";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "[", "]");
                        attrJoin.Key         = "[" + attrJoin.Key + "]";
                        attrJoin.ExternalKey = "[" + attrJoin.ExternalKey + "]";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "[" + prop.ColumnName + "]";
                        }
                        break;

                    case ESqlConnector.MySQL:
                        tableName            = "`" + tableName + "`";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "`", "`");
                        attrJoin.Key         = "`" + attrJoin.Key + "`";
                        attrJoin.ExternalKey = "`" + attrJoin.ExternalKey + "`";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "`" + prop.ColumnName + "`";
                        }
                        break;

                    case ESqlConnector.PostgreSQL:
                        tableName            = "\"" + tableName + "\"";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "\"", "\"");
                        attrJoin.Key         = "\"" + attrJoin.Key + "\"";
                        attrJoin.ExternalKey = "\"" + attrJoin.ExternalKey + "\"";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "\"" + prop.ColumnName + "\"";
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(Config.SqlConnector));
                    }
                }
                else
                {
                    attrJoin.TableName = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema);
                }

                originalBuilder.SqlBuilder.Append(", " + GetFieldsSelect(attrJoin.TableName, props));
                joinBuilder.Append(joinString + " " + attrJoin.TableName + " ON " + tableName + "." + attrJoin.Key + " = " + attrJoin.TableName + "." + attrJoin.ExternalKey + " ");
            }
            return(joinBuilder.ToString());
        }
Пример #20
0
        private void InitProperties()
        {
            var entityType     = typeof(TEntity);
            var entityTypeInfo = entityType.GetTypeInfo();
            var tableAttribute = entityTypeInfo.GetCustomAttribute <TableAttribute>();

            TableName   = tableAttribute != null ? tableAttribute.Name : entityTypeInfo.Name;
            TableSchema = tableAttribute != null ? tableAttribute.Schema : string.Empty;

            AllProperties = entityType.FindClassProperties().Where(q => q.CanWrite).ToArray();

            var props = AllProperties.Where(ExpressionHelper.GetPrimitivePropertiesPredicate()).ToArray();

            var joinProperties = AllProperties.Where(p => p.GetCustomAttributes <JoinAttributeBase>().Any()).ToArray();

            SqlJoinProperties = GetJoinPropertyMetadata(joinProperties);

            // Filter the non stored properties
            SqlProperties = props.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            // Filter key properties
            KeySqlProperties = props.Where(p => p.GetCustomAttributes <KeyAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

            // Use identity as key pattern
            var identityProperty = props.FirstOrDefault(p => p.GetCustomAttributes <IdentityAttribute>().Any());

            IdentitySqlProperty = identityProperty != null ? new SqlPropertyMetadata(identityProperty) : null;

            var dateCreatedProperty = props.FirstOrDefault(p => p.GetCustomAttributes <CreatedAtAttribute>().Count() == 1);

            if (dateCreatedProperty != null && (dateCreatedProperty.PropertyType == typeof(DateTime) ||
                                                dateCreatedProperty.PropertyType == typeof(DateTime?)) &&
                !dateCreatedProperty.GetCustomAttributes <NotMappedAttribute>().Any())
            {
                CreatedAtProperty         = props.FirstOrDefault(p => p.GetCustomAttributes <CreatedAtAttribute>().Any());
                CreatedAtPropertyMetadata = new SqlPropertyMetadata(CreatedAtProperty);
            }

            var dateChangedProperty = props.FirstOrDefault(p => p.GetCustomAttributes <UpdatedAtAttribute>().Count() == 1);

            if (dateChangedProperty != null && (dateChangedProperty.PropertyType == typeof(DateTime) || dateChangedProperty.PropertyType == typeof(DateTime?)))
            {
                UpdatedAtProperty         = props.FirstOrDefault(p => p.GetCustomAttributes <UpdatedAtAttribute>().Any());
                UpdatedAtPropertyMetadata = new SqlPropertyMetadata(UpdatedAtProperty);
            }

            var rowVersionProperty = props.FirstOrDefault(p => p.GetCustomAttributes <RowVersionAttribute>().Count() == 1);

            if (rowVersionProperty != null && (rowVersionProperty.PropertyType == typeof(byte[]) ||
                                               rowVersionProperty.PropertyType == typeof(byte)) &&
                !rowVersionProperty.GetCustomAttributes <NotMappedAttribute>().Any())
            {
                RowVersionProperty         = props.FirstOrDefault(p => p.GetCustomAttributes <RowVersionAttribute>().Any());
                RowVersionPropertyMetadata = new SqlPropertyMetadata(RowVersionProperty);
            }

            var manUpdateProperty = props.Where(p => p.GetCustomAttributes <MandatoryUpdateAttribute>().Any());

            if (manUpdateProperty.Any())
            {
                MandatoryUpdateProperty   = props.Where(p => p.GetCustomAttributes <MandatoryUpdateAttribute>().Any() && !p.GetCustomAttributes <NotMappedAttribute>().Any()).ToArray();
                ManUpdatePropertyMetadata = MandatoryUpdateProperty.Select(x => new SqlPropertyMetadata(x)).ToArray();
            }

            var manInsertProperty = props.Where(p => p.GetCustomAttributes <MandatoryInsertAttribute>().Any());

            if (manInsertProperty.Any())
            {
                MandatoryInsertProperty   = props.Where(p => p.GetCustomAttributes <MandatoryInsertAttribute>().Any() && !p.GetCustomAttributes <NotMappedAttribute>().Any()).ToArray();
                ManInsertPropertyMetadata = MandatoryInsertProperty.Select(x => new SqlPropertyMetadata(x)).ToArray();
            }
        }
Пример #21
0
 void PropertyIsSet(AllProperties propertyToCheck)
 {
     if (isPropertySet.ContainsKey(propertyToCheck))
         isPropertySet[propertyToCheck] = true;
     else
         isPropertySet.Add(propertyToCheck, true);
 }
Пример #22
0
        private void LazyInitializeDerivedCollections()
        {
            _allProperties = new Lazy <IReadOnlyList <ResourceProperty> >(
                () =>

                // Add locally defined identifying properties first
                Properties.Where(p => p.IsIdentifying)

                // Add reference properties, identifying references first, followed by required, and then optional
                .Concat(
                    References
                    .OrderByDescending(
                        r => (r.Association.IsIdentifying ? 100: 0)
                        + (r.IsRequired ? 10 : 0))
                    .SelectMany(r => r.Properties))

                // Add non-identifying properties
                .Concat(Properties.Where(p => !p.IsIdentifying))
                .Distinct(ModelComparers.ResourcePropertyNameOnly)
                .ToList());

            _allPropertyByName = new Lazy <IReadOnlyDictionary <string, ResourceProperty> >(
                () =>
                AllProperties.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase));

            _propertyByName = new Lazy <IReadOnlyDictionary <string, ResourceProperty> >(
                () =>
                Properties
                .ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase));

            _embeddedObjectByName = new Lazy <IReadOnlyDictionary <string, EmbeddedObject> >(
                () =>
                EmbeddedObjects.ToDictionary(
                    x => x.PropertyName,
                    x => x,
                    StringComparer.InvariantCultureIgnoreCase));

            // Added lazy initialization of dictionary
            _extensionByName = new Lazy <IReadOnlyDictionary <string, Extension> >(
                () =>
                Extensions.ToDictionary(
                    x => x.PropertyName,
                    x => x,
                    StringComparer.InvariantCultureIgnoreCase));

            _collectionByName = new Lazy <IReadOnlyDictionary <string, Collection> >(
                () =>
                Collections.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase));

            _referenceByName = new Lazy <IReadOnlyDictionary <string, Reference> >(
                () =>
                References.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase));

            _allMembers = new Lazy <IReadOnlyList <ResourceMemberBase> >(
                () => LazyInitializeAllMembers()
                .ToList());

            _memberByName = new Lazy <IReadOnlyDictionary <string, ResourceMemberBase> >(
                () => AllMembers.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase));

            _memberNamesInvolvedInJsonCollisions = new Lazy <IReadOnlyList <string> >(
                () =>
            {
                var allProposedNames =
                    AllMembers.Select(
                        p =>
                        Tuple.Create(
                            p.PropertyName,
                            JsonNamingConvention.ProposeJsonPropertyName(p.ParentFullName.Name, p.PropertyName)))
                    .ToList();

                var proposedJsonNames = new HashSet <string>();
                var rejectedJsonNames = new HashSet <string>();

                foreach (var nameAndProposedName in allProposedNames)
                {
                    if (!proposedJsonNames.Add(nameAndProposedName.Item2))
                    {
                        rejectedJsonNames.Add(nameAndProposedName.Item2);
                    }
                }

                return(allProposedNames
                       .Where(t => rejectedJsonNames.Contains(t.Item2))
                       .Select(t => t.Item1)
                       .ToList());
            }
                );
        }
        private string AppendJoinToSelect(SqlQuery originalBuilder, params Expression <Func <TEntity, object> >[] includes)
        {
            var joinBuilder = new StringBuilder();

            foreach (var include in includes)
            {
                var joinProperty   = AllProperties.First(q => q.Name == ExpressionHelper.GetPropertyName(include));
                var declaringType  = joinProperty.DeclaringType.GetTypeInfo();
                var tableAttribute = declaringType.GetCustomAttribute <TableAttribute>();
                var tableName      = tableAttribute != null ? tableAttribute.Name : declaringType.Name;

                var attrJoin = joinProperty.GetCustomAttribute <JoinAttributeBase>();

                if (attrJoin == null)
                {
                    continue;
                }

                var joinString = "";
                if (attrJoin is LeftJoinAttribute)
                {
                    joinString = "LEFT JOIN";
                }
                else if (attrJoin is InnerJoinAttribute)
                {
                    joinString = "INNER JOIN";
                }
                else if (attrJoin is RightJoinAttribute)
                {
                    joinString = "RIGHT JOIN";
                }

                var joinType   = joinProperty.PropertyType.IsGenericType() ? joinProperty.PropertyType.GenericTypeArguments[0] : joinProperty.PropertyType;
                var properties = joinType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                var props      = properties.Where(p => !p.GetCustomAttributes <NotMappedAttribute>().Any()).Select(p => new SqlPropertyMetadata(p)).ToArray();

                if (Config.UseQuotationMarks)
                {
                    switch (Config.SqlProvider)
                    {
                    case SqlProvider.MSSQL:
                        tableName            = "[" + tableName + "]";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "[", "]");
                        attrJoin.Key         = "[" + attrJoin.Key + "]";
                        attrJoin.ExternalKey = "[" + attrJoin.ExternalKey + "]";
                        attrJoin.TableAlias  = "[" + attrJoin.TableAlias + "]";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "[" + prop.ColumnName + "]";
                        }
                        break;

                    case SqlProvider.MySQL:
                        tableName            = "`" + tableName + "`";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "`", "`");
                        attrJoin.Key         = "`" + attrJoin.Key + "`";
                        attrJoin.ExternalKey = "`" + attrJoin.ExternalKey + "`";
                        attrJoin.TableAlias  = "`" + attrJoin.TableAlias + "`";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "`" + prop.ColumnName + "`";
                        }
                        break;

                    case SqlProvider.PostgreSQL:
                        tableName            = "\"" + tableName + "\"";
                        attrJoin.TableName   = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema, "\"", "\"");
                        attrJoin.Key         = "\"" + attrJoin.Key + "\"";
                        attrJoin.ExternalKey = "\"" + attrJoin.ExternalKey + "\"";
                        attrJoin.TableAlias  = "\"" + attrJoin.TableAlias + "\"";
                        foreach (var prop in props)
                        {
                            prop.ColumnName = "\"" + prop.ColumnName + "\"";
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(Config.SqlProvider));
                    }
                }
                else
                {
                    attrJoin.TableName = GetTableNameWithSchemaPrefix(attrJoin.TableName, attrJoin.TableSchema);
                }

                originalBuilder.SqlBuilder.Append($", {GetFieldsSelect(attrJoin.TableAlias, props)}");
                joinBuilder.Append(
                    $"{joinString} {attrJoin.TableName} AS {attrJoin.TableAlias} ON {tableName}.{attrJoin.Key} = {attrJoin.TableAlias}.{attrJoin.ExternalKey} ");

                if (LogicalDelete && props.Any(s => s.PropertyName == LogicalDeleteProperty.Name))
                {
                    bool isDateTime = LogicalDeleteProperty.PropertyType.IsDateTime();
                    joinBuilder.AppendFormat(" AND {0}.{1} {2} {3} ", attrJoin.TableAlias, LogicalDeletePropertyMetadata.ColumnName, isDateTime ? "IS" : "!=", isDateTime ? "NULL" : GetLogicalDeleteValue());
                }
            }

            return(joinBuilder.ToString());
        }
Пример #24
0
 public string Get(string prop)
 {
     return(string.Join(", ", AllProperties
                        .Where(r => r.Name.Equals(prop, System.StringComparison.OrdinalIgnoreCase))
                        .Select(a => a.Value).Distinct().ToArray()));
 }