Esempio n. 1
0
 private static ExplorerItem GetPropertyItem(ISessionFactory sessionFactory, IClassMetadata classMetadata, string propertyName)
 {
     var kind = GetKind(classMetadata, propertyName);
     var propertyType = classMetadata.GetPropertyType(propertyName);
     return new ExplorerItem(kind == ExplorerItemKind.Property
                                 ? string.Format("{0} ({1})", propertyName, propertyType.ReturnedClass.Name)
                                 : propertyName,
                             kind,
                             GetIcon(sessionFactory, classMetadata, propertyName))
                {
                    Tag = classMetadata.GetPropertyType(propertyName)
                };
 }
Esempio n. 2
0
        /// <summary>
        /// For a given property type, containing type, and property name, return true if it should
        /// be serialized and false if not.  By default, value types and system types are serialized,
        /// but collections and custom types are not.
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="propertyType"></param>
        /// <param name="containingType"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        protected bool IsIncluded(IClassMetadata meta, Type propertyType, Type containingType, string name)
        {
            if (includedMembers != null && includedMembers.Contains(name))
            {
                return(true);
            }

            if (includedTypeMembers != null && includedTypeMembers.ContainsKey(containingType))
            {
                var list = includedTypeMembers[containingType];
                if (list.Contains(name))
                {
                    return(true);
                }
            }

            if (meta != null && meta.GetPropertyType(name).IsAssociationType)
            {
                return(false);
            }

            if (typeof(System.Collections.IEnumerable).IsAssignableFrom(propertyType))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        public static Core.Validator GetValidatorFromSession(ISessionFactory sessionFactory)
        {
            var allDefindedClasses = sessionFactory.GetAllClassMetadata();

            Core.Validator validator = new Core.Validator();
            foreach (KeyValuePair <string, IClassMetadata> pair in allDefindedClasses)
            {
                IClassMetadata metadata = pair.Value;
                foreach (string propertyName in metadata.PropertyNames)
                {
                    IType      propertyType = metadata.GetPropertyType(propertyName);
                    StringType st           = propertyType as StringType;
                    if (st != null)
                    {
                        if (st.SqlType.Length > 0)
                        {
                            validator.AddRule(Rule.For(metadata.GetMappedClass(EntityMode.Poco))
                                              .OnMember(propertyName)
                                              .MaxLength(st.SqlType.Length)
                                              .Message(String.Format(
                                                           "Property {0} have a maximum length of {1}",
                                                           propertyName,
                                                           st.SqlType.Length)));
                        }
                    }
                }
            }
            return(validator);
        }
Esempio n. 4
0
 static ExplorerItemKind GetKind(IClassMetadata classMetadata, string propertyName)
 {
     var propertyType = classMetadata.GetPropertyType(propertyName);
     return propertyType.IsCollectionType
                ? ExplorerItemKind.CollectionLink
                : propertyType.IsAssociationType
                      ? ExplorerItemKind.ReferenceLink
                      : ExplorerItemKind.Property;
 }
 private static ExplorerItem GetPropertyItem(IClassMetadata classMetadata, string propertyName)
 {
     return new ExplorerItem(string.Format("{0}", propertyName),
                             GetKind(classMetadata, propertyName),
                             GetIcon(classMetadata, propertyName))
                {
                    Tag = classMetadata.GetPropertyType(propertyName)
                };
 }
 static ExplorerIcon GetIcon(IClassMetadata classMetadata, string propertyName)
 {
     var propertyType = classMetadata.GetPropertyType(propertyName);
     return propertyType.IsCollectionType
                ? ExplorerIcon.OneToMany
                : propertyType.IsAssociationType
                      ? ExplorerIcon.ManyToOne
                      : ExplorerIcon.Column;
 }
Esempio n. 7
0
 private static IEnumerable<ExplorerItem> GetId(IClassMetadata classMetadata)
 {
     var propertyName = classMetadata.IdentifierPropertyName;
     if (propertyName != null)
         yield return new ExplorerItem(propertyName, ExplorerItemKind.Property, ExplorerIcon.Key)
                          {
                              Tag = classMetadata.GetPropertyType(propertyName)
                          };
 }
Esempio n. 8
0
        void FilterLeafNode(LeafNode leafnode, IClassMetadata metadata, DetachedCriteria query)
        {
            if (leafnode.Name == metadata.IdentifierPropertyName)
            {
                FilterPrimaryKey(leafnode, metadata, query);
                return;
            }

            var propsplit = leafnode.Name.Split('_');
            var prop      = propsplit.FirstOrDefault();
            var mode      = propsplit.LastOrDefault();

            if (prop == null)
            {
                return;
            }
            if (!metadata.PropertyNames.Contains(prop))
            {
                return;
            }

            var proptype = metadata.GetPropertyType(prop);

            if (proptype is EntityType)
            {
                var etype = (EntityType)proptype;
                if (etype.IsNullable)
                {
                    switch (leafnode.Value.ToString())
                    {
                    case "null":
                        query.Add(Restrictions.IsNull(prop));
                        SetParam(leafnode);
                        return;

                    case "notnull":
                        query.Add(Restrictions.IsNotNull(prop));
                        SetParam(leafnode);
                        return;
                    }
                }
            }
            else
            {
                if (leafnode.Value.ToString() == "all")
                {
                    return;
                }
                bool isconverted = FilterProperty(leafnode, proptype.ReturnedClass, query, prop, mode);
                if (isconverted)
                {
                    return;
                }
                Logger.Warn(string.Format("Could not convert value '{0}' to type '{1}'", leafnode.Value, proptype.ReturnedClass));
            }
        }
Esempio n. 9
0
 static ExplorerIcon GetIcon(ISessionFactory sessionFactory, IClassMetadata classMetadata, string propertyName)
 {
     var propertyType = classMetadata.GetPropertyType(propertyName);
     return propertyType.IsCollectionType
                ? ((ICollectionPersister)sessionFactory.GetCollectionMetadata(
                    string.Format("{0}.{1}", classMetadata.GetMappedClass(EntityMode.Poco), propertyName)))
                      .IsManyToMany
                      ? ExplorerIcon.ManyToMany
                      : ExplorerIcon.OneToMany
                : propertyType.IsAssociationType
                      ? ExplorerIcon.ManyToOne
                      : ExplorerIcon.Column;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="metadata"></param>
        public PersistentClassInfo(IClassMetadata metadata)
        {
            if (metadata == null)
                throw new MissingMetadataException("The metadata info of persistent class cannot be null.");

            this.metadata = metadata;
            this.properties = new HashSet<IPropertyInfo>();

            try
            {
                string idName = metadata.IdentifierPropertyName;
                IType type = metadata.GetPropertyType(idName);

                this.identifier = new PropertyMapInfo(type, idName);
            }
            catch (Exception)
            {
                //metadata.GetPropertyValuesToInsert()
            }

            metadata.PropertyNames.All
                (
                    property =>
                    {
                        try
                        {
                            IType type = metadata.GetPropertyType(property);
                            PropertyMapInfo current = new PropertyMapInfo(type, property);
                            properties.Add(current);
                        }
                        catch (Exception)
                        {
                            //
                        }
                        return true;
                    }
                );
        }
Esempio n. 11
0
        protected List <TreeNode> GetTreeNodes(IClassMetadata classMetadata, Identifier identifier)
        {
            List <TreeNode> result = new List <TreeNode>();
            // Add special ratio names in order after the default ratio name
            int lastRatioIndex = -1;

            foreach (String propertyName in classMetadata.PropertyNames)
            {
                IType propertyType = classMetadata.GetPropertyType(propertyName);
                if (propertyType is ManyToOneType)
                {
                    continue;
                }
                var  label   = propertyName;
                bool isRatio = RatioPropertyAccessor.IsRatioOrRdotpProperty(label);
                if (isRatio)
                {
                    label = RatioPropertyAccessor.GetDisplayName(label);
                }
                else if (AnnotationDef.IsAnnotationProperty(label))
                {
                    label = AnnotationDef.GetColumnDisplayName(label);
                }
                else if (label.IndexOf("Ratio", StringComparison.Ordinal) != -1) // Not L10N: Label is only used in this file. Never displayed.
                {
                    lastRatioIndex = result.Count;
                }
                var columnInfo = CreateColumnInfo(identifier, classMetadata, propertyName);
                if (columnInfo.IsHidden)
                {
                    continue;
                }
                TreeNode propertyNode
                    = new TreeNode
                    {
                    Name = propertyName,
                    Text = label,
                    Tag  = columnInfo
                    };
                if (isRatio && lastRatioIndex != -1)
                {
                    result.Insert(++lastRatioIndex, propertyNode);
                }
                else
                {
                    result.Add(propertyNode);
                }
            }
            return(result);
        }
Esempio n. 12
0
        public Dictionary <string, int> GetStringFieldLengths()
        {
            Dictionary <string, int> temp = new Dictionary <string, int>();

            IClassMetadata metadata = _sessionFactory.GetClassMetadata(typeof(T));

            foreach (string propertyName in metadata.PropertyNames)
            {
                IType      propertyType = metadata.GetPropertyType(propertyName);
                StringType st           = propertyType as StringType;
                if (st != null && st.SqlType.Length > 0)
                {
                    temp.Add(propertyName, st.SqlType.Length);
                }
            }
            return(temp);
        }
Esempio n. 13
0
        void RangeLeafNode(LeafNode node, IClassMetadata metadata)
        {
            var proptree = node.FullName.SplitAndTrim(".").Skip(1).ToList();

            if (proptree.IsEmpty())
            {
                return;
            }

            var prop = proptree.LastOrDefault();

            if (prop == null || prop.Length < 3)
            {
                return;
            }
            var mod       = prop.SplitAndTrim("_").LastOrDefault();
            var propfield = prop.Substring(0, prop.Length - 3);

            proptree[proptree.Count - 1] = propfield;
            var field = proptree.Join(".");

            var type = metadata.PropertyNames.Contains(propfield)
                            ? metadata.GetPropertyType(propfield).ReturnedClass
                            : GuessType(node);

            if (type == null)
            {
                return;
            }

            switch (mod)
            {
            case "gt":
            case "ge":
                RegisterRange(field, node.Value.ToString(), null, type);
                break;

            case "lt":
            case "le":
                RegisterRange(field, null, node.Value.ToString(), type);
                break;
            }
            Querystring[node.FullName.SplitAndTrim(".").Skip(1).Join(".")] = node.Value.ToString();
        }
Esempio n. 14
0
        void FilterCompositeNode(CompositeNode compositenode, IClassMetadata metadata, DetachedCriteria query)
        {
            if (!metadata.PropertyNames.Contains(compositenode.Name))
            {
                return;
            }
            var proptype = metadata.GetPropertyType(compositenode.Name);

            if (proptype is EntityType)
            {
                var etype         = (EntityType)proptype;
                var childmetadata = AR.Holder.GetClassMetadata(etype.ReturnedClass);
                var childcriteria = _childCriterias.TryGet(compositenode.Name, () => query.CreateCriteria(compositenode.Name, JoinType.LeftOuterJoin));
                foreach (var childnode in compositenode.ChildNodes)
                {
                    RecursiveFilter(childcriteria, childnode, childmetadata);
                }
            }
            else if (proptype is CollectionType)
            {
                var ctype         = (CollectionType)proptype;
                var reltype       = ctype.ReturnedClass.GetGenericArguments().FirstOrDefault();
                var childmetadata = AR.Holder.GetClassMetadata(reltype);
                if (childmetadata == null)
                {
                    return;
                }

                var persister = SessionFactory.GetCollectionMetadata(ctype.Role) as ICollectionPersister;
                if (persister == null)
                {
                    return;
                }

                if (persister.IsOneToMany)
                {
                }
                else if (persister.IsManyToMany)
                {
                }
            }
        }
Esempio n. 15
0
        void FilterCompositeNode(CompositeNode node, IClassMetadata metadata)
        {
            if (!metadata.PropertyNames.Contains(node.Name))
            {
                return;
            }

            var proptype = metadata.GetPropertyType(node.Name);

            if (proptype is EntityType)
            {
                var childmetadata = AR.Holder.GetClassMetadata(proptype.ReturnedClass);
                foreach (var childNode in node.ChildNodes)
                {
                    RecursiveFilter(node, childNode, childmetadata);
                }
            }
            else if (proptype is CollectionType)
            {
                var ctype   = (CollectionType)proptype;
                var reltype = ctype.ReturnedClass.GetGenericArguments().FirstOrDefault();
                if (reltype == null)
                {
                    return;
                }

                var childmetadata = AR.Holder.GetClassMetadata(reltype);
                if (childmetadata == null)
                {
                    return;
                }

                foreach (var childnode in node.ChildNodes)
                {
                    RecursiveFilter(node, childnode, childmetadata);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// For a given property type, containing type, and property name, return true if it should
        /// be serialized and false if not.  By default, value types and system types are serialized,
        /// but collections and custom types are not.
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="propertyType"></param>
        /// <param name="containingType"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        protected bool IsIncluded(IClassMetadata meta, Type propertyType, Type containingType, string name)
        {
            if (includedMembers != null && includedMembers.Contains(name)) return true;

            if (includedTypeMembers != null && includedTypeMembers.ContainsKey(containingType))
            {
                var list = includedTypeMembers[containingType];
                if (list.Contains(name)) return true;
            }

            if (meta != null && meta.GetPropertyType(name).IsAssociationType) return false;

            if (typeof(System.Collections.IEnumerable).IsAssignableFrom(propertyType)) return false;

            return true;
        }
Esempio n. 17
0
        /// <summary>
        /// Add the Fetch clauses to the query according to the given expand paths
        /// </summary>
        /// <param name="queryable">The query to expand</param>
        /// <param name="expandPaths">The names of the properties to expand.  May include nested paths of the form "Property/SubProperty"</param>
        /// <param name="sessionFactory">Provides the NHibernate metadata for the classes</param>
        /// <param name="expandMap">Will be populated with the names of the expanded properties for each type.</param>
        /// <param name="expandCollections">If true, eagerly fetch collections. Caution: this causes problems with $skip and $top operations.
        ///     Default is false.  expandMap will still be populated with the collection property, so it will be lazy loaded.
        ///     Be sure to set default_batch_fetch_size in the configuration for lazy loaded collections.</param>
        /// <returns></returns>
        public IQueryable ApplyExpansions(IQueryable queryable, string[] expandPaths, ExpandTypeMap expandMap, bool expandCollections = false)
        {
            if (queryable == null)
            {
                throw new ArgumentException("Query cannot be null");
            }

            var nHibQuery = queryable.Provider as DefaultQueryProvider;

            if (nHibQuery == null)
            {
                throw new ArgumentException("Expansion only supported on INHibernateQueryable queries");
            }

            if (!expandPaths.Any())
            {
                throw new ArgumentException("Expansion Paths cannot be null");
            }

            var currentQueryable = queryable;

            foreach (string expand in expandPaths)
            {
                // We always start with the resulting element type
                var currentType  = currentQueryable.ElementType;
                var isFirstFetch = true;
                var isInvoking   = true;

                // split on '/' or '.'
                var segments = expand.Split('/', '.');
                expandMap.Deepen(segments.Length);
                foreach (string seg in segments)
                {
                    if (expandMap != null && !expandMap.map.ContainsKey(currentType))
                    {
                        expandMap.map.Add(currentType, new List <string>());
                    }

                    IClassMetadata metadata = sessionFactory.GetClassMetadata(currentType);
                    if (metadata == null)
                    {
                        throw new ArgumentException("Type '" + currentType + "' not recognized as a valid type for this Context");
                    }

                    // Gather information about the property
                    var propInfo = currentType.GetProperty(seg);

                    if (propInfo == null)
                    {
                        throw new ArgumentException("Type '" + currentType.Name + "' does not have property '" + seg + "'");
                    }
                    if (expandMap != null && !expandMap.map[currentType].Contains(seg))
                    {
                        expandMap.map[currentType].Add(seg);
                    }

                    var propType     = propInfo.PropertyType;
                    var metaPropType = metadata.GetPropertyType(seg);

                    // When this is the first segment of a path, we have to use Fetch instead of ThenFetch
                    var propFetchFunctionName = (isFirstFetch ? "Fetch" : "ThenFetch");

                    // The delegateType is a type for the lambda creation to create the correct return value
                    System.Type delegateType;

                    if (metaPropType.IsCollectionType)
                    {
                        // We have to use "FetchMany" or "ThenFetchMany" when the target property is a collection
                        propFetchFunctionName += "Many";

                        // We only support IList<T> or something similar
                        propType     = propType.GetGenericArguments().Single();
                        delegateType = typeof(Func <,>).MakeGenericType(currentType,
                                                                        typeof(IEnumerable <>).MakeGenericType(propType));
                        if (!expandCollections)
                        {
                            // if we don't expand this collection, we won't invoke any sub-expansions of it either
                            // but we still need to traverse the tree top populate expandMap
                            isInvoking = false;
                        }
                    }
                    else
                    {
                        delegateType = typeof(Func <,>).MakeGenericType(currentType, propType);
                    }

                    if (isInvoking)
                    {
                        // Get the correct extension method (Fetch, FetchMany, ThenFetch, or ThenFetchMany)
                        var fetchMethodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(propFetchFunctionName,
                                                                                              BindingFlags.Static |
                                                                                              BindingFlags.Public |
                                                                                              BindingFlags.InvokeMethod);
                        var fetchMethodTypes = new List <System.Type>();
                        fetchMethodTypes.AddRange(currentQueryable.GetType().GetGenericArguments().Take(isFirstFetch ? 1 : 2));
                        fetchMethodTypes.Add(propType);
                        fetchMethodInfo = fetchMethodInfo.MakeGenericMethod(fetchMethodTypes.ToArray());

                        // Create an expression of type new delegateType(x => x.{seg.Name})
                        var exprParam  = System.Linq.Expressions.Expression.Parameter(currentType, "x");
                        var exprProp   = System.Linq.Expressions.Expression.Property(exprParam, seg);
                        var exprLambda = System.Linq.Expressions.Expression.Lambda(delegateType, exprProp,
                                                                                   new System.Linq.Expressions.
                                                                                   ParameterExpression[] { exprParam });

                        // Call the *Fetch* function
                        var args = new object[] { currentQueryable, exprLambda };
                        currentQueryable = (IQueryable)fetchMethodInfo.Invoke(null, args) as IQueryable;
                    }
                    currentType  = propType;
                    isFirstFetch = false;
                }
            }

            return(currentQueryable);
        }
Esempio n. 18
0
 protected List<TreeNode> GetTreeNodes(IClassMetadata classMetadata, Identifier identifier)
 {
     List<TreeNode> result = new List<TreeNode>();
     // Add special ratio names in order after the default ratio name
     int lastRatioIndex = -1;
     foreach (String propertyName in classMetadata.PropertyNames)
     {
         IType propertyType = classMetadata.GetPropertyType(propertyName);
         if (propertyType is ManyToOneType)
         {
             continue;
         }
         var label = propertyName;
         bool isRatio = RatioPropertyAccessor.IsRatioOrRdotpProperty(label);
         if (isRatio)
             label = RatioPropertyAccessor.GetDisplayName(label);
         else if (AnnotationDef.IsAnnotationProperty(label))
             label = AnnotationDef.GetColumnDisplayName(label);
         else if (label.IndexOf("Ratio", StringComparison.Ordinal) != -1) // Not L10N: Label is only used in this file. Never displayed.
             lastRatioIndex = result.Count;
         var columnInfo = CreateColumnInfo(identifier, classMetadata, propertyName);
         if (columnInfo.IsHidden)
         {
             continue;
         }
         TreeNode propertyNode
             = new TreeNode
             {
                 Name = propertyName,
                 Text = label,
                 Tag = columnInfo
             };
         if (isRatio && lastRatioIndex != -1)
             result.Insert(++lastRatioIndex, propertyNode);
         else
             result.Add(propertyNode);
     }
     return result;
 }
Esempio n. 19
0
        /// <summary>
        /// 查找用户是否包含属性
        /// </summary>
        /// <param name="propertyName">属性名</param>
        /// <returns></returns>
        public bool CheckEntityHasProperty(string propertyName)
        {
            IClassMetadata classMetadata = GetClassMetadata();

            return(classMetadata.GetPropertyType(propertyName) != null);
        }