예제 #1
0
 public void Visit(IFieldDescriptor fieldDescriptor)
 {
     if (fieldDescriptor is XMLFieldDescriptor)
     {
         foreach (ICustomAction x in fieldDescriptor.CustomActions)
         {
             if (x is XMLCustomAction)
             {
                 ((XMLCustomAction)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
             }
         }
         foreach (IInvokedMethod x in fieldDescriptor.InvokedMethods)
         {
             if (x is XMLInvokedMethod)
             {
                 ((XMLInvokedMethod)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
             }
         }
         foreach (IModifiedProperty x in fieldDescriptor.ModifiedProperties)
         {
             if (x is XMLModifiedProperty)
             {
                 ((XMLModifiedProperty)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
             }
         }
     }
 }
예제 #2
0
        private static long Hash(JToken content, IFieldDescriptor field_desc)
        {
            //TODO conflict resolve
            string str;
            string hashimport = field_desc.GetAttributeValue(Consts.c_KW_HashImport);
            string cellidkey  = field_desc.GetAttributeValue(Consts.c_KW_CellIdKey);

            if ((cellidkey != null && field_desc.Type == Consts.c_Type_Guid) ||
                (hashimport == Consts.c_KW_Guid))
            {
                str = ((Guid)content).ToString();
            }
            else if ((cellidkey != null && field_desc.Type == Consts.c_Type_DateTime) ||
                     (hashimport == Consts.c_KW_DateTime))
            {
                str = ((DateTime)content).ToString("s");//XXX issue #226
            }
            else
            {
                str = content.ToString();
            }
            //TODO what if we're hashing a whole struct to cell id? how do we normalize?

            return(Trinity.Core.Lib.HashHelper.HashString2Int64(str));
        }
예제 #3
0
        public byte[] ToMsg()
        {
            try
            {
                var msg = new byte[PackedLength];
                lenFormatter.Pack(msg, PackedLength - 4, 0);

                msg[4] = (byte)0xf0;
                msg[5] = 0x00;
                msg[6] = 0x21;
                int offset = 7;

                byte[] bitmap = GenerateBitmap();

                Array.Copy(bitmap, 0, msg, offset, bitmap.Length);
                offset += bitmap.Length;

                foreach (var kvp in this)
                {
                    IFieldDescriptor fieldDesc = GetFieldDescriptor(kvp.Key);
                    byte[]           fieldData = fieldDesc.Pack((int)kvp.Key, kvp.Value);
                    Array.Copy(fieldData, 0, msg, offset, fieldData.Length);
                    offset += fieldData.Length;
                }

                return(msg);
            }
            catch (FieldFormatException ffe)
            {
                throw new FieldFormatException("48.", ffe.FieldNumber, ffe.Message);
            }
        }
예제 #4
0
        public void AddColumn(IDataContext db, IFieldDescriptor field)
        {
            if (db == null)
            {
                throw new ArgumentNullException("session");
            }

            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            var sqlType = MssqlSqlTypeConverter.GetSqlType(field);
            var sql     = new SqlString("alter table [",
                                        this.Name,
                                        "] add [",
                                        field.Name, "] ", sqlType);

            db.Execute(sql);

            //TODO
            //this.SetColumnComment(db, field);

            if (field.IsUnique)
            {
                this.AddUniqueConstraint(db, field.Name);
            }
        }
예제 #5
0
        /// <inheritdoc />
        public void SetFieldValue(IFieldDescriptor field, IConcreteValue value)
        {
            var typeMemoryLayout  = _memoryAllocator.GetTypeMemoryLayout(field.DeclaringType);
            var fieldMemoryLayout = typeMemoryLayout[field.Resolve()];

            this.WriteStruct((int)fieldMemoryLayout.Offset, _memoryAllocator, fieldMemoryLayout.ContentsLayout, value);
        }
예제 #6
0
        // -------------------------
        // Implementation rationale
        // -------------------------
        //
        // Objects in .NET are implemented as a single memory region containing all fields and are referenced by
        // a single pointer to the first byte of the object. Getting and setting field values of an object is done
        // by reading from this base pointer + the field offset. In C this would be something like the following:
        //
        //    *(MyFieldType*) (ptr_to_TypeA_object + offset_MyField);
        //
        // or using pointer notation:
        //
        //    ptr_to_TypeA_object->MyField
        //
        // Although C# represents itself as a type-safe language, CIL is not. As a result, it is possible for a
        // ldfld instruction to perform type confusion, and read "non-existing" fields from a type, by pushing
        // an object reference of type A, and referencing a field from another type B in the  operand of the
        // ldfld instruction. For example, the following CIL snippet runs fine:
        //
        //     newobj     void TypeA::.ctor()
        //     ldfld      MyFieldType TypeB::MyField
        //
        // The runtime (tested on Mono and .NET Core) will reinterpret the pushed object as TypeB, even though it is
        // a pointer to TypeA, and use the field offset as if it was actually an instance of TypeB:
        //
        //    ((TypeB*) ptr_to_TypeA_object)->MyField
        //
        // which is equivalent to:
        //
        //    *(MyFieldType*) (ptr_to_TypeA_object + offset_MyField))
        //
        // For this reason, we do not store the memory type layout of the current object within this class, but rather
        // query the memory allocator that was used to create this LLE object for the memory layout of the field's
        // declaring type.

        /// <inheritdoc />
        public IConcreteValue GetFieldValue(IFieldDescriptor field)
        {
            var typeMemoryLayout  = _memoryAllocator.GetTypeMemoryLayout(field.DeclaringType);
            var fieldMemoryLayout = typeMemoryLayout[field.Resolve()];

            return(this.ReadStruct((int)fieldMemoryLayout.Offset, _memoryAllocator, fieldMemoryLayout.ContentsLayout));
        }
        private async Task WriteObjectPropertyDeserializationAsync(
            CodeWriter writer,
            IResultParserTypeDescriptor possibleType,
            string jsonElement,
            ITypeLookup typeLookup)
        {
            for (int i = 0; i < possibleType.ResultDescriptor.Fields.Count; i++)
            {
                IFieldDescriptor fieldDescriptor = possibleType.ResultDescriptor.Fields[i];

                await writer.WriteIndentAsync().ConfigureAwait(false);

                if (fieldDescriptor.Type.NamedType().IsLeafType())
                {
                    ITypeInfo typeInfo = typeLookup.GetTypeInfo(
                        fieldDescriptor.Type,
                        true);

                    string deserializeMethod =
                        SerializerNameUtils.CreateDeserializerName(
                            fieldDescriptor.Type);

                    await writer.WriteAsync(deserializeMethod).ConfigureAwait(false);

                    await writer.WriteAsync('(').ConfigureAwait(false);

                    await writer.WriteAsync(jsonElement).ConfigureAwait(false);

                    await writer.WriteAsync(", \"").ConfigureAwait(false);

                    await writer.WriteAsync(fieldDescriptor.ResponseName).ConfigureAwait(false);

                    await writer.WriteAsync("\")").ConfigureAwait(false);
                }
                else
                {
                    await writer.WriteAsync("Parse").ConfigureAwait(false);

                    await writer.WriteAsync(GetPathName(fieldDescriptor.Path))
                    .ConfigureAwait(false);

                    await writer.WriteAsync('(').ConfigureAwait(false);

                    await writer.WriteAsync(jsonElement).ConfigureAwait(false);

                    await writer.WriteAsync(", \"").ConfigureAwait(false);

                    await writer.WriteAsync(fieldDescriptor.ResponseName).ConfigureAwait(false);

                    await writer.WriteAsync("\")").ConfigureAwait(false);
                }

                if (i < possibleType.ResultDescriptor.Fields.Count - 1)
                {
                    await writer.WriteAsync(',').ConfigureAwait(false);
                }

                await writer.WriteLineAsync().ConfigureAwait(false);
            }
        }
예제 #8
0
        public static string GetSqlType(IFieldDescriptor field)
        {
            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            var func = mapping[field.Type];

            var sb = new StringBuilder();

            sb.Append(func(field));
            if (field.IsRequired)
            {
                sb.Append(' ');
                sb.Append("not null");
            }

            if (field.IsUnique)
            {
                sb.Append(' ');
                sb.Append("unique");
            }
            return(sb.ToString());
        }
예제 #9
0
        private void Verify(IFieldDescriptor field, ICliValue expectedValue)
        {
            var result = Dispatcher.Execute(ExecutionContext, new CilInstruction(CilOpCodes.Ldsfld, field));

            Assert.True(result.IsSuccess);
            Assert.Equal(expectedValue, ExecutionContext.ProgramState.Stack.Top);
        }
예제 #10
0
 public static IFieldDescriptor Resolver <TResult>(
     this IFieldDescriptor descriptor,
     Func <Task <TResult> > fieldResolver)
 {
     return(descriptor.Type(typeof(TResult), false)
            .Resolver((ctx, ct) => fieldResolver()));
 }
예제 #11
0
        private void SetAndVerify(IFieldDescriptor field, IConcreteValue fieldValue, ICliValue expectedValue)
        {
            var environment = ExecutionContext.GetService <ICilRuntimeEnvironment>();

            environment.StaticFieldFactory.Get(field).Value = fieldValue;
            Verify(field, expectedValue);
        }
예제 #12
0
        private IConcreteValue GetInitialFieldValue(IFieldDescriptor field)
        {
            var definition = field.Resolve();

            if (definition != null)
            {
                // Check if the field has an initial value through a Constant row.
                var constant = definition.Constant;
                if (constant?.Value != null)
                {
                    return(ObjectToCtsValue(
                               constant.Value.Data,
                               definition.Module.CorLibTypeFactory.FromElementType(constant.Type)));
                }

                // Check if the field has an initial value through a field RVA row.
                if (definition.HasFieldRva && definition.FieldRva != null &&
                    definition.FieldRva is IReadableSegment readableSegment)
                {
                    return(ObjectToCtsValue(
                               readableSegment.ToArray(),
                               field.Signature.FieldType));
                }
            }

            return(_valueFactory.CreateValue(field.Signature.FieldType, false));
        }
예제 #13
0
        public void AddColumn(IDataContext db, IFieldDescriptor field)
        {
            if (db == null)
            {
                throw new ArgumentNullException("session");
            }

            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            var sqlType = PgSqlTypeConverter.GetSqlType(field);
            var sql     = String.Format(CultureInfo.InvariantCulture,
                                        @"alter table ""{0}"" add column ""{1}"" {2}",
                                        this.Name, field.Name, sqlType);

            db.Execute(SqlString.Parse(sql));

            this.SetColumnComment(db, field);

            if (field.IsUnique)
            {
                this.AddUniqueConstraint(db, field.Name);
            }
        }
예제 #14
0
 public static IFieldDescriptor Resolver <TResult>(
     this IFieldDescriptor descriptor,
     Func <Task <TResult> > fieldResolver)
 {
     return(descriptor.Resolver((ctx, ct) => fieldResolver(),
                                typeof(NativeType <TResult>)));
 }
예제 #15
0
 public static IFieldDescriptor Resolver <TResult>(
     this IFieldDescriptor descriptor,
     Func <IResolverContext, TResult> fieldResolver)
 {
     return(descriptor
            .Type <NativeType <TResult> >()
            .Resolver((ctx, ct) => fieldResolver(ctx),
                      typeof(NativeType <TResult>)));
 }
 /// <inheritdoc />
 public int GetHashCode(IFieldDescriptor obj)
 {
     unchecked
     {
         int hashCode = obj.Name == null ? 0 : obj.Name.GetHashCode();
         hashCode = (hashCode * 397) ^ GetHashCode(obj.DeclaringType);
         hashCode = (hashCode * 397) ^ GetHashCode(obj.Signature);
         return(hashCode);
     }
 }
예제 #17
0
        private static FieldInfo GetFieldInfo(IFieldDescriptor fieldDescriptor, IClassConfiguration parent)
        {
            Type      t = Type.GetType(parent.ClassName);
            FieldInfo f = t.GetField(fieldDescriptor.FieldName,
                                     BindingFlags.NonPublic |
                                     BindingFlags.Public |
                                     BindingFlags.Instance);

            return(f);
        }
예제 #18
0
 private void SetColumnComment(IDataContext db, IFieldDescriptor field)
 {
     if (!string.IsNullOrEmpty(field.Label))
     {
         //添加注释
         var commentSql = String.Format(CultureInfo.InvariantCulture,
                                        @"comment on column ""{0}"".""{1}"" is '{2}'",
                                        this.Name, field.Name, field.Label.SqlEscape());
         db.Execute(SqlString.Parse(commentSql));
     }
 }
예제 #19
0
 /// <summary>
 /// Creates a new instance of the <see cref="StaticField"/> class.
 /// </summary>
 /// <param name="field">The field to encapsulate </param>
 public StaticField(IFieldDescriptor field)
 {
     if (field == null)
     {
         throw new ArgumentNullException(nameof(field));
     }
     if (field.Signature.HasThis)
     {
         throw new ArgumentException("Field must be static.");
     }
     Field = field;
 }
        /// <summary>
        /// Verifies and inserts an instruction into the collection that references a field.
        /// </summary>
        /// <param name="index">The zero-based index at which the instruction should be inserted at.</param>
        /// <param name="code">The field opcode.</param>
        /// <param name="field">The field referenced by the instruction.</param>
        /// <returns>The created instruction.</returns>
        /// <exception cref="InvalidCilInstructionException">
        /// Occurs when the provided operation is not a field opcode.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Occurs when <paramref name="field"/> is null.
        /// </exception>
        public CilInstruction Insert(int index, CilOpCode code, IFieldDescriptor field)
        {
            if (code.OperandType != CilOperandType.InlineField && code.OperandType != CilOperandType.InlineTok)
            {
                throw new InvalidCilInstructionException(code);
            }

            if (field is null)
            {
                throw new ArgumentNullException(nameof(field));
            }

            return(InsertAndReturn(index, code, field));
        }
예제 #21
0
 private void SetColumnComment(IDataContext db, IFieldDescriptor field)
 {
     if (!string.IsNullOrEmpty(field.Label))
     {
         //添加注释
         var commentSql = new SqlString(
             "comment on column [",
             this.Name,
             "].[",
             field.Name,
             "] is '", field.Label.SqlEscape(), "'");
         db.Execute(commentSql);
     }
 }
예제 #22
0
        public void Visit(IFieldDescriptor fieldDescriptor)
        {
            if (fieldDescriptor.FieldName == null)
            {
                throw new ContextConfigurationException("IFieldDescriptor without definition of 'FieldName' found");
            }

            IClassConfiguration parent = fieldDescriptor.ParentClassConfiguration;
            FieldInfo           f      = GetFieldInfo(fieldDescriptor, parent);

            if (f == null)
            {
                throw new ContextConfigurationException("Field '" + fieldDescriptor.FieldName + "' not found in class '" + parent.ClassName + "'");
            }
        }
        /// <inheritdoc />
        public bool Equals(IFieldDescriptor x, IFieldDescriptor y)
        {
            if (ReferenceEquals(x, y))
            {
                return(true);
            }
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
            {
                return(false);
            }

            return(x.Name == y.Name &&
                   Equals(x.DeclaringType, y.DeclaringType) &&
                   Equals(x.Signature, y.Signature));
        }
예제 #24
0
        public static StructField ConvertFromFieldDescriptor(IFieldDescriptor fd)
        {
            if (fd == null)
            {
                return(null);
            }

            var type = DataType.ConvertFromType(fd.Type);

            return(new StructField
            {
                Name = fd.Name,
                Type = type,
                Nullable = fd.Optional || (type is NullableValueType)
            });
        }
예제 #25
0
        private void DeclareFields(
            IObjectTypeDescriptor typeDescriptor,
            string typeName,
            IReadOnlyCollection <FieldDefinitionNode> fieldDefinitions)
        {
            foreach (FieldDefinitionNode fieldDefinition in fieldDefinitions)
            {
                IFieldDescriptor fieldDescriptor = typeDescriptor
                                                   .Field(fieldDefinition.Name.Value)
                                                   .Description(fieldDefinition.Description?.Value)
                                                   .Type(fieldDefinition.Type)
                                                   .SyntaxNode(fieldDefinition);

                DeclareFieldArguments(fieldDescriptor, fieldDefinition);
            }
        }
예제 #26
0
 private void DeclareFieldArguments(
     IFieldDescriptor fieldDescriptor,
     FieldDefinitionNode fieldDefinition)
 {
     foreach (InputValueDefinitionNode inputFieldDefinition in
              fieldDefinition.Arguments)
     {
         fieldDescriptor.Argument(inputFieldDefinition.Name.Value,
                                  a =>
         {
             a.Description(inputFieldDefinition.Description?.Value)
             .Type(inputFieldDefinition.Type)
             .DefaultValue(inputFieldDefinition.DefaultValue)
             .SyntaxNode(inputFieldDefinition);
         });
     }
 }
예제 #27
0
        public void Visit(IModifiedProperty modifiedProperty)
        {
            if (modifiedProperty.PropertyName == null)
            {
                throw new ContextConfigurationException("IModifiedProperty without definition of 'PropertyName' found");
            }
            IFieldDescriptor p  = modifiedProperty.ParentFieldDescriptor;
            FieldInfo        f  = GetFieldInfo(p, p.ParentClassConfiguration);
            Type             t  = f.FieldType;
            PropertyInfo     pi = t.GetProperty(modifiedProperty.PropertyName,
                                                BindingFlags.NonPublic |
                                                BindingFlags.Public |
                                                BindingFlags.Instance);

            if (pi == null)
            {
                throw new ContextConfigurationException("Fieldtype of field '" + p.FieldName + "' in class '" + p.ParentClassConfiguration.ClassName + "' does not define property '" + modifiedProperty.PropertyName + "'");
            }
        }
예제 #28
0
        public ICell ImportEntity(string type, string content, long?parent_id = null)
        {
            var fields = parser.CsvSplit(content);

            if (fields.Count != m_fieldNames.Count)
            {
                throw new ImporterException("Invalid record. The number of a field ({0}) must equal to {1}: {2}",
                                            fields.Count, m_fieldNames.Count, content);
            }

            var jsonObj                = new JObject();
            var fieldDescDict          = GetFieldDescriptors(type);
            IFieldDescriptor fieldDesc = null;

            for (int colIndex = 0; colIndex < m_fieldNames.Count; colIndex++)
            {
                var    fieldName  = m_fieldNames[colIndex];
                string fieldValue = fields[colIndex];

                if (fieldValue == null || !fieldDescDict.TryGetValue(fieldName, out fieldDesc))
                {
                    // Ignore this field if it's value is null or could not find the descriptor.
                    continue;
                }

                string csvArraySplitBy = fieldDesc.GetAttributeValue(Consts.c_KW_CsvArray);
                if (fieldValue == null || csvArraySplitBy == null)
                {
                    jsonObj[fieldName] = fieldValue;
                }
                else
                {
                    var elements  = fieldValue.Split(csvArraySplitBy.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    var jsonArray = new JArray();
                    foreach (var elem in elements)
                    {
                        jsonArray.Add(elem);
                    }
                    jsonObj[fieldName] = jsonArray;
                }
            }
            return(m_jsonImporter.ImportEntity(type, jsonObj.ToString(), parent_id));
        }
예제 #29
0
        /// <summary>
        /// Gets or creates an instance of a static field.
        /// </summary>
        /// <param name="field">The field to encapsulate.</param>
        /// <returns>The static field.</returns>
        public StaticField Get(IFieldDescriptor field)
        {
            if (field is null)
            {
                throw new ArgumentNullException(nameof(field));
            }
            if (field.Signature.HasThis)
            {
                throw new ArgumentException("Field has the HasThis flag set in the field signature.");
            }

            StaticField staticField;

            while (!_cache.TryGetValue(field, out staticField))
            {
                _cache.TryAdd(field, new StaticField(field));
            }
            return(staticField);
        }
예제 #30
0
        public void Visit(IInvokedMethod invokedMethod)
        {
            if (invokedMethod.MethodName == null)
            {
                throw new ContextConfigurationException("InvokedMethod without definition of 'MethodName' found");
            }
            IFieldDescriptor p = invokedMethod.ParentFieldDescriptor;
            FieldInfo        f = GetFieldInfo(p, p.ParentClassConfiguration);
            Type             t = f.FieldType;
            MethodInfo       m = t.GetMethod(invokedMethod.MethodName,
                                             BindingFlags.NonPublic |
                                             BindingFlags.Public |
                                             BindingFlags.Instance);

            if (m == null)
            {
                throw new ContextConfigurationException("Fieldtype of field '" + p.FieldName + "' in class '" + p.ParentClassConfiguration.ClassName + "' does not define method '" + invokedMethod.MethodName + "'");
            }
        }
        public void Visit(IFieldDescriptor fieldDescriptor)
        {
            if(fieldDescriptor.FieldName == null)
            {
                throw new ContextConfigurationException("IFieldDescriptor without definition of 'FieldName' found");
            }

            IClassConfiguration parent = fieldDescriptor.ParentClassConfiguration;
            FieldInfo f = GetFieldInfo(fieldDescriptor, parent);
            if (f == null)
            {
                throw new ContextConfigurationException("Field '" + fieldDescriptor.FieldName + "' not found in class '" + parent.ClassName+"'");
            }
        }
예제 #32
0
 public Int32 CompareTo(IFieldDescriptor fieldDescriptor)
 {
     return fieldDescriptor is FieldDescriptor
                ? String.Compare(Id, fieldDescriptor.Id, StringComparison.Ordinal)
                : -1;
 }
        public void Visit(IFieldDescriptor fieldDescriptor)
        {
            if (fieldDescriptor is XMLFieldDescriptor)
            {
                foreach (ICustomAction x in fieldDescriptor.CustomActions)
                {
                    if (x is XMLCustomAction)
                    {
                        ((XMLCustomAction)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
                    }
                }
                foreach (IInvokedMethod x in fieldDescriptor.InvokedMethods)
                {
                    if (x is XMLInvokedMethod)
                    {
                        ((XMLInvokedMethod)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
                    }
                }
                foreach (IModifiedProperty x in fieldDescriptor.ModifiedProperties)
                {
                    if (x is XMLModifiedProperty)
                    {
                        ((XMLModifiedProperty)x).ParentFieldDescriptor = (XMLFieldDescriptor)fieldDescriptor;
                    }
                }

            }
        }
 private static FieldInfo GetFieldInfo(IFieldDescriptor fieldDescriptor, IClassConfiguration parent)
 {
     Type t = Type.GetType(parent.ClassName);
     FieldInfo f = t.GetField(fieldDescriptor.FieldName,
         BindingFlags.NonPublic |
         BindingFlags.Public |
         BindingFlags.Instance);
     return f;
 }