public void GetType_should_return_mapped_type_when_type_is_registered()
        {
            var typeDescription = new TypeDescription("test", new IPropertyDescription[0]);
            var generatedType = new GeneratedType("test", typeof(int), typeDescription);
            typeMapper.RegisterNewType(typeDescription, generatedType);

            var result = typeMapper.GetType(this.GetType());

            Assert.AreEqual(result, this.GetType());
        }
 private void BuildDictionary(
     DataType dataType,
     Type type,
     TypeDescription typeDescription,
     bool inputGraph,
     IEnumerable<Type> ancestors, 
     MemberDescription memberDescription)
 {
     var types = type.GetGenericDictionaryTypes();
     dataType.IsDictionary = true;
     dataType.Comments = memberDescription.WhenNotNull(x => x.Comments).OtherwiseDefault() ?? dataType.Comments;
     dataType.DictionaryEntry = new DictionaryEntry
     {
         KeyName = memberDescription.WhenNotNull(x => x.DictionaryEntry.KeyName).OtherwiseDefault() ??
                   typeDescription.WhenNotNull(x => x.DictionaryEntry.KeyName).OtherwiseDefault(),
         KeyComments = memberDescription.WhenNotNull(x => x.DictionaryEntry.KeyComments).OtherwiseDefault() ??
                       typeDescription.WhenNotNull(x => x.DictionaryEntry.KeyComments).OtherwiseDefault(),
         KeyType = BuildGraph(dataType, types.Key, inputGraph, ancestors),
         ValueComments = memberDescription.WhenNotNull(x => x.DictionaryEntry.ValueComments).OtherwiseDefault() ??
                         typeDescription.WhenNotNull(x => x.DictionaryEntry.ValueComments).OtherwiseDefault(),
         ValueType = BuildGraph(dataType, types.Value, inputGraph, ancestors)
     };
 }
Example #3
0
        public void LoadField(string fieldName)
        {
            var firstVar = _evaluator.Pop();

            var vreg         = SetNewVReg();
            var computedType = firstVar.ComputedType();

            if (computedType.ClrType.IsByRef)
            {
                computedType = new TypeDescription(computedType.ClrType.GetElementType());
            }
            vreg.FixedType =
                new TypeDescription(
                    computedType.ClrType.LocateField(fieldName).FieldType);
            var assignment = new FieldGetter
            {
                AssignedTo = vreg,
                FieldName  = fieldName,
                Instance   = (LocalVariable)firstVar
            };

            AddOperation(OperationKind.GetField, assignment);
        }
Example #4
0
        /// <summary>
        ///     Helper function. Enumerate all the objects in the dump
        /// </summary>
        /// <param name="path">path of the dump</param>
        /// <param name="typeDescription"></param>
        /// <param name="shardIndex"></param>
        /// <returns></returns>
        public static IEnumerable <CachedObject> ObjectsInDump(string path, TypeDescription typeDescription,
                                                               int shardIndex = -1)
        {
            var fileMask = shardIndex != -1
                ? $"{typeDescription.FullTypeName}_shard{shardIndex:D4}*.txt"
                : $"{typeDescription.FullTypeName}_shard*.txt";

            var files = Directory.GetFiles(path, fileMask);

            foreach (var file in files)
            {
                var content = File.ReadAllText(file);

                var parts = content.Split(new[] { "\\-" }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(txt => txt.Trim()).Where(t => !string.IsNullOrWhiteSpace(t)).ToList();

                foreach (var part in parts)
                {
                    var cachedObject = CachedObject.PackJson(part, typeDescription);
                    yield return(cachedObject);
                }
            }
        }
        /// <summary>
        /// 将Map平台AppForm格式xml字符串转换为实体对象集合
        /// </summary>
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>xml结构为3层,第1层被忽略,第2层为数据库表名,第3层为字段名</description></item>
        /// <item><description>xml结构第2层节点必须包含keyname,keyvalue属性,keyvalue属性可以为空</description></item>
        /// <item><description>如果类,属性存在Alias别名标记,则按照别名赋值,否则按照类名,属性名赋值</description></item>
        /// </list>
        /// </remarks>
        /// <example>
        /// <para>下面的代码演示了从ConvertXmlToList()方法的用法</para>
        /// <code>
        /// <![CDATA[
        /// using System;
        /// using System.Collections.Generic;
        /// using System.Linq;
        /// using System.Text;
        ///
        /// //引入命名空间
        /// using Hack.Fast.Extensions;
        /// using Hack.Fast.Extensions.Xml;
        /// using Hack.Fast.Extensions.DAL;
        /// namespace Demo
        /// {
        ///     public class DemoBusiness
        ///     {
        ///			public void Demo(){
        ///				string xml = @"<UserData>
        ///							     <cb_Contract keyname="ContractGUID" keyvalue="">
        ///								   <ContractName>测试合同一</ContractName>
        ///								   <ContractCode>HT-001</ContractCode>
        ///								   ...其他值
        ///							     </cb_Contract>
        ///							     <cb_Contract keyname="ContractGUID" keyvalue="">
        ///								   <ContractName>测试合同二</ContractName>
        ///								   <ContractCode>HT-002</ContractCode>
        ///								   ...其他值
        ///							     </cb_Contract>
        ///							   </UserData>";
        ///
        ///				List<CbContract> contracts = XmlDataEntity.ConvertXmlToList<CbContract>(xml);
        ///
        ///				foreach(CbContract contract in contracts){
        ///					//主键为空,表示是新增
        ///					if (contract.ContractGUID == Guid.Empty){
        ///						contract.ContractGUID = Guid.NewGuid();
        ///						//插入到数据库
        ///						contract.Insert();
        ///					}
        ///					else{
        ///						//更新到数据库
        ///						contract.Update();
        ///					}
        ///				}
        ///			}
        ///     }
        /// }
        /// ]]>
        /// </code>
        /// </example>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="xml">xml字符串</param>
        /// <returns>实体对象集合</returns>
        public static List <T> ConvertXmlToList <T>(string xml) where T : BaseEntity, new()
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentNullException("xml");
            }

            Type            type        = typeof(T);
            TypeDescription description = TypeDescriptionCache.GetTypeDiscription(type);

            if (description.ExecuteFunc == null)
            {
                throw BaseEntity.GetNonStandardExecption(type);
            }

            try {
                return(description.ExecuteFunc(12, new object[] { xml }) as List <T>);
            }
            catch (System.Exception ex) {
                //这里不希望调用者看到代码生成器产生的代码结构,于是在这里抛出捕获到的异常
                throw ex;
            }
        }
Example #6
0
        /// <summary>
        ///     Initialize an empty datastore from a type description
        /// </summary>
        /// <param name="typeDescription"></param>
        /// <param name="evictionPolicy"></param>
        public DataStore(TypeDescription typeDescription, EvictionPolicy evictionPolicy)
        {
            TypeDescription = typeDescription ?? throw new ArgumentNullException(nameof(typeDescription));

            EvictionPolicy = evictionPolicy ?? throw new ArgumentNullException(nameof(evictionPolicy));

            //initialize the primary key dictionary
            _dataByPrimaryKey = new Dictionary <KeyValue, CachedObject>();


            //initialize the unique keys dictionaries (une by unique key)
            _dataByUniqueKey = new Dictionary <string, Dictionary <KeyValue, CachedObject> >();

            foreach (var keyInfo in typeDescription.UniqueKeyFields)
            {
                _dataByUniqueKey.Add(keyInfo.Name, new Dictionary <KeyValue, CachedObject>());
            }

            //initialize the indexes (one by index key)
            _dataByIndexKey = new Dictionary <string, IndexBase>();

            // scalar indexed fields
            foreach (var indexField in typeDescription.IndexFields)
            {
                var index = IndexFactory.CreateIndex(indexField);
                _dataByIndexKey.Add(indexField.Name, index);
            }


            // list indexed fields

            foreach (var indexField in typeDescription.ListFields)
            {
                var index = IndexFactory.CreateIndex(indexField);
                _dataByIndexKey.Add(indexField.Name, index);
            }
        }
Example #7
0
        internal static List <T> ToList <T>(DataTable table, TypeDescription description) where T : class, new()
        {
            Type type = typeof(T);

            Dictionary <string, DbMapInfo> dict = description.MemberDict;

            List <T> list = new List <T>();

            foreach (DataRow row in table.Rows)
            {
                T obj = Activator.CreateInstance(type) as T;
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    string    name = table.Columns[i].ColumnName;
                    DbMapInfo info;
                    if (dict.TryGetValue(name, out info))
                    {
                        object val = row[i];

                        if (val != null && DBNull.Value.Equals(val) == false)
                        {
                            if (info.AttrColumn != null && info.AttrColumn.TimeStamp)
                            {
                                info.PropertyInfo.FastSetValue(obj, val.ConvertToTimeStamp(info.PropertyInfo.PropertyType));
                            }
                            else
                            {
                                info.PropertyInfo.FastSetValue(obj, val.Convert(info.PropertyInfo.PropertyType));
                            }
                        }
                    }
                }
                list.Add(obj);
            }
            return(list);
        }
        public void testDecimalMerge()
        {
            TypeDescription schema = TypeDescription.createDecimal()
                                     .withPrecision(38).withScale(16);

            ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(schema);
            ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(schema);

            stats1.updateDecimal(HiveDecimal.create(10));
            stats1.updateDecimal(HiveDecimal.create(100));
            stats2.updateDecimal(HiveDecimal.create(1));
            stats2.updateDecimal(HiveDecimal.create(1000));
            stats1.merge(stats2);
            DecimalColumnStatistics typed = (DecimalColumnStatistics)stats1;

            Assert.Equal(1, typed.getMinimum().longValue());
            Assert.Equal(1000, typed.getMaximum().longValue());
            stats1.reset();
            stats1.updateDecimal(HiveDecimal.create(-10));
            stats1.updateDecimal(HiveDecimal.create(10000));
            stats1.merge(stats2);
            Assert.Equal(-10, typed.getMinimum().longValue());
            Assert.Equal(10000, typed.getMaximum().longValue());
        }
        private void AddPreDestroyMethodPoints(TypeDescription description, MethodInfo[] methods)
        {
            List <OrderedInjectionPoint> orderedInjectionPoints = new List <OrderedInjectionPoint> ();

            foreach (MethodInfo method in methods)
            {
                object[] injections = method.GetCustomAttributes(PRE_DESTROY_ATTRIBUTE_TYPE, true);
                if (injections.Length == 0)
                {
                    continue;
                }

                PreDestroy attr = injections [0] as PreDestroy;

                PreDestroyInjectionPoint injectionPoint = new PreDestroyInjectionPoint(attr.order, method);
                orderedInjectionPoints.Add(injectionPoint);
            }

            orderedInjectionPoints.Sort(SortInjectionPoints);
            foreach (PreDestroyInjectionPoint point in orderedInjectionPoints)
            {
                description.AddPreDestroyMethod(point);
            }
        }
        private static Expression ConvertToNullable(Expression notNullableExpression, TypeDescription typeDescription)
        {
            if (notNullableExpression == null)
            {
                throw new ArgumentNullException("notNullableExpression");
            }
            if (typeDescription != null && notNullableExpression.Type != typeDescription)
            {
                throw new ArgumentException("Wrong type description.", "typeDescription");
            }
            if (typeDescription == null)
            {
                typeDescription = TypeDescription.GetTypeDescription(notNullableExpression.Type);
            }

            if (typeDescription.CanBeNull == false)
            {
                return(Expression.Convert(notNullableExpression, typeDescription.GetNullableType()));
            }
            else
            {
                return(notNullableExpression);
            }
        }
        private void AddPostConstructMethodPoints(TypeDescription description, MethodInfo[] methods)
        {
            List <OrderedInjectionPoint> orderedInjectionPoints = new List <OrderedInjectionPoint> ();

            foreach (MethodInfo method in methods)
            {
                object[] injections = method.GetCustomAttributes(POST_CONSTRUCT_ATTRIBUTE_TYPE, true);
                if (injections.Length == 0)
                {
                    continue;
                }

                PostConstruct attr = injections [0] as PostConstruct;

                PostConstructInjectionPoint injectionPoint = new PostConstructInjectionPoint(attr.order, method);
                orderedInjectionPoints.Add(injectionPoint);
            }

            orderedInjectionPoints.Sort(SortInjectionPoints);
            foreach (OrderedInjectionPoint point in orderedInjectionPoints)
            {
                description.AddInjectionPoint(point);
            }
        }
Example #12
0
        private void BuildDictionary(
            DataType dataType,
            Type type,
            TypeDescription typeDescription,
            bool inputGraph,
            IEnumerable <Type> ancestors,
            MemberDescription memberDescription)
        {
            var types = type.GetGenericDictionaryTypes();

            dataType.IsDictionary    = true;
            dataType.Comments        = memberDescription.WhenNotNull(x => x.Comments).OtherwiseDefault() ?? dataType.Comments;
            dataType.DictionaryEntry = new DictionaryEntry
            {
                KeyName = memberDescription.WhenNotNull(x => x.DictionaryEntry.KeyName).OtherwiseDefault() ??
                          typeDescription.WhenNotNull(x => x.DictionaryEntry.KeyName).OtherwiseDefault(),
                KeyComments = memberDescription.WhenNotNull(x => x.DictionaryEntry.KeyComments).OtherwiseDefault() ??
                              typeDescription.WhenNotNull(x => x.DictionaryEntry.KeyComments).OtherwiseDefault(),
                KeyType       = BuildGraph(dataType, types.Key, inputGraph, ancestors),
                ValueComments = memberDescription.WhenNotNull(x => x.DictionaryEntry.ValueComments).OtherwiseDefault() ??
                                typeDescription.WhenNotNull(x => x.DictionaryEntry.ValueComments).OtherwiseDefault(),
                ValueType = BuildGraph(dataType, types.Value, inputGraph, ancestors)
            };
        }
Example #13
0
        public static void GetHashCode___Should_be_equal___When_objects_have_the_same_property_values()
        {
            // Arrange
            var typeDescription1A = new TypeDescription();
            var typeDescription1B = new TypeDescription {
                AssemblyQualifiedName = null, Name = null, Namespace = null
            };

            var typeDescription2A = A.Dummy <TypeDescription>();
            var typeDescription2B = new TypeDescription {
                AssemblyQualifiedName = typeDescription2A.AssemblyQualifiedName, Name = typeDescription2A.Name, Namespace = typeDescription2A.Namespace
            };

            // Act
            var hash1A = typeDescription1A.GetHashCode();
            var hash1B = typeDescription1B.GetHashCode();

            var hash2A = typeDescription2A.GetHashCode();
            var hash2B = typeDescription2B.GetHashCode();

            // Assert
            hash1A.Should().Be(hash1B);
            hash2A.Should().Be(hash2B);
        }
Example #14
0
        public void LoadStaticField(FieldInfo operand)
        {
            var vreg          = SetNewVReg();
            var fieldName     = operand.Name;
            var declaringType = operand.DeclaringType;

            if (declaringType == typeof(IntPtr) && fieldName == "Zero")
            {
                var voidPtr = new TypeDescription(typeof(IntPtr));
                vreg.FixedType = voidPtr;
                var nullPtrAssign = new Assignment
                {
                    AssignedTo = vreg,
                    Right      = new ConstValue(0)
                    {
                        FixedType = voidPtr
                    }
                };
                AddOperation(nullPtrAssign);
                return;
            }
            vreg.FixedType =
                new TypeDescription(declaringType.LocateField(fieldName, true).FieldType);
            var typeData   = new TypeDescription(declaringType);
            var assignment = new Assignment
            {
                AssignedTo = vreg,
                Right      = new StaticFieldGetter
                {
                    FieldName     = fieldName,
                    DeclaringType = typeData
                }
            };

            AddOperation(assignment);
        }
Example #15
0
 public static bool IsString(this TypeDescription typeDescription)
 {
     return(typeDescription.TypeString.StartsWith("string", StringComparison.CurrentCulture));
 }
Example #16
0
 public static bool IsUint(this TypeDescription typeDescription)
 {
     return(!typeDescription.IsDynamicArray() && !typeDescription.IsStaticArray() &&
            typeDescription.TypeString.StartsWith("uint", StringComparison.CurrentCulture));
 }
Example #17
0
        public static Tuple <Matrix, Vector, TypeDescription> Convert <T>(IEnumerable <T> examples, TypeDescription description = null)
        {
            var t = typeof(T);
            Dictionary <Object, int> labelsDictionary = new Dictionary <Object, int>();
            int labelsCounter = 0;
            Dictionary <int, Object> labelsDictionaryReversed = new Dictionary <int, Object>();

            // build up type descriptions along with dictionary
            if (description == null)
            {
                description = GetDescription(t)
                              .BuildDictionaries <T>(examples);
            }


            // number of examples
            var n = examples.Count();

            // this in essence counts all non-string properties singly
            // and adds the correspondin dictionary lengths for all
            // string features
            var d = description.Features
                    .Where(p => !(p is StringProperty)).Count() +
                    description.Features
                    .Where(p => p is StringProperty)
                    .Aggregate(0, (no, p) => no += (p as StringProperty).Dictionary.Length);

            var X = new double[n, d];
            var Y = new double[n];
            int i = 0;

            foreach (var example in examples)
            {
                int j = 0;
                foreach (var f in description.Features)
                {
                    var item = Conversion.Converter.GetItem <T>(example, f);

                    if (f is StringProperty)
                    {
                        var s = f as StringProperty;

                        var wc = GetWordCount((string)item, s);
                        for (int k = 0; k < wc.Length; k++)
                        {
                            X[i, j] = wc[k];
                            j++;
                        }
                    }
                    else
                    {
                        X[i, j] = Conversion.Converter.Convert(item);
                        j++;
                    }
                }

                // getting label
                var y = Conversion.Converter.GetItem <T>(example, description.Label);

                //building the labesl dictionary - because later we have to work with doubles/integers
                //which represent the labels
                if (!labelsDictionary.ContainsKey(y))
                {
                    labelsDictionary.Add(y, labelsCounter);
                    labelsDictionaryReversed.Add(labelsCounter, y);
                    labelsCounter++;
                }


                Y[i] = labelsDictionary[y];

                i++;
            }

            description.Label.Labels = labelsDictionaryReversed.Select(x => x.Value).ToArray();



            // create vectors for each example
            return(new Tuple <Matrix, Vector, TypeDescription>(
                       new Matrix(X),
                       new Vector(Y),
                       description));
        }
        private static bool TryConvertInPlace(ref Expression expression, TypeDescription targetType, out float quality)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            quality = TypeConversion.QUALITY_NO_CONVERSION;
            var targetTypeUnwrap = targetType.IsNullable ? targetType.UnderlyingType : targetType;
            // try to convert value of constant
            var constantExpression = default(ConstantExpression);

            if (TryExposeConstant(expression, out constantExpression) == false)
            {
                return(false);
            }

            var constantValue      = constantExpression.Value;
            var constantType       = TypeDescription.GetTypeDescription(constantExpression.Type);
            var constantTypeUnwrap = constantType.IsNullable ? constantType.UnderlyingType : constantType;

            if (constantValue == null && constantType.DefaultExpression != constantExpression && targetType.CanBeNull)
            {
                quality    = TypeConversion.QUALITY_SAME_TYPE;
                expression = Expression.Constant(null, targetType);
                return(true);
            }
            else if (constantValue == null)
            {
                return(false);
            }

            var constantTypeCode          = constantTypeUnwrap.TypeCode;
            var convertibleToExpectedType = default(bool);

            // ReSharper disable RedundantCast
            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (targetTypeUnwrap.TypeCode)
            {
            case TypeCode.Byte: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, byte.MinValue, byte.MaxValue); break;

            case TypeCode.SByte: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, sbyte.MinValue, (ulong)sbyte.MaxValue); break;

            case TypeCode.Char:
            case TypeCode.UInt16: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, ushort.MinValue, ushort.MaxValue); break;

            case TypeCode.Int16: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, short.MinValue, (ulong)short.MaxValue); break;

            case TypeCode.UInt32: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, uint.MinValue, uint.MaxValue); break;

            case TypeCode.Int32: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, int.MinValue, int.MaxValue); break;

            case TypeCode.UInt64: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, (long)ulong.MinValue, ulong.MaxValue); break;

            case TypeCode.Int64: convertibleToExpectedType = IsInRange(constantValue, constantTypeCode, long.MinValue, long.MaxValue); break;

            case TypeCode.Double:
            case TypeCode.Decimal:
            case TypeCode.Single: convertibleToExpectedType = NumberUtils.IsSignedInteger(constantTypeCode) || NumberUtils.IsUnsignedInteger(constantTypeCode); break;

            default: convertibleToExpectedType = false; break;
            }
            // ReSharper restore RedundantCast

            if (!convertibleToExpectedType)
            {
                return(false);
            }

            var newValue = Convert.ChangeType(constantValue, targetTypeUnwrap.TypeCode, Constants.DefaultFormatProvider);

            expression = Expression.Constant(newValue, targetType);
            quality    = TypeConversion.QUALITY_IN_PLACE_CONVERSION;          // converted in-place
            return(true);
        }
Example #19
0
 private static TypeDescription GetTypeDescription(Type sourceClass)
 {
     var propertySource = new ClassSource(sourceClass);
     var typeDesctiption = new TypeDescription(sourceClass.FullName, propertySource.GetProperties());
     return typeDesctiption;
 }
Example #20
0
        /// <summary>
        ///     Initialize for a specified cacheable data type
        /// </summary>
        /// <param name="type"></param>
        public QueryBuilder(Type type)
        {
            var clientTypeDescription = ClientSideTypeDescription.RegisterType(type);

            _typeDescription = clientTypeDescription.AsTypeDescription;
        }
Example #21
0
 public NullableSerializer(TypeDescription description)
 {
     this.typeDescription = description;
 }
        private static bool TryPromoteNumberBinaryOperation(ref Expression leftOperand, TypeDescription leftType, ref Expression rightOperand, TypeDescription rightType, ExpressionType type, out Expression operation)
        {
            if (leftOperand == null)
            {
                throw new ArgumentNullException("leftOperand");
            }
            if (leftType == null)
            {
                throw new ArgumentNullException("leftType");
            }
            if (rightOperand == null)
            {
                throw new ArgumentNullException("rightOperand");
            }
            if (rightType == null)
            {
                throw new ArgumentNullException("rightType");
            }

            operation = null;

            var leftTypeUnwrap         = leftType.IsNullable ? leftType.UnderlyingType : leftType;
            var rightTypeUnwrap        = rightType.IsNullable ? rightType.UnderlyingType : rightType;
            var leftTypeCode           = leftTypeUnwrap.TypeCode;
            var rightTypeCode          = rightTypeUnwrap.TypeCode;
            var promoteLeftToNullable  = leftType.IsNullable || rightType.IsNullable;
            var promoteRightToNullable = rightType.IsNullable || (type != ExpressionType.Coalesce && promoteLeftToNullable);

            if (leftTypeUnwrap == rightTypeUnwrap)
            {
                if (leftTypeCode >= TypeCode.SByte && leftTypeCode <= TypeCode.UInt16)
                {
                    // expand smaller integers to int32
                    leftOperand  = Expression.Convert(leftOperand, promoteLeftToNullable ? TypeDescription.Int32Type.GetNullableType() : TypeDescription.Int32Type);
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? TypeDescription.Int32Type.GetNullableType() : TypeDescription.Int32Type);
                    return(false);
                }
            }
            else if (leftTypeCode == TypeCode.Decimal || rightTypeCode == TypeCode.Decimal)
            {
                if (leftTypeCode == TypeCode.Double || leftTypeCode == TypeCode.Single || rightTypeCode == TypeCode.Double || rightTypeCode == TypeCode.Single)
                {
                    return(false);                    // will throw exception
                }
                if (leftTypeCode == TypeCode.Decimal)
                {
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(decimal?) : typeof(decimal));
                }
                else
                {
                    leftOperand = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(decimal?) : typeof(decimal));
                }
            }
            else if (leftTypeCode == TypeCode.Double || rightTypeCode == TypeCode.Double)
            {
                if (leftTypeCode == TypeCode.Double)
                {
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(double?) : typeof(double));
                }
                else
                {
                    leftOperand = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(double?) : typeof(double));
                }
            }
            else if (leftTypeCode == TypeCode.Single || rightTypeCode == TypeCode.Single)
            {
                if (leftTypeCode == TypeCode.Single)
                {
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(float?) : typeof(float));
                }
                else
                {
                    leftOperand = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(float?) : typeof(float));
                }
            }
            else if (leftTypeCode == TypeCode.UInt64)
            {
                var quality           = 0.0f;
                var rightOperandTmp   = rightOperand;
                var expectedRightType = promoteRightToNullable ? typeof(ulong?) : typeof(ulong);
                if (NumberUtils.IsSignedInteger(rightTypeCode) && TryMorphType(ref rightOperandTmp, expectedRightType, out quality) == false)
                {
                    return(false);                    // will throw exception
                }
                rightOperand = rightOperandTmp;
                rightOperand = rightOperand.Type != expectedRightType?Expression.Convert(rightOperand, expectedRightType) : rightOperand;
            }
            else if (rightTypeCode == TypeCode.UInt64)
            {
                var quality          = 0.0f;
                var leftOperandTmp   = leftOperand;
                var expectedLeftType = promoteLeftToNullable ? typeof(ulong?) : typeof(ulong);
                if (NumberUtils.IsSignedInteger(leftTypeCode) && TryMorphType(ref leftOperandTmp, expectedLeftType, out quality) == false)
                {
                    return(false);                    // will throw exception
                }
                leftOperand = leftOperandTmp;
                leftOperand = leftOperand.Type != expectedLeftType?Expression.Convert(leftOperand, expectedLeftType) : leftOperand;
            }
            else if (leftTypeCode == TypeCode.Int64 || rightTypeCode == TypeCode.Int64)
            {
                if (leftTypeCode == TypeCode.Int64)
                {
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(long?) : typeof(long));
                }
                else
                {
                    leftOperand = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(long?) : typeof(long));
                }
            }
            else if ((leftTypeCode == TypeCode.UInt32 && NumberUtils.IsSignedInteger(rightTypeCode)) ||
                     (rightTypeCode == TypeCode.UInt32 && NumberUtils.IsSignedInteger(leftTypeCode)))
            {
                rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(long?) : typeof(long));
                leftOperand  = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(long?) : typeof(long));
            }
            else if (leftTypeCode == TypeCode.UInt32 || rightTypeCode == TypeCode.UInt32)
            {
                if (leftTypeCode == TypeCode.UInt32)
                {
                    rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(uint?) : typeof(uint));
                }
                else
                {
                    leftOperand = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(uint?) : typeof(uint));
                }
            }
            else
            {
                rightOperand = Expression.Convert(rightOperand, promoteRightToNullable ? typeof(int?) : typeof(int));
                leftOperand  = Expression.Convert(leftOperand, promoteLeftToNullable ? typeof(int?) : typeof(int));
            }

            if (promoteLeftToNullable)
            {
                leftOperand = ConvertToNullable(leftOperand, null);
            }
            if (promoteRightToNullable)
            {
                rightOperand = ConvertToNullable(rightOperand, null);
            }

            return(false);
        }
Example #23
0
 public static TypeDescription CreateTypeDescription(global::System.Collections.ObjectModel.ObservableCollection<string> types, NumberQualifiers numberQualifiers)
 {
     TypeDescription typeDescription = new TypeDescription();
     if ((types == null))
     {
         throw new global::System.ArgumentNullException("types");
     }
     typeDescription.Types = types;
     if ((numberQualifiers == null))
     {
         throw new global::System.ArgumentNullException("numberQualifiers");
     }
     typeDescription.NumberQualifiers = numberQualifiers;
     return typeDescription;
 }
 private TypeExpression(NRefactory.AstType astType, TypeDescription typeDescription, IScope scope, INRefcatoryExpressionVisitor visitor)
     : base(scope, visitor) {
     _astType = astType;
     _typeDescription = typeDescription;
 }
Example #25
0
 private static TypeDescription GetTypeDescription(MethodInfo method)
 {
     var propertySource = new MethodSource(method);
     var typeDescription = new TypeDescription(method.DeclaringType.FullName + "+" + method.Name, propertySource.GetProperties());
     return typeDescription;
 }
Example #26
0
        // TODO: Provide a better way to check for array type
        public static bool IsStaticArray(this TypeDescription typeDescription)
        {
            var match = Regex.Match(typeDescription.TypeString, @".*\[\d+\]").Success;

            return(match);
        }
Example #27
0
 public void AddTypeDescription(Type type, TypeDescription description)
 {
     _typeDescriptor.AddDescription(type, description);
 }
Example #28
0
        private void CrawlRawObjectData(PackedMemorySnapshot packedMemorySnapshot, StartIndices startIndices, BytesAndOffset bytesAndOffset, TypeDescription typeDescription, bool useStaticFields, int indexOfFrom, List <Connection> out_connections, List <PackedManagedObject> out_managedObjects)
        {
            var fields = useStaticFields ? _staticFields[typeDescription.typeIndex] : _instanceFields[typeDescription.typeIndex];

            foreach (var field in fields)
            {
                var fieldType     = packedMemorySnapshot.typeDescriptions[field.typeIndex];
                var fieldLocation = bytesAndOffset.Add(field.offset - (useStaticFields ? 0 : _virtualMachineInformation.objectHeaderSize));

                if (fieldType.isValueType)
                {
                    CrawlRawObjectData(packedMemorySnapshot, startIndices, fieldLocation, fieldType, false, indexOfFrom, out_connections, out_managedObjects);

                    continue;
                }

                //temporary workaround for a bug in 5.3b4 and earlier where we would get literals returned as fields with offset 0. soon we'll be able to remove this code.
                bool gotException = false;
                try
                {
                    fieldLocation.ReadPointer();
                }
                catch (ArgumentException)
                {
                    UnityEngine.Debug.LogWarningFormat("Skipping field {0} on type {1}", field.name, typeDescription.name);
                    UnityEngine.Debug.LogWarningFormat("FieldType.name: {0}", fieldType.name);
                    gotException = true;
                }

                if (!gotException)
                {
                    CrawlPointer(packedMemorySnapshot, startIndices, fieldLocation.ReadPointer(), indexOfFrom, out_connections, out_managedObjects);
                }
            }
        }
        private static bool TryPromoteEnumBinaryOperation(ref Expression leftOperand, TypeDescription leftType, ref Expression rightOperand, TypeDescription rightType, ExpressionType type, out Expression operation)
        {
            if (leftOperand == null)
            {
                throw new ArgumentNullException("leftOperand");
            }
            if (leftType == null)
            {
                throw new ArgumentNullException("leftType");
            }
            if (rightOperand == null)
            {
                throw new ArgumentNullException("rightOperand");
            }
            if (rightType == null)
            {
                throw new ArgumentNullException("rightType");
            }

            operation = null;

            var leftTypeUnwrap    = leftType.IsNullable ? leftType.UnderlyingType : leftType;
            var rightTypeUnwrap   = rightType.IsNullable ? rightType.UnderlyingType : rightType;
            var promoteToNullable = leftType.IsNullable != rightType.IsNullable;

            // enum + number
            if (leftTypeUnwrap.IsEnum && rightTypeUnwrap.IsNumber && (type == ExpressionType.Add || type == ExpressionType.AddChecked || type == ExpressionType.Subtract || type == ExpressionType.SubtractChecked))
            {
                var integerType = leftTypeUnwrap.UnderlyingType;
                leftOperand = Expression.Convert(leftOperand, promoteToNullable ? integerType.GetNullableType() : integerType);
                if (promoteToNullable)
                {
                    rightOperand = ConvertToNullable(rightOperand, leftType);
                }

                switch (type)
                {
                case ExpressionType.Add: operation = Expression.Add(leftOperand, rightOperand); break;

                case ExpressionType.AddChecked: operation = Expression.AddChecked(leftOperand, rightOperand); break;

                case ExpressionType.Subtract: operation = Expression.Subtract(leftOperand, rightOperand); break;

                case ExpressionType.SubtractChecked: operation = Expression.SubtractChecked(leftOperand, rightOperand); break;

                default: throw new InvalidOperationException("Only subtraction and addition with numbers are promoted.");
                }

                operation = Expression.Convert(operation, promoteToNullable ? leftTypeUnwrap.GetNullableType() : leftTypeUnwrap);
                return(true);
            }
            // number + enum
            else if (rightTypeUnwrap.IsEnum && leftTypeUnwrap.IsNumber && (type == ExpressionType.Add || type == ExpressionType.AddChecked || type == ExpressionType.Subtract || type == ExpressionType.SubtractChecked))
            {
                var integerType = rightTypeUnwrap.UnderlyingType;
                rightOperand = Expression.ConvertChecked(rightOperand, promoteToNullable ? integerType.GetNullableType() : integerType);
                if (promoteToNullable)
                {
                    leftOperand = ConvertToNullable(leftOperand, rightType);
                }

                operation = Expression.MakeBinary(type, leftOperand, rightOperand);
                operation = Expression.Convert(operation, promoteToNullable ? rightTypeUnwrap.GetNullableType() : rightTypeUnwrap);
                return(true);
            }
            // null + nullable-enum
            else if (IsNull(leftOperand) && rightType.CanBeNull)
            {
                leftType    = rightType;
                leftOperand = rightType.DefaultExpression;
            }
            // nullable-enum + null
            else if (IsNull(rightOperand) && leftType.CanBeNull)
            {
                rightType    = leftType;
                rightOperand = leftType.DefaultExpression;
            }
            // enum OP enum
            else if (rightTypeUnwrap == leftTypeUnwrap && (type == ExpressionType.And || type == ExpressionType.Or || type == ExpressionType.ExclusiveOr ||
                                                           type == ExpressionType.GreaterThan || type == ExpressionType.GreaterThanOrEqual ||
                                                           type == ExpressionType.LessThan || type == ExpressionType.LessThanOrEqual))
            {
                var integerType = rightTypeUnwrap.UnderlyingType;
                rightOperand = Expression.ConvertChecked(rightOperand, promoteToNullable ? integerType.GetNullableType() : integerType);
                leftOperand  = Expression.Convert(leftOperand, promoteToNullable ? integerType.GetNullableType() : integerType);

                operation = Expression.MakeBinary(type, leftOperand, rightOperand);
                return(true);
            }
            // [not]nullable + [not]nullable
            else if (promoteToNullable)
            {
                leftOperand = ConvertToNullable(leftOperand, leftType);
                if (type != ExpressionType.Coalesce)
                {
                    rightOperand = ConvertToNullable(rightOperand, rightType);
                }
            }

            return(false);
        }
        public static IReadOnlyList <TypeDescription> HandlersFor(this IEnumerable <TypeDescription> types, TypeDescription type)
        {
            var eventHandlers  = types.EventHandlersFor(type);
            var commandHandler = types.CommandHandlerFor(type);

            if (commandHandler == null)
            {
                return(eventHandlers);
            }

            return(eventHandlers.Concat(new[] { commandHandler }).ToList());
        }
Example #31
0
 private static TypeDescription GetTypeDescription(string typeName, IDictionary<string, Type> properties)
 {
     var propertySource = new DictionarySource(properties);
     var typeDescription = new TypeDescription(typeName, propertySource.GetProperties());
     return typeDescription;
 }
Example #32
0
        private bool CanBeInstantiated(Type type)
        {
            TypeDescription description = _typeDescriptor.GetDescription(type);

            return(description.ctor != null);
        }
 public void SetUp()
 {
     generator = new PocoEmitGenertor();
     typeMapper = new DefaultTypeMapper(new Dictionary<ITypeDescription, IGeneratedType>());
     typeDescription = new TypeDescription("Sample.Class", new List<IPropertyDescription>()
         {
             new PropertyDescription("Number", typeof(int)),
             new PropertyDescription("Text", typeof(string))
         });
 }
        private static bool TryFindConversion(ref Expression expression, TypeDescription actualType, TypeDescription targetType, out float quality)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (actualType == null)
            {
                throw new ArgumentNullException("actualType");
            }
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            quality = TypeConversion.QUALITY_NO_CONVERSION;

            var actualTypeUnwrap = actualType.IsNullable ? actualType.UnderlyingType : actualType;
            var targetTypeUnwrap = targetType.IsNullable ? targetType.UnderlyingType : targetType;

            // converting null to nullable-or-reference
            if (targetType.CanBeNull && IsNull(expression))
            {
                expression = targetType.DefaultExpression;
                quality    = TypeConversion.QUALITY_SAME_TYPE;              // exact type (null)
                return(true);
            }

            // converting value to nullable value e.g. T to T?
            if (targetTypeUnwrap == actualType)
            {
                expression = Expression.Convert(expression, targetType);
                quality    = TypeConversion.QUALITY_IN_PLACE_CONVERSION;
                return(true);
            }

            var conversion = default(TypeConversion);

            if (TypeConversion.TryGetTypeConversion(actualTypeUnwrap, targetTypeUnwrap, out conversion) == false || conversion.Quality <= TypeConversion.QUALITY_NO_CONVERSION)
            {
                return(false);
            }

            // implicit convertion on expectedType
            if (conversion.Implicit != null && conversion.Implicit.TryMakeConversion(expression, out expression, checkedConversion: true))
            {
                quality = TypeConversion.QUALITY_IMPLICIT_CONVERSION;
                return(true);
            }

            expression = Expression.Convert(expression, targetType);
            quality    = conversion.Quality;
            return(true);
        }
Example #35
0
        /// <summary>
        /// Инициализирует объект типа Teleform.Reporting.Type.
        /// </summary>
        /// <param name="name">Имя типа.</param>
        /// <param name="accessibleFormats">Коллекция поддерживаемых форматов.</param>
        /// <exception cref="ArgumentNullException">Значения параметра name или accessibleFormats суть null.</exception>
        /// <exception cref="ArgumentException">Параметр accessibleFormats представляет пустую коллекцию.</exception>
        public Type(string name, string runtimeType, IEnumerable <Format> accessibleFormats, IEnumerable <Operator> accessibleOperators, IEnumerable <AggregateFunction> accessibleAggregateFunctions,
                    TypeDescription typeDescription, long minValue, long maxValue, string pattern, string patternDescription,
                    Format defaultFormat, int?length, int?viewLength)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name", "message is here");
            }

            if (runtimeType == null)
            {
                throw new ArgumentNullException("clrType", string.Format("Для типа {0} не заполнено поле runTimeTypeID в таблице [Typing].[BusinessType]", name));
            }

            if (accessibleFormats == null)
            {
                throw new ArgumentNullException("accessibleFormats",
                                                string.Format("Коллекция доступных форматов типа '{0}' не является допустимой.", name));
            }

            if (accessibleFormats.Count() == 0)
            {
                throw new ArgumentException(
                          string.Format("Коллекция доступных форматов типа '{0}' пуста.", name),
                          "accessibleFormats");
            }

            Description = typeDescription;

            //Numeric = Description.HasFlag(TypeDescription.Number);

            this.minValue = minValue;
            this.maxValue = maxValue;

            Pattern            = pattern;
            PatternDescription = patternDescription;
            Length             = length;
            ViewLength         = viewLength;

            Name        = name;
            RuntimeType = runtimeType;

            if (defaultFormat == null)
            {
                DefaultFormat = new Format(0, "General", "", "", null, "{0}", null);
            }
            else
            {
                DefaultFormat = defaultFormat;
            }

            this.accessibleFormats = new List <Format>(accessibleFormats);

            if (accessibleOperators != null)
            {
                this.accessibleOperators = accessibleOperators.OrderBy(o => o.Order).ToList();
            }
            else
            {
                this.accessibleOperators = Enumerable.Empty <Operator>();
            }

            if (accessibleAggregateFunctions != null)
            {
                this.accessibleAggregateFunctions = new List <AggregateFunction>(accessibleAggregateFunctions);
            }
            else
            {
                this.accessibleAggregateFunctions = Enumerable.Empty <AggregateFunction>();
            }

            if (!types.Keys.Contains(name))
            {
                types.Add(name, this);
            }
        }
 private void BuildArray(
     DataType dataType,
     Type type,
     TypeDescription typeDescription,
     bool inputGraph,
     IEnumerable<Type> ancestors,
     MemberDescription memberDescription)
 {
     dataType.IsArray = true;
     dataType.Comments = memberDescription.WhenNotNull(x => x.Comments).OtherwiseDefault() ?? dataType.Comments;
     var itemType = BuildGraph(dataType, type.GetListElementType(), inputGraph, ancestors);
     dataType.ArrayItem = new ArrayItem
     {
         Name = memberDescription.WhenNotNull(x => x.ArrayItem.Name).OtherwiseDefault() ??
                typeDescription.WhenNotNull(x => x.ArrayItem.Name).OtherwiseDefault() ?? itemType.Name,
         Comments = memberDescription.WhenNotNull(x => x.ArrayItem.Comments).OtherwiseDefault() ??
                    typeDescription.ArrayItem.WhenNotNull(x => x.Comments).OtherwiseDefault(),
         Type = itemType
     };
 }
Example #37
0
        private DataSet MainDataBind(TypeDescription td)
        {
            DataSet ds = null;
            //кэш для различных мероприятий
            if (Cache["results"+ddEventList.SelectedValue+"_"+ddStatType.SelectedValue] == null)
            {
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DBConn"]);
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;
                    cmd.CommandText = td.StProcName;

                    if (!td.IsExtended)
                    {
                        cmd.Parameters.Add("@AId_Competition",Convert.ToInt32(ddEventList.SelectedValue));
                    }
                    else
                    {
                        switch (td. ExtIdType)
                        {
                            case 1:
                                cmd.Parameters.Add("@AId_Competition",Convert.ToInt32(ddEventList.SelectedValue));
                                cmd.Parameters.Add("@AID_UserPosition",td.ExtId);
                                break;
                            case 2:
                                cmd.Parameters.Add("@AId_Competition",Convert.ToInt32(ddEventList.SelectedValue));
                                cmd.Parameters.Add("@AID_AntiUserPosition",td.ExtId);
                                break;
                            case 3:
                                cmd.Parameters.Add("@AId_Competition",Convert.ToInt32(ddEventList.SelectedValue));
                                cmd.Parameters.Add("@AID_GameType",td.ExtId);
                                break;
                        }
                    }

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    da.Fill(ds);

                    Cache.Insert("results"+ddEventList.SelectedValue+"_"+ddStatType.SelectedValue,
                        ds,
                        null,
                        System.Web.Caching.Cache.NoAbsoluteExpiration,
                        TimeSpan.FromMinutes(3));
                }
                catch (Exception exc)
                {
                    Response.Write(exc.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
            else
            {
                ds = (DataSet)Cache["results"+ddEventList.SelectedValue+"_"+ddStatType.SelectedValue];
            }

            return ds;
        }
        public static string GetArgumentsAsTextWithEscaping(this MethodInterpreter interpreter, ClosureEntities closureEntities)
        {
            var method         = interpreter.Method;
            var parameterInfos = method.GetParameters();
            var escapingBools  = method.BuildEscapingBools(closureEntities);
            var sb             = new StringBuilder();
            var index          = 0;
            var analyze        = interpreter.AnalyzeProperties;

            if (!method.IsStatic)
            {
                var parameterData = analyze.GetVariableData(new LocalVariable
                {
                    VarName = "_this",
                    Kind    = VariableKind.Argument,
                    Id      = 0
                });
                if (parameterData != EscapingMode.Unused)
                {
                    TypeDescription argumentTypeDescription = UsedTypeList.Set(method.DeclaringType.GetReversedMappedType(closureEntities) ?? method.DeclaringType.GetMappedType(closureEntities), closureEntities);
                    var             thisText = String.Format("const {0}& _this", argumentTypeDescription.GetClrType(closureEntities).ToCppName()); // all "_this" should be smart pointers
                    //For some reason at three Virtual Test 4 fails this, is something wrong with the escaping ?
//                    if ((!escapingBools[0]))
//                    {
//                        thisText = String.Format("{0} _this",
//                            argumentTypeDescription.ClrType.ToCppName(true, EscapingMode.Pointer));
//                    }
                    sb.Append(thisText);
                    index++;
                }
            }
            var isFirst = index == 0;

            for (index = 0; index < parameterInfos.Length; index++)
            {
                var parameterInfo = parameterInfos[index];
                var parameterData = analyze.GetVariableData(new LocalVariable()
                {
                    Kind    = VariableKind.Argument,
                    VarName = parameterInfo.Name
                });
                if (parameterData == EscapingMode.Unused)
                {
                    continue;
                }

                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    sb.Append(", ");
                }
                var isSmartPtr              = escapingBools[index];
                var nonEscapingMode         = isSmartPtr ? EscapingMode.Smart : EscapingMode.Pointer;
                var parameterType           = parameterInfo.ParameterType.GetReversedMappedType(closureEntities);
                var argumentTypeDescription = UsedTypeList.Set(parameterType, closureEntities);
                sb.AppendFormat("{0} {1}",
                                argumentTypeDescription.GetClrType(closureEntities).ToCppName(nonEscapingMode, isPInvoke: method.IsPinvoke()), //Handle byref
                                parameterInfo.Name);
            }
            return(sb.ToString());
        }
 /// <summary>
 /// Returns the types with a method handling <paramref name="type"/> as an event.
 /// </summary>
 public static IReadOnlyList <TypeDescription> EventHandlersFor(this IEnumerable <TypeDescription> types, TypeDescription type)
 {
     return(types
            .Where(t => t.IsClass() && t.ImplementsType("Pitstop.Infrastructure.Messaging.IMessageHandlerCallback"))
            .Where(t => t.Methods.Any(m => m.Name == "HandleAsync" && m.Parameters.Any(p => p.Type.EndsWith("." + type.Name, StringComparison.Ordinal))))
            .ToList());
 }
Example #40
0
 /// <summary>
 ///     Create from a <see cref="TypeDescription" />
 /// </summary>
 /// <param name="typeDescription"></param>
 public QueryBuilder(TypeDescription typeDescription)
 {
     _typeDescription = typeDescription ?? throw new ArgumentNullException(nameof(typeDescription));
 }
        public static IReadOnlyList <TypeDescription> GetSourceCommands(this IEnumerable <TypeDescription> types, TypeDescription type)
        {
            var commands =
                from t in types
                from m in t.Methods
                from s in m.Statements
                from i in FlattenStatements(s).OfType <InvocationDescription>()
                where i.ContainingType.EndsWith(type.Name) && i.Name == type.Name
                select types.First(i.ContainingType);

            return(commands.ToList());
        }