Example #1
0
        /// <summary>
        /// Adds a new Field to this collection.
        /// </summary>
        /// <param name="name">Name of the field to add</param>
        /// <param name="dataType">Data type of the field to add</param>
        /// <param name="size">Size of the field to add</param>
        /// <param name="fieldAttributes">Attributes on the field to add</param>
        public void Append(string name, DataType dataType, long? size, FieldAttribute? fieldAttributes)
        {
            List<object> parms = new List<object>();
            parms.Add(name);
            parms.Add(dataType);
            parms.Add(size);
            parms.Add(fieldAttributes);

            InternalObject.GetType().InvokeMember("Append", System.Reflection.BindingFlags.InvokeMethod, null, InternalObject, parms.ToArray());
        }
        internal HarshFieldMetadata(PropertyInfo definitionProperty, FieldAttribute fieldAttribute)
        {
            if (definitionProperty == null)
            {
                throw Logger.Fatal.ArgumentNull("definitionProperty");
            }

            if (fieldAttribute == null)
            {
                throw Logger.Fatal.ArgumentNull("fieldAttribute");
            }

            InitializeFromDefinition(definitionProperty, fieldAttribute);
        }
Example #3
0
        private CodeAttributeArgument[] GenerateFieldArguments(FieldAttribute field, string nameAlias)
        {
            var attrList = new List <CodeAttributeArgument>();

            // TODO add precision, etc.

            if (field.IsPrimaryKey)
            {
                attrList.Add(new CodeAttributeArgument(new CodeSnippetExpression("IsPrimaryKey=true")));
            }

            if (field.SearchOrder != FieldSearchOrder.NotSearchable)
            {
                attrList.Add(new CodeAttributeArgument(new CodeSnippetExpression("SearchOrder=FieldSearchOrder." + field.SearchOrder.ToString())));
            }

            if (!string.IsNullOrEmpty(nameAlias))
            {
                attrList.Add(new CodeAttributeArgument(new CodeSnippetExpression(string.Format("FieldName=\"{0}\"", nameAlias))));
            }

            return(attrList.ToArray());
        }
Example #4
0
 void CommonString(Expression <Func <TEntity, string> > p, Func <string, bool> verify, Func <string, string> geterror)
 {
     if (p.Body is MemberExpression)
     {
         MemberExpression me        = p.Body as MemberExpression;
         PropertyInfo     prop      = me.Member as PropertyInfo;
         string           str       = prop.GetValue(_entity)?.ToString().Trim();
         FieldAttribute   f         = prop.GetAttribute <FieldAttribute>();
         string           fieldname = me.Member.Name;
         if (f != null)
         {
             fieldname = f.Fieldname;
         }
         if (!verify(str))
         {
             SetError(geterror(fieldname));
         }
     }
     else
     {
         throw new Exception("此校验只对字段属性生效");
     }
 }
Example #5
0
        public Field(IEntityInfo entity, PropertyInfo prop, FieldAttribute fieldAttribute)
        {
            Entity       = entity;
            PropertyInfo = prop;
            if (fieldAttribute != null)
            {
                RequireUniqueValue = fieldAttribute.RequireUniqueValue;
                SearchOrder        = fieldAttribute.SearchOrder;
                FieldName          = fieldAttribute.FieldName ?? prop.Name;
                FullFieldName      = string.Format("[{0}].[{1}]", Entity.GetNameInStore(), FieldName);
                AliasFieldName     = string.Format("{0}{1}", Entity.GetNameInStore(), FieldName);

                IsCreationTracking = fieldAttribute.IsCreationTracking;
                IsUpdateTracking   = fieldAttribute.IsUpdateTracking;
                IsDeletionTracking = fieldAttribute.IsDeletionTracking;
                IsLastSyncTracking = fieldAttribute.IsLastSyncTracking;
            }

            if (prop != null)
            {
                FieldProperties = FieldPropertyFactory.Create(prop.PropertyType, fieldAttribute);
            }
        }
Example #6
0
        private Field CreateField(PropertyInfo prop, FieldAttribute fieldAttribute)
        {
            Field field;

            if (fieldAttribute.IsPrimaryKey)
            {
                PrimaryKey = PrimaryKey.Create(this, prop, fieldAttribute as PrimaryKeyAttribute);
                field      = PrimaryKey;
            }
            else if (fieldAttribute.IsForeignKey)
            {
                var foreignKey = ForeignKey.Create(Entities, this, prop, fieldAttribute as ForeignKeyAttribute);
                ForeignKeys.Add(foreignKey);
                field = foreignKey;
            }
            else
            {
                field = Field.Create(this, prop, fieldAttribute);
            }

            Fields.Add(field);
            return(field);
        }
Example #7
0
        private void ProcessNullable(FieldDef fieldDef, FieldAttribute attribute)
        {
            var canUseNullableFlag = !fieldDef.ValueType.IsValueType && !fieldDef.IsStructure;

            if (attribute.nullable != null)
            {
                if (canUseNullableFlag)
                {
                    fieldDef.IsNullable           = attribute.nullable.Value;
                    fieldDef.IsDeclaredAsNullable = attribute.nullable.Value;
                }
                else if (attribute.nullable.Value != fieldDef.ValueType.IsNullable())
                {
                    throw new DomainBuilderException(
                              string.Format(Strings.ExNullableAndNullableOnUpgradeCannotBeUsedWithXField, fieldDef.Name));
                }
            }

            if (attribute.nullableOnUpgrade != null)
            {
                if (!canUseNullableFlag)
                {
                    throw new DomainBuilderException(
                              string.Format(Strings.ExNullableAndNullableOnUpgradeCannotBeUsedWithXField, fieldDef.Name));
                }

                if (fieldDef.IsNullable)
                {
                    return;
                }

                if (context.BuilderConfiguration.Stage == UpgradeStage.Upgrading)
                {
                    fieldDef.IsNullable = attribute.nullableOnUpgrade == true;
                }
            }
        }
Example #8
0
        private void CreateTable(Type model_type)
        {
            ParsedModel    pm = GetParsedModel(model_type);
            ModelAttribute ma = GetParsedModel(model_type).Model;
            Dictionary <string, FieldAttribute> fas = pm.StorageableFields;
            string columns_str = "";
            int    len         = fas.Count;
            int    i           = 0;

            foreach (string key in fas.Keys)
            {
                i++;
                FieldAttribute fa = fas[key];
                columns_str += string.Format("{0} {1} {2} {3}", fa.FieldName, fa.DataType, fa.IsPrimaryKey? (ma.IdentityInsert? "identity(1,1)" : "") + " PRIMARY KEY" : "", fa.Nullable? "" : "NOT NULL");
                if (i != len)
                {
                    columns_str += ",";
                }
            }
            string table_str = string.Format("create table {0} ({1})", ma.TableName, columns_str);

            Set(table_str);
            DataBaseUpdateLogs.Add("创建表" + ma.TableName);
        }
Example #9
0
    TentativeDamage CalculateTentativeDamage(Unit Target, Unit Origin)
    {
        TentativeDamage result = new TentativeDamage();

        result.Origin = Origin;
        result.Target = Target;
        FieldData      targetData           = FieldDataAsset.I.GetFieldDataFromFieldType(Target.CurrentField.GetComponent <Field>().fieldType);
        FieldAttribute targetFieldAttribute = targetData.GetFieldAttributeFromMobilityType(Target.UnitStats.mobilityType);
        float          currentVisibleSP     = GetTargetVisiblity(Target).curSoftpointVis *(targetFieldAttribute.cover * Convert.ToInt32(!Target.isMoving));

        result.SP = Mathf.Ceil(Mathf.Min(currentVisibleSP, CalculateCurrentFirepower(Origin).curFirepowerSoft));
        if (float.IsNaN(result.SP))
        {
            result.SP = 0;
        }
        float currentVisibleHP = GetTargetVisiblity(Target).curHardpointVis *(targetFieldAttribute.cover * Convert.ToInt32(!Target.isMoving));

        result.HP = Mathf.Ceil(Mathf.Min(currentVisibleHP, CalculateCurrentFirepower(Origin).curFirepowerHard));
        if (float.IsNaN(result.HP))
        {
            result.HP = 0;
        }
        return(result);
    }
Example #10
0
        public PropertyDescription(Type classType, PropertyInfo property)
        {
            ClassType = classType;
            Property  = property;

            //获取或构建 特性
            FieldAttribute = property.GetAttributes <FieldAttribute>().FirstOrDefault();
            if (FieldAttribute == null)
            {
                FieldAttribute = new FieldAttribute {
                    //FieldName = property.Name,
                    EditShow = false
                };
            }

            // 通过DataSource来构建FullName
            if (FieldAttribute.DataSource.IsNullOrEmpty())
            {
                FieldAttribute.DataSource = FieldAttribute.DataSourceType?.FullName;
            }

            DisplayAttribute = property.GetAttributes <DisplayAttribute>().FirstOrDefault();
            if (DisplayAttribute == null)
            {
                DisplayAttribute = new DisplayAttribute();
            }

            Name = property.Name;
            HelpBlockAttribute = property.GetAttributes <HelpBlockAttribute>()?.FirstOrDefault();

            RequiredAttribute = property.GetAttributes <RequiredAttribute>()?.FirstOrDefault();

            MaxLengthAttribute = property.GetAttributes <MaxLengthAttribute>()?.FirstOrDefault();

            MinLengthAttribute = property.GetAttributes <MinLengthAttribute>()?.FirstOrDefault();
        }
Example #11
0
        /// <summary>
        /// Gets a value from a specific property.
        /// </summary>
        /// <remarks>
        /// If the IObjectWrapper is a proxy, this method fetches the IObject
        /// from the database and assigns it to this.UnderlyingObject
        /// </remarks>
        /// <exception cref="ActiveRecordAttributeException"></exception>
        /// <param name="propertyName">string</param>
        /// <returns>object</returns>
        public static object GetValue(this IActiveRecord wrapper, string propertyName)
        {
            if (wrapper.IsProxy)
            {
                wrapper.FetchUnderlyingObject();
            }

            if (wrapper.Deleted)
            {
                throw new ActiveRecordException("O objeto foi deletado e não é possível acessar seus atributos.");
            }

            FieldAttribute att = wrapper.GetFieldDefinition(typeof(FieldAttribute), propertyName);

            if (att == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         String.Format("Não foi possível localizar o atributo de campo para a propriedade {0}", propertyName));
            }

            if (att is DomainFieldAttribute)
            {
                return(GetDisplayValue(wrapper, att));
            }
            if (att is RelationshipAttribute)
            {
                return(FindRelatedObjects(wrapper, att));
            }

            if (att.FieldType == esriFieldType.esriFieldTypeBlob)
            {
                return(GetBlobValue(wrapper, att));
            }

            return(att.Index == -1 ? null : wrapper.UnderlyingObject.get_Value(att.Index));
        }
Example #12
0
        /// <summary>
        /// Gets the FieldAttribute located at property
        /// of a certain type
        /// </summary>
        /// <remarks>
        /// If type is null, it defaults to FieldAttribute
        /// </remarks>
        /// <param name="wrapper">IActiveWrapper</param>
        /// <param name="fieldAttributeType">Type</param>
        /// <param name="propertyName">string</param>
        /// <returns>FieldAttribute</returns>
        public static FieldAttribute GetFieldDefinition(this IActiveRecord wrapper, Type fieldAttributeType, string propertyName)
        {
            if (fieldAttributeType == null)
            {
                fieldAttributeType = typeof(FieldAttribute);
            }

            FieldAttribute propertyAttribute = null;

            try
            {
                Type         t          = wrapper.GetType();
                PropertyInfo propInfo   = t.GetProperty(propertyName);
                object[]     attributes = propInfo.GetCustomAttributes(typeof(FieldAttribute), true);
                if (attributes.Length == 1)
                {
                    propertyAttribute = (FieldAttribute)attributes[0];
                }
            }
            catch (AmbiguousMatchException ambEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A propriedade {0} possui dois ou mais atributos de campo.", propertyName),
                          ambEx);
            }
            catch (ArgumentException argEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A propriedade {0} não possui nenhum atributo de campo.", propertyName),
                          argEx);
            }

            return(propertyAttribute);
        }
Example #13
0
        public async Task <object> ReadAsync(Type type, DataType dataType, FieldAttribute attr, int?readLen = null)
        {
            switch (dataType)
            {
            case DataType.Auto:
                return(await this.ReadAutoAsync(type, attr.Absolute, attr.CountLength));

            case DataType.Boolean:
                return(await this.ReadBooleanAsync());

            case DataType.Byte:
                return(await this.ReadByteAsync());

            case DataType.UnsignedByte:
                return(await this.ReadUnsignedByteAsync());

            case DataType.Short:
                return(await this.ReadShortAsync());

            case DataType.UnsignedShort:
                return(await this.ReadUnsignedShortAsync());

            case DataType.Int:
                return(await this.ReadIntAsync());

            case DataType.Long:
                return(await this.ReadLongAsync());

            case DataType.Float:
                return(await this.ReadFloatAsync());

            case DataType.Double:
                return(await this.ReadDoubleAsync());

            case DataType.String:
                return(await this.ReadStringAsync(attr.MaxLength));

            case DataType.Chat:
                return(await this.ReadChatAsync());

            case DataType.Identifier:
                return(await this.ReadStringAsync());

            case DataType.VarInt:
                return(await this.ReadVarIntAsync());

            case DataType.VarLong:
                return(await this.ReadVarLongAsync());

            case DataType.Position:
            {
                if (type == typeof(Position))
                {
                    if (attr.Absolute)
                    {
                        return(new Position(await this.ReadDoubleAsync(), await this.ReadDoubleAsync(), await this.ReadDoubleAsync()));
                    }

                    return(await this.ReadPositionAsync());
                }
                else if (type == typeof(SoundPosition))
                {
                    return(new SoundPosition(await this.ReadIntAsync(), await this.ReadIntAsync(), await this.ReadIntAsync()));
                }

                return(null);
            }

            case DataType.Angle:
                return(this.ReadFloatAsync());

            case DataType.UUID:
                return(Guid.Parse(await this.ReadStringAsync()));

            case DataType.Velocity:
                return(new Velocity(await this.ReadShortAsync(), await this.ReadShortAsync(), await this.ReadShortAsync()));

            case DataType.EntityMetadata:
            case DataType.Slot:
            {
                return(await this.ReadSlotAsync());
            }

            case DataType.ByteArray:
            {
                int len = readLen.Value;
                var arr = await this.ReadUInt8ArrayAsync(len);

                return(arr);
            }

            case DataType.NbtTag:
            case DataType.Array:
            default:
                throw new NotImplementedException(nameof(type));
            }
        }
Example #14
0
        private static (object value, OracleDbType?dbType) getDbFieldValue(Doc doc, Schema.FieldDef fld, FieldAttribute fattr, OracleDataStoreBase store)
        {
            var result = doc.GetFieldValue(fld);

            return(CLRValueToDB(store, result, fattr.BackendType));
        }
        internal static Field ToFieldType(MemberInfo member)
        {
            var propertyInfo = member as PropertyInfo;

            if (propertyInfo == null)
            {
                var methodInfo = member as MethodInfo;
                if (methodInfo == null)
                {
                    Assert.Inconsistent();
                }
                var    declaringType = methodInfo.DeclaringType;
                string trimGet       = member.Name.Substring(4);
                propertyInfo = declaringType.GetProperty(trimGet);
            }

            Type           propType        = propertyInfo.PropertyType;
            string         spName          = TranslateToFieldName(propertyInfo.Name);
            var            fieldAttrs      = propertyInfo.GetCustomAttributes(typeof(FieldAttribute), true);
            var            customAttrs     = (CustomPropertyAttribute[])propertyInfo.GetCustomAttributes(typeof(CustomPropertyAttribute), true);
            string         dispName        = null;
            bool           isMultilineText = false;
            object         defaultValue    = null;
            bool           required        = false;
            FieldAttribute attr            = null;

            if (fieldAttrs.Length != 0)
            {
                attr = (FieldAttribute)fieldAttrs[0];
                var spPropName = attr.Name;
                if (spPropName != null)
                {
                    spName = spPropName;
                }
                dispName        = attr.DisplayName;
                isMultilineText = attr.IsMultilineText;
                required        = attr.Required;
                defaultValue    = attr.DefaultValue;
            }


            var field = new Field {
                Name     = spName, Property = propertyInfo, DisplayName = dispName,
                Required = required, DefaultValue = defaultValue, FieldAttribute = attr,
            };

            if (customAttrs.Length != 0)
            {
                var typeAttr = customAttrs.FirstOrDefault(ca => ca.Name == "Type");
                if (typeAttr != null)
                {
                    field.Type = (SPFieldType)Enum.Parse(typeof(SPFieldType), typeAttr.Value);
                    return(field);
                }
            }

            if (attr != null && attr.FieldProvider != null)
            {
                field.Type = SPFieldType.Invalid;
                return(field);
            }

            if (propType == typeof(string))
            {
                field.Type = isMultilineText ? SPFieldType.Note : SPFieldType.Text;
                return(field);
            }

            if (isMultilineText)
            {
                throw new SharepointCommonException("[IsMultilineText] can be used only for text fields.");
            }

            if (propType == typeof(Version) || propType == typeof(Guid))
            {
                field.Type = SPFieldType.Text;
                return(field);
            }

            if (propType == typeof(DateTime) || propType == typeof(DateTime?))
            {
                field.Type = SPFieldType.DateTime;
                return(field);
            }


            if (propType == typeof(User))
            {
                field.Type = SPFieldType.User;
                return(field);
            }

            if (propType == typeof(double) || propType == typeof(double?) ||
                propType == typeof(int) || propType == typeof(int?))
            {
                field.Type = SPFieldType.Number;
                return(field);
            }

            if (propType == typeof(decimal) || propType == typeof(decimal?))
            {
                field.Type = SPFieldType.Currency;
                return(field);
            }

            if (propType == typeof(bool) || propType == typeof(bool?))
            {
                field.Type = SPFieldType.Boolean;
                return(field);
            }

            // lookup fields
            if (typeof(Item).IsAssignableFrom(propType))
            {
                // lookup single value
                if (attr == null)
                {
                    throw new SharepointCommonException("Lookups must be marked with [SharepointCommon.Attributes.FieldAttribute]");
                }

                field.Type        = SPFieldType.Lookup;
                field.LookupList  = attr.LookupList;
                field.LookupField = attr.LookupField ?? "Title";
                return(field);
            }

            if (CommonHelper.ImplementsOpenGenericInterface(propType, typeof(IEnumerable <>)))
            {
                Type argumentType = propType.GetGenericArguments()[0];

                //// user multi value

                if (argumentType == typeof(User))
                {
                    field.Type         = SPFieldType.User;
                    field.IsMultiValue = true;
                    return(field);
                    //return new Field {Type = SPFieldType.User, Name = propertyInfo.Name, IsMultiValue = true,};
                }

                //// lookup multi value

                if (attr == null)
                {
                    throw new SharepointCommonException("Lookups must be marked with [SharepointCommon.Attributes.FieldAttribute]");
                }


                if (typeof(Item).IsAssignableFrom(argumentType))
                {
                    field.Type         = SPFieldType.Lookup;
                    field.LookupList   = attr.LookupList;
                    field.LookupField  = attr.LookupField;
                    field.IsMultiValue = true;
                    return(field);
                }
            }

            if (propType.IsEnum)
            {
                field.Type    = SPFieldType.Choice;
                field.Choices = EnumMapper.GetEnumMemberTitles(propType);
                if (field.Choices.Any() == false)
                {
                    throw new SharepointCommonException("enum must have at least one field");
                }
                return(field);
            }

            if (CommonHelper.ImplementsOpenGenericInterface(propType, typeof(Nullable <>)))
            {
                Type argumentType = propType.GetGenericArguments()[0];

                if (argumentType.IsEnum)
                {
                    field.Type    = SPFieldType.Choice;
                    field.Choices = Enum.GetNames(argumentType);
                    if (field.Choices.Any() == false)
                    {
                        throw new SharepointCommonException("enum must have at least one field");
                    }
                    return(field);
                }
            }

            if (propType == typeof(Person))
            {
                throw new SharepointCommonException("Cannot use [Person] as mapped property. Use [User] instead.");
            }

            throw new SharepointCommonException("no field type mapping found");
        }
Example #16
0
 public void FieldAttribute_InitializingConstructorForUnsetControlType()
 {
     fieldAttribute = new FieldAttribute(ControlType.Unset, ColumnSpan.Unset);
     Assert.AreEqual(ControlType.Unset, fieldAttribute.ControlType);
     Assert.AreEqual(ColumnSpan.Unset, fieldAttribute.ColumnSpan);
 }
Example #17
0
 public void FieldAttribute_InitializingConstructorForMultiselectControlType()
 {
     fieldAttribute = new FieldAttribute(ControlType.Multiselect, ColumnSpan.Large);
     Assert.AreEqual(ControlType.Multiselect, fieldAttribute.ControlType);
     Assert.AreEqual(ColumnSpan.Large, fieldAttribute.ColumnSpan);
 }
Example #18
0
        private Schema erlSchemaToCRUDSchema(string name)
        {
            var erlSect = GetErlSchemaSection(name);

            if (erlSect == null)
            {
                throw new ErlDataAccessException(StringConsts.ERL_DS_SCHEMA_MAP_NOT_KNOWN_ERROR.Args(name));
            }

            var defs = new List <Schema.FieldDef>();

            var isInsert = erlSect.AttrByName(CONFIG_INSERT_ATTR).ValueAsBool(false);
            var isUpdate = erlSect.AttrByName(CONFIG_UPDATE_ATTR).ValueAsBool(false);
            var isDelete = erlSect.AttrByName(CONFIG_DELETE_ATTR).ValueAsBool(false);

            var isReadonly = !(isInsert || isUpdate || isDelete);


            var keyCount   = 0;
            var nodeFields = erlSect.Children.Where(c => c.IsSameName(CONFIG_FIELD_SECTION));

            foreach (var nodeField in nodeFields)
            {
                var fname    = nodeField.AttrByName(Configuration.CONFIG_NAME_ATTR).Value;
                var ftitle   = nodeField.AttrByName(CONFIG_TITLE_ATTR).Value;
                var isKey    = nodeField.AttrByName(CONFIG_KEY_ATTR).ValueAsBool();
                var required = nodeField.AttrByName(CONFIG_REQUIRED_ATTR).ValueAsBool(false);
                var type     = nodeField.AttrByName(CONFIG_TYPE_ATTR).Value;
                var clrType  = mapErlTypeToCLR(type);

                object minV = null;
                object maxV = null;

                var sv = nodeField.AttrByName(CONFIG_MIN_ATTR).Value;
                if (sv.IsNotNullOrWhiteSpace())
                {
                    minV = sv.AsType(clrType, true);
                }

                sv = nodeField.AttrByName(CONFIG_MAX_ATTR).Value;
                if (sv.IsNotNullOrWhiteSpace())
                {
                    maxV = sv.AsType(clrType, true);
                }



                var    strDfltValue = nodeField.AttrByName(CONFIG_DEFAULT_ATTR).ValueAsString(string.Empty);
                object dfltValue    = null;

                if (clrType != typeof(string))
                {
                    if (strDfltValue.IsNotNullOrWhiteSpace())
                    {
                        if (clrType == typeof(DateTime?))
                        {
                            dfltValue = ((long)strDfltValue.AsType(typeof(long), false)).FromMicrosecondsSinceUnixEpochStart();
                        }
                        else
                        {
                            dfltValue = strDfltValue.AsType(clrType, false);
                        }
                    }
                }
                else
                {
                    dfltValue = strDfltValue;
                }

                if (isKey)
                {
                    keyCount++;
                }

                List <string> vList = null;

                var values = nodeField.Children.Where(c => c.IsSameName(CONFIG_VALUE_SECTION));
                foreach (var vnode in values)
                {
                    var code = vnode.AttrByName(CONFIG_CODE_ATTR).Value;
                    var disp = vnode.AttrByName(CONFIG_DISPLAY_ATTR).Value;
                    if (code.IsNullOrWhiteSpace())
                    {
                        continue;
                    }

                    if (vList == null)
                    {
                        vList = new List <string>();
                    }
                    if (disp.IsNullOrWhiteSpace())
                    {
                        vList.Add(code);
                    }
                    else
                    {
                        vList.Add("{0}: {1}".Args(code, disp));
                    }
                }


                var caze = CharCase.AsIs;

                var ca = nodeField.AttrByName(CONFIG_CASE_ATTR).Value;
                if (ca.EqualsOrdIgnoreCase("upper"))
                {
                    caze = CharCase.Upper;
                }
                else
                if (ca.EqualsOrdIgnoreCase("lower"))
                {
                    caze = CharCase.Lower;
                }


                var atr = new FieldAttribute(
                    targetName: m_Store.TargetName,
                    backendName: fname,
                    backendType: type,
                    storeFlag: StoreFlag.LoadAndStore,
                    key: isKey,
                    required: required,
                    dflt: dfltValue,

                    min: minV,
                    max: maxV,

                    charCase: caze,

                    visible:   nodeField.AttrByName(CONFIG_VISIBLE_ATTR).ValueAsBool(true),
                    maxLength: nodeField.AttrByName(CONFIG_LEN_ATTR).ValueAsInt(0),
                    description: ftitle,
                    formatRegExp: nodeField.AttrByName(CONFIG_FORMAT_ATTR).Value,
                    formatDescr: nodeField.AttrByName(CONFIG_FORMAT_DESCR_ATTR).Value,
                    displayFormat: nodeField.AttrByName(CONFIG_DISPLAY_FORMAT_ATTR).Value,
                    valueList: vList == null ? null : string.Join(",", vList),   //"CAR: Car Driver,SMK: Smoker, REL: Religious, CNT: Country music lover, GLD: Gold collector"
                    metadata: nodeField.ToLaconicString());

                var def = new Schema.FieldDef(fname, clrType, new FieldAttribute[] { atr });
                defs.Add(def);
            }//for fields



            var result = new Schema(name, isReadonly, defs.ToArray());

            result.ExtraData[SCHEMA_KEY_COUNT] = keyCount;
            result.ExtraData[Schema.EXTRA_SUPPORTS_INSERT_ATTR] = isInsert;
            result.ExtraData[Schema.EXTRA_SUPPORTS_UPDATE_ATTR] = isUpdate;
            result.ExtraData[Schema.EXTRA_SUPPORTS_DELETE_ATTR] = isDelete;

            return(result);
        }
Example #19
0
 /// <summary>
 /// Ctor
 /// </summary>
 public PiMap(PropertyInfo pi, FieldAttribute fieldAttr)
 {
     this.pi        = pi;
     this.fieldAttr = fieldAttr;
     this.dbType    = DbTypeConvertor.TypeToDbType(pi.PropertyType);
 }
Example #20
0
 public void FieldAttribute_InitializingDafaultConstructor()
 {
     fieldAttribute = new FieldAttribute();
     Assert.AreEqual(ColumnSpan.Small, fieldAttribute.ColumnSpan);
 }
Example #21
0
        public EntityInfo[] GetEntityDefinitions()
        {
            ValidateConnection();

            var entities = new List <EntityInfo>();

            using (var connection = new SqlCeConnection(m_connectionString))
                using (var cmd = new SqlCeCommand(GetTablesSQL, connection))
                {
                    connection.Open();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var info      = new EntityInfo();
                            var indexInfo = new Dictionary <string, IndexInfo>();

                            info.Entity             = new EntityAttribute();
                            info.Entity.NameInStore = reader.GetString(0);

                            using (var indexCommand = new SqlCeCommand(
                                       string.Format("SELECT INDEX_NAME, PRIMARY_KEY, COLUMN_NAME, COLLATION FROM INFORMATION_SCHEMA.INDEXES WHERE TABLE_NAME = '{0}'", info.Entity.NameInStore),
                                       connection))
                                using (var indexReader = indexCommand.ExecuteReader())
                                {
                                    while (indexReader.Read())
                                    {
                                        var indexName  = indexReader.GetString(0);
                                        var primaryKey = indexReader.GetBoolean(1);
                                        var columnName = indexReader.GetString(2);
                                        var sortOrder  = indexReader.GetInt16(3) == 1 ? FieldSearchOrder.Ascending : FieldSearchOrder.Descending;
                                        // collation of 1 == ascending, 2 == descending (based on a quick test, this might be incorrect)

                                        // TODO: handle cases where a column is in multiple indexes (ORM doesn't support that scenario for now)
                                        if (!indexInfo.ContainsKey(columnName))
                                        {
                                            indexInfo.Add(columnName, new IndexInfo()
                                            {
                                                ColumnName  = columnName,
                                                IndexName   = indexName,
                                                PrimaryKey  = primaryKey,
                                                SearchOrder = sortOrder
                                            });
                                        }
                                    }
                                }

                            // TODO: look for primary key to set key scheme
                            info.Entity.KeyScheme = KeyScheme.None;

                            using (var fieldCommand = new SqlCeCommand(
                                       string.Format("SELECT COLUMN_NAME, COLUMN_HASDEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, AUTOINC_SEED FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}'", info.Entity.NameInStore),
                                       connection))
                            {
                                using (var fieldReader = fieldCommand.ExecuteReader())
                                {
                                    while (fieldReader.Read())
                                    {
                                        var field = new FieldAttribute();
                                        field.FieldName   = fieldReader.GetString(0);
                                        field.AllowsNulls = string.Compare(fieldReader.GetString(2), "YES", true) == 0;
                                        field.DataType    = fieldReader.GetString(3).ParseToDbType();
                                        object val = fieldReader[4];
                                        if (!val.Equals(DBNull.Value))
                                        {
                                            field.Length = Convert.ToInt32(val);
                                        }
                                        val = fieldReader[5];
                                        if (!val.Equals(DBNull.Value))
                                        {
                                            field.Precision = Convert.ToInt32(val);
                                        }
                                        val = fieldReader[6];
                                        if (!val.Equals(DBNull.Value))
                                        {
                                            field.Scale = Convert.ToInt32(val);
                                        }
                                        val = fieldReader[7];
                                        if (!val.Equals(DBNull.Value))
                                        {
                                            // identity field, so it must be the PK (or part of it)
                                            info.Entity.KeyScheme = KeyScheme.Identity;
                                        }

                                        // check for indexes
                                        if (indexInfo.ContainsKey(field.FieldName))
                                        {
                                            var idx = indexInfo[field.FieldName];

                                            if (idx.PrimaryKey)
                                            {
                                                field.IsPrimaryKey = true;

                                                if (field.DataType == DbType.Guid)
                                                {
                                                    info.Entity.KeyScheme = KeyScheme.GUID;
                                                }
                                            }
                                            field.SearchOrder = idx.SearchOrder;
                                        }

                                        // TODO: populate the remainder of the field info
                                        info.Fields.Add(field);
                                    }
                                }
                            }

                            // check for references
                            using (var referenceSourceCommand = new SqlCeCommand(
                                       string.Format(
                                           "SELECT a.Constraint_name, a.TABLE_NAME, b.COLUMN_NAME " +
                                           "FROM information_schema.table_constraints AS a " +
                                           "INNER JOIN information_schema.KEY_COLUMN_USAGE AS b ON a.CONSTRAINT_NAME = b.CONSTRAINT_NAME " +
                                           "WHERE (a.TABLE_NAME = '{0}') AND (a.CONSTRAINT_TYPE = 'FOREIGN KEY')",
                                           info.Entity.NameInStore),
                                       connection))
                            {
                                string constraintName  = null;
                                string localField      = null;
                                string remoteTable     = null;
                                string remoteFieldName = null;
                                bool   referenceExists = false;

                                using (var srcReader = referenceSourceCommand.ExecuteReader())
                                {
                                    while (srcReader.Read())
                                    {
                                        constraintName = (string)srcReader[0];
                                        localField     = (string)srcReader[2];

                                        using (var referenceTargetCommand = new SqlCeCommand(
                                                   string.Format(
                                                       "SELECT a.UNIQUE_CONSTRAINT_TABLE_NAME, b.COLUMN_NAME " +
                                                       "FROM information_schema.REFERENTIAL_CONSTRAINTS AS a INNER JOIN " +
                                                       "information_schema.KEY_COLUMN_USAGE AS b ON a.Constraint_name = b.CONSTRAINT_NAME " +
                                                       "WHERE a.CONSTRAINT_NAME = '{0}'",
                                                       constraintName),
                                                   connection))
                                        {
                                            using (var targetReader = referenceTargetCommand.ExecuteReader())
                                            {
                                                while (targetReader.Read())
                                                {
                                                    remoteTable     = (string)targetReader[0];
                                                    remoteFieldName = (string)targetReader[1];
                                                    referenceExists = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (referenceExists)
                                {
                                    var reference = new ReferenceInfo()
                                    {
                                        ReferenceTable  = remoteTable,
                                        LocalFieldName  = localField,
                                        RemoteFieldName = remoteFieldName
                                    };
                                    info.References.Add(reference);
                                }
                            }
                            entities.Add(info);
                        }
                    }
                }

            return(entities.ToArray());
        }
Example #22
0
 public void FieldAttribute_InitializingConstructorForNarrativeControlType()
 {
     fieldAttribute = new FieldAttribute(ControlType.Narrative);
     Assert.AreEqual(ControlType.Narrative, fieldAttribute.ControlType);
     Assert.AreEqual(ColumnSpan.Small, fieldAttribute.ColumnSpan);
 }
Example #23
0
 public void FieldAttribute_InitializingConstructorForTextControlType()
 {
     _fieldAttribute = new FieldAttribute(ControlType.Text, ColumnSpan.Medium);
     Assert.AreEqual(ControlType.Text, _fieldAttribute.ControlType);
     Assert.AreEqual(ColumnSpan.Medium, _fieldAttribute.ColumnSpan);
 }
Example #24
0
 public void FieldAttribute_InitializingConstructorForOfficerControlType()
 {
     fieldAttribute = new FieldAttribute(ControlType.Officer, ColumnSpan.Medium);
     Assert.AreEqual(ControlType.Officer, fieldAttribute.ControlType);
     Assert.AreEqual(ColumnSpan.Medium, fieldAttribute.ColumnSpan);
 }
Example #25
0
 private CodeAttributeArgument[] GenerateFieldArguments(FieldAttribute field)
 {
     return(GenerateFieldArguments(field, null));
 }
Example #26
0
        public void Record_ValidInitJSON()
        {
            var json =
                @"{
  'OK': true,
  'ID': '39a833dd-b48f-46c1-83a6-96603cc962a6',
  'ISOLang': 'eng',
  '__FormMode': 'Edit',
  '__CSRFToken': '1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP',
  '__Roundtrip': '{\'GDID\':\'0:1:5\'}',
  'fields': [
      {
        'def': {
          'Name': 'Mnemonic',
          'Type': 'string',
          'Description': 'Mnemonic',
          'Required': true,
          'MinSize': 1,
          'Size': 25,
          'Placeholder': 'Mnemonic',
          'Stored': false
        },
        'val': 'Dns'
      },
      {
        'def': {
          'Name': 'Vertical_ID',
          'Type': 'string',
          'Description': 'Vertical',
          'Required': false,
          'Visible': false,
          'Size': 15,
          'DefaultValue': 'HAB',
          'Key': true,
          'Case': 'Upper',
          'LookupDict': {
            'HAB': 'HAB.rs Health and Beauty',
            'READRS': 'READ.rs Book Business',
            'SLRS': 'SL.RS General Business'
          }
        },
        'val': 'HAB'
      },
      {
        'def': {
          'Name': 'Table_ID',
          'Type': 'int',
          'Key': true,
          'Description': 'Table',
          'Required': true,
          'Visible': false,
          'MinValue': 1,
          'MaxValue': 123,
          'DefaultValue': 15,
          'Kind': 'Number',
          'Stored': true
        },
        'val': 2
      }
    ]
}";

            var init = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var rec  = new Record(init);

            Assert.AreEqual(0, rec.ServerErrors.Count());

            Assert.AreEqual(true, rec.OK);
            Assert.AreEqual("eng", rec.ISOLang);
            Assert.AreEqual(new Guid("39a833dd-b48f-46c1-83a6-96603cc962a6"), rec.ID);
            Assert.AreEqual("Edit", rec.FormMode);
            Assert.AreEqual("1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP", rec.CSRFToken);

            var roundtrip = rec.Roundtrip;

            Assert.IsNotNull(roundtrip);
            Assert.AreEqual(roundtrip.Count, 1);
            Assert.AreEqual("0:1:5", roundtrip["GDID"]);

            Assert.AreEqual(3, rec.Schema.FieldCount);

            var fdef = rec.Schema["Mnemonic"];

            Assert.IsNotNull(fdef);
            Assert.AreEqual("Mnemonic", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual(false, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            var attr = fdef.Attrs.First();

            Assert.AreEqual("Mnemonic", attr.Description);
            Assert.AreEqual(true, attr.Required);
            Assert.AreEqual(true, attr.Visible);
            Assert.AreEqual(null, attr.Min);
            Assert.AreEqual(null, attr.Max);
            Assert.AreEqual(1, attr.MinLength);
            Assert.AreEqual(25, attr.MaxLength);
            Assert.AreEqual(null, attr.Default);
            Assert.AreEqual(0, attr.ParseValueList().Count);
            Assert.AreEqual(StoreFlag.OnlyLoad, attr.StoreFlag);
            Assert.AreEqual(@"''{Name=Mnemonic Type=string Description=Mnemonic Required=True MinSize=1 Size=25 Placeholder=Mnemonic Stored=False}", attr.MetadataContent);
            Assert.AreEqual("Dns", rec["Mnemonic"]);

            fdef = rec.Schema["Vertical_ID"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("Vertical_ID", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual(true, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Assert.AreEqual("Vertical", attr.Description);
            Assert.AreEqual(false, attr.Required);
            Assert.AreEqual(false, attr.Visible);
            Assert.AreEqual(null, attr.Min);
            Assert.AreEqual(null, attr.Max);
            Assert.AreEqual(0, attr.MinLength);
            Assert.AreEqual(15, attr.MaxLength);
            Assert.AreEqual(CharCase.Upper, attr.CharCase);
            Assert.AreEqual("HAB", attr.Default);
            Assert.AreEqual(FieldAttribute.ParseValueListString("HAB:HAB.rs Health and Beauty,READRS:READ.rs Book Business,SLRS:SL.RS General Business", true), attr.ParseValueList(true));
            Assert.AreEqual("''{Name=Vertical_ID Type=string Description=Vertical Required=False Visible=False Size=15 DefaultValue=HAB Key=True Case=Upper LookupDict=\"{\\\"HAB\\\":\\\"HAB.rs Health and Beauty\\\",\\\"READRS\\\":\\\"READ.rs Book Business\\\",\\\"SLRS\\\":\\\"SL.RS General Business\\\"}\"}", attr.MetadataContent);
            Assert.AreEqual("HAB", rec["Vertical_ID"]);

            fdef = rec.Schema["Table_ID"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("Table_ID", fdef.Name);
            Assert.AreEqual(typeof(long), fdef.Type);
            Assert.AreEqual(true, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Assert.AreEqual("Table", attr.Description);
            Assert.AreEqual(true, attr.Required);
            Assert.AreEqual(false, attr.Visible);
            Assert.AreEqual(1, attr.Min);
            Assert.AreEqual(123, attr.Max);
            Assert.AreEqual(15, attr.Default);
            Assert.AreEqual(DataKind.Number, attr.Kind);
            Assert.AreEqual(StoreFlag.LoadAndStore, attr.StoreFlag);
            Assert.AreEqual(0, attr.ParseValueList(true).Count);
            Assert.AreEqual("''{Name=Table_ID Type=int Key=True Description=Table Required=True Visible=False MinValue=1 MaxValue=123 DefaultValue=15 Kind=Number Stored=True}", attr.MetadataContent);
            Assert.AreEqual(2, rec["Table_ID"]);
        }
Example #27
0
        public JavaClass convert(Type abstractMojoType, string groupId)
        {
            JavaClass javaClass = new JavaClass();

            javaClass.PackageName      = abstractMojoType.Namespace;
            javaClass.ClassName        = abstractMojoType.Name;
            javaClass.ExtendsClassName = "org.apache.npanday.plugins.AbstractMojo";

            ImportPackage importPackage = new ImportPackage();

            javaClass.ImportPackage = importPackage.AddPackage("org.apache.npanday.plugins.FieldAnnotation");

            List <String> classComments = new List <String>();

            System.Attribute[] attributes =
                System.Attribute.GetCustomAttributes(abstractMojoType);

            foreach (Attribute attribute in attributes)
            {
                if (attribute is ClassAttribute)
                {
                    ClassAttribute mojo = (ClassAttribute)attribute;
                    classComments.Add(@"@phase " + mojo.Phase);
                    classComments.Add(@"@goal " + mojo.Goal);
                    break;
                }
            }

            javaClass.Comments = classComments;

            List <JavaField> javaFields = new List <JavaField>();

            foreach (FieldInfo field in abstractMojoType.GetFields())
            {
                foreach (Attribute attribute in field.GetCustomAttributes(true))
                {
                    FieldAttribute mojo = (FieldAttribute)attribute;
                    javaFields.Add(CreateJavaField("public", mojo.Type, mojo.Name,
                                                   CreateMojoComment(mojo.Expression),
                                                   "FieldAnnotation()"));
                }
            }

            //mojo parameters
            javaFields.Add(CreateJavaField("private", "org.apache.maven.project.MavenProject", "project",
                                           CreateMojoComment("${project}"), null));
            javaFields.Add(CreateJavaField("private", "String", "localRepository",
                                           CreateMojoComment("${settings.localRepository}"), null));
            javaFields.Add(CreateJavaField("private", "String", "vendor",
                                           CreateMojoComment("${vendor}"), null));
            javaFields.Add(CreateJavaField("private", "String", "vendorVersion",
                                           CreateMojoComment("${vendorVersion}"), null));
            javaFields.Add(CreateJavaField("private", "String", "frameworkVersion",
                                           CreateMojoComment("${frameworkVersion}"), null));

            //components
            List <String> comments = new List <String>();

            comments.Add("@component");
            javaFields.Add(CreateJavaField("private", "npanday.executable.NetExecutableFactory",
                                           "netExecutableFactory", comments, null));
            javaFields.Add(CreateJavaField("private", "org.apache.npanday.plugins.PluginContext",
                                           "pluginContext", comments, null));

            //methods
            List <JavaMethod> javaMethods = new List <JavaMethod>();

            javaMethods.Add(CreateJavaMethod("public", "String", "getMojoArtifactId",
                                             new Code().AddLine(@"return """
                                                                + abstractMojoType.Namespace + @""";")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getMojoGroupId",
                                             new Code().AddLine(@"return """
                                                                + groupId + @""";")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getClassName",
                                             new Code().AddLine(@"return """ + abstractMojoType.Namespace
                                                                + "." + abstractMojoType.Name + @""";")));

            javaMethods.Add(CreateJavaMethod("public", "org.apache.npanday.plugins.PluginContext",
                                             "getNetPluginContext",
                                             CreateCodeWithSimpleReturnType("pluginContext")));

            javaMethods.Add(CreateJavaMethod("public", "npanday.executable.NetExecutableFactory",
                                             "getNetExecutableFactory",
                                             CreateCodeWithSimpleReturnType("netExecutableFactory")));

            javaMethods.Add(CreateJavaMethod("public", "org.apache.maven.project.MavenProject", "getMavenProject",
                                             CreateCodeWithSimpleReturnType("project")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getLocalRepository",
                                             CreateCodeWithSimpleReturnType("localRepository")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getVendorVersion",
                                             CreateCodeWithSimpleReturnType("vendorVersion")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getVendor",
                                             CreateCodeWithSimpleReturnType("vendor")));

            javaMethods.Add(CreateJavaMethod("public", "String", "getFrameworkVersion",
                                             CreateCodeWithSimpleReturnType("frameworkVersion")));
            javaClass.JavaMethods = javaMethods;
            javaClass.JavaFields  = javaFields;
            return(javaClass);
        }
Example #28
0
 public static Field Create(IEntityInfo entity, PropertyInfo prop, FieldAttribute fieldAttribute)
 {
     return(new Field(entity, prop, fieldAttribute));
 }
 private void InitializeFromDefinition(PropertyInfo definitionProperty, FieldAttribute fieldAttribute)
 {
     FieldId = fieldAttribute.FieldId;
     InternalName = definitionProperty.Name;
     StaticName = InternalName;
 }
Example #30
0
        public async Task WriteAsync(DataType type, FieldAttribute attribute, object value, int length = 32767)
        {
            switch (type)
            {
            case DataType.Auto:
            {
                if (value is Player player)
                {
                    await this.WriteUnsignedByteAsync(0xff);
                }
                else
                {
                    await this.WriteAutoAsync(value);
                }

                break;
            }

            case DataType.Angle:
            {
                await this.WriteAngleAsync((Angle)value);

                break;
            }

            case DataType.Boolean:
            {
                await this.WriteBooleanAsync((bool)value);

                break;
            }

            case DataType.Byte:
            {
                await this.WriteByteAsync((sbyte)value);

                break;
            }

            case DataType.UnsignedByte:
            {
                await this.WriteUnsignedByteAsync((byte)value);

                break;
            }

            case DataType.Short:
            {
                await this.WriteShortAsync((short)value);

                break;
            }

            case DataType.UnsignedShort:
            {
                await this.WriteUnsignedShortAsync((ushort)value);

                break;
            }

            case DataType.Int:
            {
                await this.WriteIntAsync((int)value);

                break;
            }

            case DataType.Long:
            {
                await this.WriteLongAsync((long)value);

                break;
            }

            case DataType.Float:
            {
                await this.WriteFloatAsync((float)value);

                break;
            }

            case DataType.Double:
            {
                await this.WriteDoubleAsync((double)value);

                break;
            }

            case DataType.String:
            {
                // TODO: add casing options on Field attribute and support custom naming enums.
                var val = value.GetType().IsEnum ? value.ToString().ToCamelCase() : value.ToString();
                await this.WriteStringAsync(val, length);

                break;
            }

            case DataType.Chat:
            {
                await this.WriteChatAsync((ChatMessage)value);

                break;
            }

            case DataType.VarInt:
            {
                await this.WriteVarIntAsync((int)value);

                break;
            }

            case DataType.VarLong:
            {
                await this.WriteVarLongAsync((long)value);

                break;
            }

            case DataType.Position:
            {
                if (value is Position position)
                {
                    if (attribute.Absolute)
                    {
                        await this.WriteDoubleAsync(position.X);

                        await this.WriteDoubleAsync(position.Y);

                        await this.WriteDoubleAsync(position.Z);

                        break;
                    }

                    await this.WritePositionAsync(position);
                }
                else if (value is SoundPosition soundPosition)
                {
                    await this.WriteIntAsync(soundPosition.X);

                    await this.WriteIntAsync(soundPosition.Y);

                    await this.WriteIntAsync(soundPosition.Z);
                }

                break;
            }

            case DataType.Velocity:
            {
                var velocity = (Velocity)value;

                await this.WriteShortAsync(velocity.X);

                await this.WriteShortAsync(velocity.Y);

                await this.WriteShortAsync(velocity.Z);

                break;
            }

            case DataType.UUID:
            {
                await this.WriteUuidAsync((Guid)value);

                break;
            }

            case DataType.Array:
            {
                if (value is List <CommandNode> nodes)
                {
                    foreach (var node in nodes)
                    {
                        await node.CopyToAsync(this);
                    }
                }
                else if (value is List <PlayerInfoAction> actions)
                {
                    await this.WriteVarIntAsync(actions.Count);

                    foreach (var action in actions)
                    {
                        await action.WriteAsync(this);
                    }
                }
                else if (value is List <int> ids)
                {
                    foreach (var id in ids)
                    {
                        await this.WriteVarIntAsync(id);
                    }
                }
                else if (value is List <string> values)
                {
                    foreach (var vals in values)
                    {
                        await this.WriteStringAsync(vals);
                    }
                }
                else if (value is List <long> vals)
                {
                    foreach (var val in vals)
                    {
                        await this.WriteLongAsync(val);
                    }
                }
                else if (value is List <Tag> tags)
                {
                    await this.WriteVarIntAsync(tags.Count);

                    foreach (var tag in tags)
                    {
                        await this.WriteStringAsync(tag.Name);

                        await this.WriteVarIntAsync(tag.Count);

                        foreach (var entry in tag.Entries)
                        {
                            await this.WriteVarIntAsync(entry);
                        }
                    }
                }
                break;
            }

            case DataType.ByteArray:
            {
                var array = (byte[])value;
                if (attribute.CountLength)
                {
                    await this.WriteVarIntAsync(array.Length);

                    await this.WriteAsync(array);
                }
                else
                {
                    await this.WriteAsync(array);
                }
                break;
            }

            case DataType.Slot:
            {
                await this.WriteSlotAsync((ItemStack)value);

                break;
            }

            case DataType.EntityMetadata:
            {
                var ent = (Entity)value;
                await ent.WriteAsync(this);

                await this.WriteUnsignedByteAsync(0xff);

                break;
            }

            case DataType.NbtTag:
            {
                if (value is MixedCodec codecs)
                {
                    var dimensions = new NbtCompound(codecs.Dimensions.Name)
                    {
                        new NbtString("type", codecs.Dimensions.Name)
                    };

                    var list = new NbtList("value", NbtTagType.Compound);

                    foreach (var(_, codec) in codecs.Dimensions)
                    {
                        codec.Write(list);
                    }

                    dimensions.Add(list);

                    #region biomes
                    var biomeCompound = new NbtCompound(codecs.Biomes.Name)
                    {
                        new NbtString("type", codecs.Biomes.Name)
                    };

                    var biomes = new NbtList("value", NbtTagType.Compound);

                    foreach (var(_, biome) in codecs.Biomes)
                    {
                        biome.Write(biomes);
                    }

                    biomeCompound.Add(biomes);
                    #endregion
                    var compound = new NbtCompound("")
                    {
                        dimensions,
                        biomeCompound
                    };
                    var nbt = new NbtFile(compound);

                    nbt.SaveToStream(this, NbtCompression.None);
                }
                else if (value is DimensionCodec codec)
                {
                    var nbt = new NbtFile(codec.ToNbt());

                    nbt.SaveToStream(this, NbtCompression.None);
                }
                break;
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(type));
            }
        }
Example #31
0
        private static JSONDataMap fieldDefToJSON(string schema, Schema.FieldDef fdef, string target)
        {
            var result = new JSONDataMap();

            result["Name"] = fdef.Name;
            result["Type"] = mapType(fdef.NonNullableType);
            var key = fdef.AnyTargetKey;

            if (key)
            {
                result["Key"] = key;
            }


            if (fdef.NonNullableType.IsEnum)
            { //Generate default lookupdict for enum
                var names  = Enum.GetNames(fdef.NonNullableType);
                var values = new JSONDataMap(true);
                foreach (var name in names)
                {
                    values[name] = name;
                }

                result["LookupDict"] = values;
            }

            var attr = fdef[target];

            if (attr != null)
            {
                if (attr.Description != null)
                {
                    result["Description"] = localizeString(schema, "Description", attr.Description);
                }
                var str = attr.StoreFlag == StoreFlag.OnlyStore || attr.StoreFlag == StoreFlag.LoadAndStore;
                if (!str)
                {
                    result["Stored"] = str;
                }
                if (attr.Required)
                {
                    result["Required"] = attr.Required;
                }
                if (!attr.Visible)
                {
                    result["Visible"] = attr.Visible;
                }
                if (attr.Min != null)
                {
                    result["MinValue"] = attr.Min;
                }
                if (attr.Max != null)
                {
                    result["MaxValue"] = attr.Max;
                }
                if (attr.MinLength > 0)
                {
                    result["MinSize"] = attr.MinLength;
                }
                if (attr.MaxLength > 0)
                {
                    result["Size"] = attr.MaxLength;
                }
                if (attr.Default != null)
                {
                    result["DefaultValue"] = attr.Default;
                }
                if (attr.ValueList.IsNotNullOrWhiteSpace())
                {
                    var vl = localizeString(schema, "LookupDict", attr.ValueList);
                    result["LookupDict"] = FieldAttribute.ParseValueListString(vl);
                }
                if (attr.Kind != DataKind.Text)
                {
                    result["Kind"] = mapKind(attr.Kind);
                }
            }

            if (attr.Metadata != null)
            {
                foreach (var fn in METADATA_FIELDS)
                {
                    var mv = attr.Metadata.AttrByName(fn).Value;
                    if (mv.IsNullOrWhiteSpace())
                    {
                        continue;
                    }

                    if (fn == "Description" || fn == "Placeholder" || fn == "LookupDict" || fn == "Hint")
                    {
                        mv = localizeString(schema, fn, mv);
                    }

                    result[fn] = mv;
                }
            }


            return(result);
        }
Example #32
0
		/// <summary>
		/// Initializes a new instance of the <see cref="FieldModel"/> class.
		/// </summary>
		/// <param name="field">The field.</param>
		/// <param name="att">The att.</param>
		public FieldModel(FieldInfo field, FieldAttribute att)
		{
			this.field = field;
			this.att = att;
		}
Example #33
0
 /// <summary>
 /// Adds a new Field to this collection.
 /// </summary>
 /// <param name="name">Name of the field to add</param>
 /// <param name="dataType">Data type of the field to add</param>
 /// <param name="fieldAttributes">Attributes on the field to add</param>
 public void Append(string name, DataType dataType, FieldAttribute fieldAttributes)
 {
     Append(name, dataType, null, fieldAttributes);
 }
Example #34
0
        private dynamic GetAvroField(ITypeSymbol type, FieldAttribute fieldAttribute, bool isNullable = false, bool isArray = false)
        {
            dynamic field = new JObject();

            if (type.Equals(_wellKnownTypes.StringType) || type.Equals(_wellKnownTypes.GuidType) || type.Equals(_wellKnownTypes.TimeSpanType))
            {
                field = Convert.String(fieldAttribute.Name);
            }
            else if (type.Equals(_wellKnownTypes.ByteType))
            {
                field = Convert.ByteArray(fieldAttribute.Name);
            }
            else if (type.Equals(_wellKnownTypes.DateTimeType))
            {
                field = Convert.DateTime(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.DateTimeOffsetType))
            {
                field = Convert.String(fieldAttribute.Name);
            }
            else if (type.Equals(_wellKnownTypes.BooleanType))
            {
                field = Convert.Boolean(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.Int16Type) || type.Equals(_wellKnownTypes.Int32Type))
            {
                field = Convert.Int(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.Int64Type))
            {
                field = Convert.Long(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.DecimalType))
            {
                field = Convert.Decimal(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.DoubleType))
            {
                field = Convert.Double(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.FloatType))
            {
                field = Convert.Float(fieldAttribute.Name, isNullable);
            }
            else if (type.Equals(_wellKnownTypes.ByteArrayType))
            {
                field = Convert.ByteArray(fieldAttribute.Name);
            }
            else if (type.OriginalDefinition.Equals(_wellKnownTypes.NullableType))
            {
                var innerType = (type as INamedTypeSymbol)?.TypeArguments[0];
                field = GetAvroField(innerType, fieldAttribute, true);
            }
            else if (type.TypeKind.Equals(TypeKind.Array) || _wellKnownTypes.GenericCollectionTypes.Any(t => t.Name.Equals(type.Name)))
            {
                field.name = fieldAttribute.Name;

                var arrayType = new JObject
                {
                    ["type"] = "array"
                };

                var innerType = type.TypeKind.Equals(TypeKind.Array)
                    ? ((IArrayTypeSymbol)type).ElementType
                    : (type as INamedTypeSymbol)?.TypeArguments[0];

                arrayType["items"] = _alreadyRegistered.Contains($"{innerType?.ContainingNamespace}.{innerType?.Name}")
                    ? innerType?.Name
                    : GetAvroField(innerType, fieldAttribute, isArray: true).type;

                field.type = arrayType;
            }
            else if (type.BaseType != null && type.BaseType.Equals(_wellKnownTypes.EnumType))
            {
                field = Convert.Enum(fieldAttribute.Name, type, fieldAttribute.DefaultValue);
            }
            else if (_wellKnownTypes.LocalTypes.Contains(type))
            {
                field.name = fieldAttribute.Name;
                field.type = GenerateChildSchema(type, isArray);
            }
            else
            {
                throw new CodeGenerationException($"Unsupported type {type}");
            }

            if (!string.IsNullOrWhiteSpace(fieldAttribute.Documentation))
            {
                field.doc = fieldAttribute.Documentation;
            }

            return(field);
        }
Example #35
0
        public virtual void InitByType(Type type, object data, bool modelOnly = false, string htmlFieldName = "", object additionalViewData = null)
        {
            type = Store.GetEnumerableGenericType(type);

            if (data is IEnumerable)
            {
                data = null;
            }

            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(delegate { return(data); }, type);

            if (metadata != null)
            {
                ResourcesRegistrator registrator = metadata.AdditionalValues.ContainsKey(ClientResourceAttribute.KEY) ? (ResourcesRegistrator)metadata.AdditionalValues[ClientResourceAttribute.KEY] : null;

                if (registrator != null)
                {
                    this.Controls.Add(registrator);
                }

                HtmlHelper html = Ext.Net.X.Builder.HtmlHelper;

                ViewDataDictionary viewData = new ViewDataDictionary(html.ViewDataContainer.ViewData)
                {
                    Model         = data,
                    ModelMetadata = metadata,
                    TemplateInfo  = new TemplateInfo
                    {
                        HtmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
                    }
                };

                if (additionalViewData != null)
                {
                    foreach (KeyValuePair <string, object> kvp in new RouteValueDictionary(additionalViewData))
                    {
                        viewData[kvp.Key] = kvp.Value;
                    }
                }

                HtmlHelper helper = new HtmlHelper(
                    new ViewContext(html.ViewContext, html.ViewContext.View, viewData, html.ViewContext.TempData, html.ViewContext.Writer),
                    new ViewDataContainer(viewData)
                    );

                foreach (ModelMetadata propertyMetadata in metadata.Properties)
                {
                    ModelFieldAttribute modelAttr = propertyMetadata.AdditionalValues.ContainsKey(ModelFieldAttribute.KEY) ? (ModelFieldAttribute)propertyMetadata.AdditionalValues[ModelFieldAttribute.KEY] : null;

                    if (!propertyMetadata.ShowForEdit)
                    {
                        continue;
                    }

                    if (modelAttr == null && this.InitForModelOnly)
                    {
                        continue;
                    }

                    FieldAttribute fieldAttr = propertyMetadata.AdditionalValues.ContainsKey(FieldAttribute.KEY) ? (FieldAttribute)propertyMetadata.AdditionalValues[FieldAttribute.KEY] : null;

                    if ((modelAttr != null && modelAttr.Ignore) || (fieldAttr != null && fieldAttr.Ignore))
                    {
                        continue;
                    }

                    if (propertyMetadata.TemplateHint.IsNotEmpty())
                    {
                        this.Items.Add(new MvcItem(delegate { return(EditorExtensions.Editor(helper, propertyMetadata.PropertyName, propertyMetadata.TemplateHint)); }));
                    }
                    else
                    {
                        Type fieldType = null;

                        if (fieldAttr != null && fieldAttr.FieldType != null)
                        {
                            fieldType = fieldAttr.FieldType;

                            if (!fieldType.IsSubclassOf(typeof(Ext.Net.Field)))
                            {
                                throw new Exception("FieldType must be subclass of Ext.Net.Field");
                            }
                        }
                        else
                        {
                            if (propertyMetadata.IsComplexType)
                            {
                                continue;
                            }

                            if (Store.IsDate(propertyMetadata.ModelType))
                            {
                                fieldType = typeof(Ext.Net.DateField);
                            }
                            else if (Store.IsNumeric(propertyMetadata.ModelType))
                            {
                                fieldType = typeof(Ext.Net.NumberField);
                            }
                            else if (Store.IsBoolean(propertyMetadata.ModelType))
                            {
                                fieldType = typeof(Ext.Net.Checkbox);
                            }
                            else
                            {
                                fieldType = typeof(Ext.Net.TextField);
                            }
                        }

                        Field cmp = (Ext.Net.Field)System.Activator.CreateInstance(fieldType);

                        cmp.ViewContext = helper.ViewContext;
                        cmp.ControlFor  = propertyMetadata.PropertyName;
                        cmp.SetControlFor(propertyMetadata);

                        this.Items.Add(cmp);
                    }
                }
            }
        }