Exemple #1
0
			public static EnumInfo GetInfo(Type enumType) {
				lock (cache) {
					EnumInfo info;
					if (!Enum.cache.TryGetValue(enumType, out info)) {
						info = new EnumInfo();
						Enum.Internal_GetInfo(enumType, out info.names, out info.values);
						Enum.cache.Add(enumType, info);
					}
					return info;
				}
			}
 private EnumInfo GetEnumInfo (Type enumType)
 {
     if (!_enumInfos.ContainsKey(enumType)) {
         var nameToVal = Enum.GetNames(enumType).Zip(
             Enum.GetValues(enumType).OfType<Enum>().Select(Convert.ToUInt64),
             (name, value) => new { name, value })
             .OrderBy(p => GetBitCount(p.value)).ThenBy(p => p.value);
         _enumInfos[enumType] = new EnumInfo {
             Names = nameToVal.Select(p => p.name).ToList(),
             Values = nameToVal.Select(p => p.value).ToList(),
         };
     }
     return _enumInfos[enumType];
 }
        private EnumInfo[] GetEnumInfos()
        {
            ArrayList enumInfoList = new ArrayList();

            foreach (ClassDefinition classDefinition in MappingConfiguration.Current.ClassDefinitions)
            {
                foreach (PropertyDefinition propertyDefinition in classDefinition.MyPropertyDefinitions)
                {
                    if (propertyDefinition.PropertyType.IsEnum)
                    {
                        EnumInfo enumInfo = new EnumInfo();
                        enumInfo.type = propertyDefinition.PropertyType;

                        enumInfoList.Add(enumInfo);
                    }
                }
            }

            #region Thanks to MK
            /*
            if (! File.Exists(_configuration.AssemblyName))
                throw new CodeGeneratorException(ErrorCode.AssemblyNotFound, _configuration.AssemblyName);

            Assembly assembly = Assembly.LoadFile(_configuration.AssemblyName);
            Type[] types = assembly.GetTypes();
            ArrayList enumInfoList = new ArrayList();

            foreach (Type type in types)
            {
                if (! type.IsEnum)
                    continue;

                EnumInfo enumInfo = new EnumInfo();
                enumInfo.type = type;

                enumInfoList.Add(enumInfo);
            }
            */
            #endregion

            return (EnumInfo[])enumInfoList.ToArray(typeof(EnumInfo));
        }
 private void BuildEnumFiles(EnumInfo[] enumInfos)
 {
     foreach (EnumInfo enumInfo in enumInfos)
         BuildEnumFile(enumInfo);
 }
Exemple #5
0
 public OrderSelection(EnumInfo<OrderFields> order, bool isDescending = false) {
     _order = order;
     _defaultDescending = isDescending;
     IsDescending = isDescending;
 }
Exemple #6
0
        static CacheEntry CreateCacheEntry(Type enumType)
        {
            CacheEntry entry;

            // First get the Resource Manager.

            var attrs = (LocalizedNameContainerAttribute[])
                        enumType.GetCustomAttributes(s_attrContnrType, false);

            if (attrs.Length == 0)
            {
                s_cache[enumType] = entry = new CacheEntry(null, null, false);
                return(entry);
            }

            var container = attrs[0].ResourceManager;
            var method    = container.GetProperty("ResourceManager",
                                                  BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null,
                                                  s_resMgrType, Type.EmptyTypes, new ParameterModifier[0]);

            if (method == null)
            {
                throw new InvalidOperationException("Cannot find ResourceManager in type " + container);
            }

            var resMgr = (ResourceManager)method.GetValue(null, null);

            if (resMgr == null)
            {
                throw new InvalidOperationException("Failed to access ResourceManager in " + container);
            }

            // Resource Manager retrieved, now get the fields.

            var fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            var ei     = new EnumInfo();

            foreach (var field in fields)
            {
                var obj = (IConvertible)field.GetRawConstantValue();

                long value;
                if (obj.GetTypeCode() == TypeCode.UInt64)
                {
                    value = (long)(ulong)obj;
                }
                else
                {
                    value = obj.ToInt64(null);
                }

                // Sometimes there are two fields with the same value
                if (ei.ContainsKey(value))
                {
                    continue;
                }

                ei.Add(value, field);
            }

            // Cache the found stuff

            s_cache[enumType] = entry = new CacheEntry(resMgr, ei, enumType.IsDefined(s_attrFlagsType, false));
            return(entry);
        }
Exemple #7
0
        private FlowFormField FieldFor <TProperty>(Expression <Func <TModel, TProperty> > expression, bool containsSection, FieldConfiguration fieldConfiguration = null)
        {
            /*
             * Renders a field for a non-boolean property of the model
             */

            fieldConfiguration = fieldConfiguration ?? new FieldConfiguration();

            if (fieldConfiguration.HideIfNull && fieldConfiguration.ReadOnly && GetValue(expression) == null)
            {
                return(null);
            }

            var htmlAttrs  = Helper.ObjectToDictionary(fieldConfiguration.HtmlAttributes);
            var type       = ElementType.Text;
            var grid       = default(Grid);
            var selectList = default(MultiSelectList);
            var metadata   = ModelMetadata.FromLambdaExpression(expression, _htmlHelper.ViewData);

            // Label
            var labelHtml = LabelHtml(expression, fieldConfiguration);

            if (fieldConfiguration.ReadOnly)
            {
                labelHtml = labelHtml.ReReplace(@"</?label.*?>", "", RegexOptions.IgnoreCase);
            }

            if (fieldConfiguration.ReadOnly && expression.ReturnType.Name != "Grid`1")
            {
                var value      = (GetValue(expression) ?? "?");
                var fi         = value.GetType().GetField(value.ToString());
                var attributes = fi != null ? (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false) : new DescriptionAttribute[] { };

                var stringValue = (attributes.Length > 0) ? attributes[0].Description : value.ToString();

                return(new FlowFormField(_writer, containsSection, labelHtml, (new HtmlString(stringValue)).ToString(), parentClass: fieldConfiguration.ParentClass));
            }

            var validators = metadata.GetValidators(_htmlHelper.ViewContext.Controller.ControllerContext);

            var classes = new ClassBuilder();

            if (htmlAttrs.ContainsKey("class"))
            {
                classes.Add((string)htmlAttrs["class"]);
            }

            if (metadata.IsRequired && (!metadata.ModelType.IsEnum || fieldConfiguration.Exclude == null || fieldConfiguration.Exclude.Length == 0))
            {
                classes.Add("required");
            }
            else
            {
                labelHtml = labelHtml.Replace("</label>", " <em>(Optional)</em></label>");
            }

            switch (metadata.DataTypeName)
            {
            case "Digits":
            case "CreditCard":
                classes.Add(metadata.DataTypeName.Replace("-", "").ToLower());
                break;

            case "IPAddress":
                classes.Add("ip-address");
                break;

            case "MultilineText":
                type = ElementType.TextArea;
                break;
            }
            switch (metadata.ModelType.Name)
            {
            case "Double":
                classes.Add("number");
                break;

            case "Int32":
                classes.Add("integer");
                break;

            case "Email":
                classes.Add("email");
                break;

            case "Password":
                type = ElementType.Password;
                break;

            case "Date":
                classes.Add("date");
                break;

            case "HttpPostedFileBase":
                htmlAttrs["type"] = "file";
                break;
            }

            if (metadata.ModelType.IsEnum && metadata.ModelType.IsDefined(typeof(FlagsAttribute), false))
            {
                type = ElementType.Select;
                var list           = (IEnumerable <object>)EnumInfo.CreateList(metadata.ModelType, fieldConfiguration.Exclude);
                var selectedValues = GetSelectedEnums((Enum)metadata.Model, fieldConfiguration.Exclude).ToList();
                selectList = new MultiSelectList(list, "Value", "Display", selectedValues);
            }
            else if (metadata.ModelType.IsEnum || (
                         metadata.ModelType.IsGenericType &&
                         metadata.ModelType.GetGenericTypeDefinition().FullName == "System.Nullable`1" &&
                         metadata.ModelType.GetGenericArguments()[0].IsEnum
                         ) || (
                         typeof(IEnumerable).IsAssignableFrom(metadata.ModelType) &&
                         !typeof(string).IsAssignableFrom(metadata.ModelType) &&
                         metadata.ModelType.GetGenericArguments()[0].IsEnum
                         )
                     )
            {
                type = ElementType.Select;
                var list           = (IEnumerable <object>)EnumInfo.CreateList(metadata.ModelType.IsGenericType ? metadata.ModelType.GetGenericArguments()[0] : metadata.ModelType, fieldConfiguration.Exclude);
                var selectedValues = GetSelected(metadata.Model);
                selectList = new MultiSelectList(list, "Value", "Display", selectedValues);
            }

            foreach (var rule in validators.SelectMany(v => v.GetClientValidationRules()))
            {
                switch (rule.ValidationType)
                {
                case "range":
                    classes.Add(string.Format("range([{0},{1}])", rule.ValidationParameters["min"], rule.ValidationParameters["max"]));
                    break;

                case "min":
                    classes.Add(string.Format("min({0})", rule.ValidationParameters["min"]));
                    break;

                case "max":
                    classes.Add(string.Format("max({0})", rule.ValidationParameters["max"]));
                    break;

                case "regex":
                    classes.Add(string.Format("match(/{0}/)", rule.ValidationParameters["pattern"]));
                    break;

                case "length":
                case "maxlength":
                    if (type == ElementType.Text || type == ElementType.Password)
                    {
                        htmlAttrs["maxlength"] = rule.ValidationParameters["max"];
                    }
                    else
                    {
                        classes.Add(string.Format("maxlength({0})", rule.ValidationParameters["max"]));
                    }
                    break;

                case "minlength":
                    classes.Add(string.Format("minlength({0})", rule.ValidationParameters["min"]));
                    break;

                case "rangelength":
                    classes.Add(string.Format("rangelength([{0},{1}])", rule.ValidationParameters["min"], rule.ValidationParameters["max"]));
                    break;

                case "equalto":
                    classes.Add(string.Format("equalTo('#{0}')", rule.ValidationParameters["other"].ToString().Split('.')[1]));
                    labelHtml = labelHtml.Replace(" <em>(Optional)</em>", "");
                    break;

                case "existsin":
                    type       = ElementType.Select;
                    selectList = GetSelectListFromCollection(expression, metadata, rule);
                    break;

                case "grid":
                    grid = GetGrid(expression, metadata, rule);
                    break;

                case "notrequired":
                    labelHtml = labelHtml.Replace(" <em>(Optional)</em>", "");
                    break;

                case "filetype":
                    classes.Add(string.Format("accept('{0}')", rule.ValidationParameters["extension"]));
                    fieldConfiguration.Tip = fieldConfiguration.Tip ?? string.Format("Filetype must be: {0}", rule.ValidationParameters["pretty-extension"]);
                    break;
                }
            }

            if (classes.ToString().Trim() != "")
            {
                htmlAttrs["class"] = classes.ToString();
            }

            if (fieldConfiguration.As.HasValue)
            {
                var validOverride        = false;
                var overrideErrorMessage = "";
                switch (type)
                {
                case ElementType.Select:
                    switch (fieldConfiguration.As.Value)
                    {
                    case ElementType.Checkboxes:
                    case ElementType.RadioButtons:
                    case ElementType.Text:
                        type          = fieldConfiguration.As.Value;
                        validOverride = true;
                        break;
                    }
                    break;

                case ElementType.Text:
                    switch (fieldConfiguration.As.Value)
                    {
                    case ElementType.Checkboxes:
                    case ElementType.RadioButtons:
                    case ElementType.Select:
                        if (fieldConfiguration.PossibleValues != null)
                        {
                            selectList    = fieldConfiguration.PossibleValues;
                            type          = fieldConfiguration.As.Value;
                            validOverride = true;
                        }
                        else
                        {
                            overrideErrorMessage = "I was expecting a list.";
                        }
                        break;
                    }
                    break;
                }
                if (!validOverride)
                {
                    throw new ApplicationException(string.Format("FieldConfiguration{{ As = {0} }} not valid for field: {1} (which defaults to {2}). {3}",
                                                                 fieldConfiguration.As.Value, expression, type, overrideErrorMessage));
                }
            }

            var elementHtml = string.Empty;
            var errorHtml   = string.Empty;
            var isValid     = true;

            if (grid != null)
            {
                elementHtml = RenderGrid(grid, fieldConfiguration.ReadOnly);
                isValid     = GetErrors(expression, out errorHtml);
            }
            else
            {
                switch (type)
                {
                case ElementType.Text:
                    elementHtml = _htmlHelper.TextBoxFor(expression, htmlAttrs).ToHtmlString();
                    break;

                case ElementType.Password:
                    elementHtml = _htmlHelper.PasswordFor(expression, htmlAttrs).ToHtmlString();
                    break;

                case ElementType.TextArea:
                    elementHtml = _htmlHelper.TextAreaFor(expression, htmlAttrs).ToHtmlString();
                    break;

                case ElementType.Select:
                    if (typeof(IEnumerable).IsAssignableFrom(metadata.ModelType) &&
                        !typeof(string).IsAssignableFrom(metadata.ModelType))
                    {
                        elementHtml = _htmlHelper.ListBoxFor(expression, selectList, htmlAttrs).ToHtmlString();
                    }
                    else
                    {
                        elementHtml = _htmlHelper.DropDownListFor(expression, selectList, fieldConfiguration.Label, htmlAttrs).ToHtmlString();
                    }
                    break;

                case ElementType.Checkboxes:
                case ElementType.RadioButtons:
                    // TODO: Use HTML Attributes
                    var typeString = type == ElementType.Checkboxes ? "checkbox" : "radio";
                    elementHtml += HelperDefinitions.BeginInputList(typeString);
                    elementHtml += string.Join("", selectList.Select(i => HelperDefinitions.InputListItem(typeString, expression.GetFieldName(), i.Value, i.Text, i.Selected).ToString()));
                    elementHtml += HelperDefinitions.EndInputList();
                    break;
                }
                isValid = GetErrors(expression, out errorHtml);
            }

            elementHtml = (fieldConfiguration.Before ?? "") + elementHtml + (fieldConfiguration.After ?? "");

            return(new FlowFormField(_writer, containsSection, labelHtml, elementHtml, errorHtml, isValid, fieldConfiguration.Hint, fieldConfiguration.Tip, fieldConfiguration.HideTip, fieldConfiguration.HintClass, fieldConfiguration.ParentClass, fieldConfiguration.DisplayFieldName));
        }
Exemple #8
0
        // Token: 0x060013CD RID: 5069 RVA: 0x00068C14 File Offset: 0x00066E14
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull(type, "type");
            string typeId  = this.GetTypeId(type, false);
            string typeId2 = this.GetTypeId(type, true);

            if (!StringUtils.IsNullOrEmpty(typeId))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        schema.Type |= JsonSchemaType.Null;
                    }
                    if (required)
                    {
                        bool?required2 = schema.Required;
                        if (!(required2.GetValueOrDefault() & required2 != null))
                        {
                            schema.Required = new bool?(true);
                        }
                    }
                    return(schema);
                }
            }
            if (this._stack.Any((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type))
            {
                throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
            }
            JsonContract jsonContract = this.ContractResolver.ResolveContract(type);
            bool         flag         = (jsonContract.Converter ?? jsonContract.InternalConverter) != null;

            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (typeId2 != null)
            {
                this.CurrentSchema.Id = typeId2;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (flag)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                switch (jsonContract.ContractType)
                {
                case JsonContractType.Object:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
                    break;

                case JsonContractType.Array:
                    {
                        this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                        this.CurrentSchema.Id   = this.GetTypeId(type, false);
                        JsonArrayAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type);
                        bool flag2 = cachedAttribute == null || cachedAttribute.AllowNullItems;
                        Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                        if (collectionItemType != null)
                        {
                            this.CurrentSchema.Items = new List <JsonSchema>();
                            this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag2) ? Required.Always : Required.Default, false));
                        }
                        break;
                    }

                case JsonContractType.Primitive:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                    JsonSchemaType?type2 = this.CurrentSchema.Type;
                    if ((type2.GetValueOrDefault() == JsonSchemaType.Integer & type2 != null) && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        this.CurrentSchema.Enum = new List <JToken>();
                        EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(type);
                        for (int i = 0; i < enumValuesAndNames.Names.Length; i++)
                        {
                            ulong  value = enumValuesAndNames.Values[i];
                            JToken item  = JToken.FromObject(Enum.ToObject(type, value));
                            this.CurrentSchema.Enum.Add(item);
                        }
                    }
                    break;
                }

                case JsonContractType.String:
                {
                    JsonSchemaType value2 = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired);
                    this.CurrentSchema.Type = new JsonSchemaType?(value2);
                    break;
                }

                case JsonContractType.Dictionary:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    Type type3;
                    Type type4;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out type3, out type4);
                    if (type3 != null && this.ContractResolver.ResolveContract(type3).ContractType == JsonContractType.Primitive)
                    {
                        this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type4, Required.Default, false);
                    }
                    break;
                }

                case JsonContractType.Dynamic:
                case JsonContractType.Linq:
                    this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
                    break;

                case JsonContractType.Serializable:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
                    break;

                default:
                    throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract));
                }
            }
            return(this.Pop().Schema);
        }
Exemple #9
0
        private object GetEnumValue(EnumInfo enumInfo)
        {
            var value = enumInfo.EnumValues != null ? enumInfo.EnumValues[(Enum)BoundValue] : BoundValue;

            return(value);
        }
Exemple #10
0
        private static string GetFiledName(EnumInfo index)
        {
            List <string> list = index.PropertyName.Split('.', '-', '/').Where(o => !string.IsNullOrEmpty(o)).ToList();

            return(string.Join("", list.Select(o => char.ToUpperInvariant(o[0]) + o.Substring(1))));
        }
Exemple #11
0
 public static bool IsValid <T>(T value)
     where T : Enum
 {
     return(EnumInfo <T> .IsValid(value));
 }
Exemple #12
0
        public string GetCycle(string CycleId)
        {
            var pc = EnumInfo <PaymentCycle> .GetValue(CycleId);

            return(EnumInfo <PaymentCycle> .GetDescription(pc));
        }
        public static void SeedData(IdentityDBContext context)
        {
            Console.WriteLine("Applying database migrations...");

            context.Database.Migrate();

            Console.WriteLine("Seeding initial data...");

            bool            newEntry  = false;
            Maybe <AppUser> adminUser = context.AppUser.FirstOrDefault(e => e.Username == "*****@*****.**");

            if (adminUser.HasNoValue)
            {
                adminUser = new AppUser(
                    firstName: "Dhanuka",
                    lastName: "Jayasinghe",
                    username: Email.Create("*****@*****.**").Value,
                    password: Password.Create("Admin@#456").Value
                    );
                context.AppUser.Add(adminUser.Value);
                newEntry = true;
            }

            Maybe <AppPermission> iamAdminPermission = context.AppPermission.FirstOrDefault(e => e.Name == Permission.UserAccountAdmin.ToString());

            if (iamAdminPermission.HasNoValue)
            {
                iamAdminPermission = new AppPermission(
                    name: Permission.UserAccountAdmin.ToString(),
                    description: EnumInfo.GetDescription(Permission.UserAccountAdmin)
                    );
                context.AppPermission.Add(iamAdminPermission.Value);
                newEntry = true;
            }

            Maybe <AppGroup> adminGroup = context.AppGroup.FirstOrDefault(e => e.Name == SystemUserGroup.ADMIN.ToString());

            if (adminGroup.HasNoValue)
            {
                adminGroup = new AppGroup(SystemUserGroup.ADMIN.ToString(), "System administrator permissions");
                context.AppGroup.Add(adminGroup.Value);
                newEntry = true;
            }

            if (newEntry)
            {
                context.SaveChanges();
                newEntry = false;
            }

            if (!context.AppGroupPermission.Any(e => e.PermissionId == iamAdminPermission.Value.Id && e.AppGroupId == adminGroup.Value.Id))
            {
                AppGroupPermission groupPermission = new AppGroupPermission(iamAdminPermission, adminGroup);
                context.AppGroupPermission.Add(groupPermission);
                newEntry = true;
            }
            if (!context.AppUserGroup.Any(e => e.AppUserId == adminUser.Value.Id && e.AppGroupId == adminGroup.Value.Id))
            {
                AppUserGroup adminUserGroup = new AppUserGroup(adminUser, adminGroup);
                context.AppUserGroup.Add(adminUserGroup);
                newEntry = true;
            }

            if (newEntry)
            {
                context.SaveChanges();
            }

            Console.WriteLine("Seeding complete");
        }
Exemple #14
0
 /// <inheritdoc />
 protected override TEnum GetValue(object value)
 {
     return(EnumInfo <TEnum, TNumeric, TNumericProvider> .ToEnum((TNumeric)value));
 }
Exemple #15
0
 public static EnumInfo GetInfo(Type enumType)
 {
     EnumInfo info = new EnumInfo();
     Enum.Internal_GetInfo(enumType, out info.names, out info.values);
     return info;
 }
        /// <summary>
        ///   Generates additional enumerations used by the import or export methods.
        /// </summary>
        /// <returns><see cref="EnumInfo"/> array represnenting additional fields needed by the import/export methods. Can be empty.</returns>
        /// <exception cref="InvalidOperationException">An attempt was made to generate a boolean parsing method, but none of the valid boolean string pairs were allowed. At least one boolean string pair (Ex: 'true/false', 'yes/no', or '0/1') must be allowed.</exception>
        public override EnumInfo[] GenerateAdditionalEnums()
        {
            if (!AllowTrueFalseStrings && !AllowZeroOneStrings && !AllowYesNoStrings)
                throw new InvalidOperationException("An attempt was made to generate a boolean parsing method, but none of the valid boolean string pairs were allowed. At least one boolean string pair (Ex: 'true/false', 'yes/no', or '0/1') must be allowed.");

            int count = 0;
            if (AllowTrueFalseStrings)
                count++;
            if (AllowYesNoStrings)
                count++;
            if (AllowZeroOneStrings)
                count++;

            if (count < 2)
                return new EnumInfo[0];

            EnumInfo enumInfo = new EnumInfo
            (
                "public",
                string.Format("{0}", GetEnumTypeName(mInfo.PropertyName)),
                string.Format("Represents the types the {0} can be parsed with", mInfo.PropertyName)
            );

            if (AllowTrueFalseStrings)
                enumInfo.Values.Add(new EnumValueInfo("TrueFalse", null, "Boolean represented as 'True' or 'False'."));
            if(AllowYesNoStrings)
                enumInfo.Values.Add(new EnumValueInfo("YesNo", null, "Boolean represented as 'Yes' or 'No'."));
            if(AllowZeroOneStrings)
                enumInfo.Values.Add(new EnumValueInfo("ZeroOne", null, "Boolean represented as '0' or '1'."));
            return new EnumInfo[] { enumInfo };
        }
        public override EnumInfo[] GenerateAdditionalEnums()
        {
            if (!AllowColonSeparator && !AllowDashSeparator && !AllowDotSeparator)
                return new EnumInfo[0];

            EnumInfo[] enums = new EnumInfo[1];
            enums[0] = new EnumInfo(
                "public",
                GetEnumTypeName(mInfo.PropertyName),
                "Enumerates the various MAC Address formats that can be parsed into a PhysicalAddress"
            );
            enums[0].Values.Add(new EnumValueInfo("NoSeparator", null, "Only the hexadecimal values are provided, no separators (Ex: MMMMMMSSSSSS)."));

            if (AllowColonSeparator)
                enums[0].Values.Add(new EnumValueInfo("Colon", null, "Each byte of the address is separated by a colon (':') (Ex: MM:MM:MM:SS:SS:SS)."));

            if (AllowDashSeparator)
                enums[0].Values.Add(new EnumValueInfo("Dash", null, "Each byte of the address is separated by a dash ('-') (Ex: MM-MM-MM-SS-SS-SS)."));

            if (AllowDotSeparator)
                enums[0].Values.Add(new EnumValueInfo("Period", null, "Triplets of the address are separated by periods ('.'). Address is composed of four triplets (Ex: MMM.MMM.SSS.SSS)."));

            return enums;
        }
Exemple #18
0
 public EnumValue(EnumInfo info)
 {
     this.info = info;
 }
        public TEnum Read(ref Utf8JsonReader reader)
        {
            var token = reader.TokenType;

            if (token == JsonTokenType.String)
            {
                string enumString = reader.GetString() !;

                // Case sensitive search attempted first.
                if (_TransformedToRaw.TryGetValue(enumString, out var enumInfo))
                {
                    return(enumInfo.EnumValue);
                }

                if (_IsFlags)
                {
                    ulong calculatedValue = 0;

#if NETSTANDARD2_0
                    string[] flagValues = enumString.Split(s_Split, StringSplitOptions.None);
#else
                    string[] flagValues = enumString.Split(", ");
#endif
                    foreach (string flagValue in flagValues)
                    {
                        // Case sensitive search attempted first.
                        if (_TransformedToRaw.TryGetValue(flagValue, out enumInfo))
                        {
                            calculatedValue |= enumInfo.RawValue;
                        }
                        else
                        {
                            // Case insensitive search attempted second.
                            var matched = false;
                            foreach (var enumItem in _TransformedToRaw)
                            {
                                if (string.Equals(enumItem.Key, flagValue, StringComparison.OrdinalIgnoreCase))
                                {
                                    calculatedValue |= enumItem.Value.RawValue;
                                    matched          = true;
                                    break;
                                }
                            }

                            if (!matched)
                            {
                                throw GenerateJsonException(_EnumType, flagValue);
                            }
                        }
                    }

                    var enumValue = (TEnum)Enum.ToObject(_EnumType, calculatedValue);
                    if (_TransformedToRaw.Count < 64)
                    {
                        _TransformedToRaw[enumString] = new EnumInfo(enumString, enumValue, calculatedValue);
                    }
                    return(enumValue);
                }

                // Case insensitive search attempted second.
                foreach (var enumItem in _TransformedToRaw)
                {
                    if (string.Equals(enumItem.Key, enumString, StringComparison.OrdinalIgnoreCase))
                    {
                        return(enumItem.Value.EnumValue);
                    }
                }

                throw GenerateJsonException(_EnumType, enumString);
            }

            if (token != JsonTokenType.Number || !_AllowIntegerValues)
            {
                throw GenerateJsonException(_EnumType);
            }

            switch (_EnumTypeCode)
            {
            case TypeCode.Int32:
                if (reader.TryGetInt32(out var int32))
                {
                    return((TEnum)Enum.ToObject(_EnumType, int32));
                }
                break;

            case TypeCode.Int64:
                if (reader.TryGetInt64(out var int64))
                {
                    return((TEnum)Enum.ToObject(_EnumType, int64));
                }
                break;

            case TypeCode.Int16:
                if (reader.TryGetInt16(out var int16))
                {
                    return((TEnum)Enum.ToObject(_EnumType, int16));
                }
                break;

            case TypeCode.Byte:
                if (reader.TryGetByte(out var ubyte8))
                {
                    return((TEnum)Enum.ToObject(_EnumType, ubyte8));
                }
                break;

            case TypeCode.UInt32:
                if (reader.TryGetUInt32(out var uint32))
                {
                    return((TEnum)Enum.ToObject(_EnumType, uint32));
                }
                break;

            case TypeCode.UInt64:
                if (reader.TryGetUInt64(out var uint64))
                {
                    return((TEnum)Enum.ToObject(_EnumType, uint64));
                }
                break;

            case TypeCode.UInt16:
                if (reader.TryGetUInt16(out var uint16))
                {
                    return((TEnum)Enum.ToObject(_EnumType, uint16));
                }
                break;

            case TypeCode.SByte:
                if (reader.TryGetSByte(out var byte8))
                {
                    return((TEnum)Enum.ToObject(_EnumType, byte8));
                }
                break;
            }

            throw GenerateJsonException(_EnumType);
        }
Exemple #20
0
        static string GetName(long value, ResourceManager resources, EnumInfo info, bool checkForFlags)
        {
            object obj;

            if (!info.TryGetValue(value, out obj))
            {
                if (checkForFlags)
                {
                    ulong uvalue  = (ulong)value;
                    var   builder = new StringBuilder(1024);

                    bool  builderEmpty = true;
                    ulong bit          = 1;
                    for (int i = 0; i < sizeof(ulong) * 8; ++i, bit <<= 1)
                    {
                        if ((uvalue & bit) != 0)
                        {
                            if (!builderEmpty)
                            {
                                builder.Append(", ");
                            }

                            builder.Append(GetName((long)bit, resources, info, false));
                            builderEmpty = false;
                        }
                    }

                    return(builder.ToString());
                }

                return(value.ToString());
            }

            var keyField = obj as Tuple <string, string>;

            if (keyField == null)
            {
                var plainName = obj as Tuple <string>;
                if (plainName != null)
                {
                    return(plainName.Item1);
                }

                var field = (FieldInfo)obj;
                var attrs = (LocalizedNameAttribute[])field.GetCustomAttributes(s_attrType, false);
                if (attrs.Length == 0)
                {
                    info[value] = new Tuple <string>(field.Name);
                    return(field.Name);
                }

                info[value] = keyField = new Tuple <string, string>(attrs[0].Key, field.Name);
            }

            var result = resources.GetString(keyField.Item1);

            if (string.IsNullOrEmpty(result))
            {
                result = keyField.Item2;
            }
            return(result);
        }
        public void Write(Utf8JsonWriter writer, TEnum value)
        {
            if (_RawToTransformed.TryGetValue(value, out var enumInfo))
            {
                writer.WriteStringValue(enumInfo.Name);
                return;
            }

            var rawValue = GetEnumValue(value);

            if (_IsFlags)
            {
                ulong calculatedValue = 0;

                StringBuilder Builder = new();
                foreach (var enumItem in _RawToTransformed)
                {
                    enumInfo = enumItem.Value;
                    if (!value.HasFlag(enumInfo.EnumValue) ||
                        enumInfo.RawValue == 0)    // Definitions with 'None' should hit the cache case.
                    {
                        continue;
                    }

                    // Track the value to make sure all bits are represented.
                    calculatedValue |= enumInfo.RawValue;

                    if (Builder.Length > 0)
                    {
                        Builder.Append(", ");
                    }
                    Builder.Append(enumInfo.Name);
                }

                if (calculatedValue == rawValue)
                {
                    string finalName = Builder.ToString();
                    if (_RawToTransformed.Count < 64)
                    {
                        _RawToTransformed[value] = new EnumInfo(finalName, value, rawValue);
                    }
                    writer.WriteStringValue(finalName);
                    return;
                }
            }

            if (!_AllowIntegerValues)
            {
                throw new JsonException(
                          $"Enum type {_EnumType} does not have a mapping for integer value '{rawValue.ToString(CultureInfo.CurrentCulture)}'.");
            }

            switch (_EnumTypeCode)
            {
            case TypeCode.Int32:
                writer.WriteNumberValue((int)rawValue);
                break;

            case TypeCode.Int64:
                writer.WriteNumberValue((long)rawValue);
                break;

            case TypeCode.Int16:
                writer.WriteNumberValue((short)rawValue);
                break;

            case TypeCode.Byte:
                writer.WriteNumberValue((byte)rawValue);
                break;

            case TypeCode.UInt32:
                writer.WriteNumberValue((uint)rawValue);
                break;

            case TypeCode.UInt64:
                writer.WriteNumberValue(rawValue);
                break;

            case TypeCode.UInt16:
                writer.WriteNumberValue((ushort)rawValue);
                break;

            case TypeCode.SByte:
                writer.WriteNumberValue((sbyte)rawValue);
                break;

            default:
                throw new JsonException();     // GetEnumValue should have already thrown.
            }
        }
        protected void ParseEnum(string line, StringReader rdr, Globals globals, ref int currentLine)
        {
            string[] nameparts = line.Split(' ');
            string enumName = nameparts[1];
            List<string> enumValues = new List<string>();
            while ((line = rdr.ReadLine()) != null) {
                string defName = "";
                int lineNumber = 0;
                ExtractLineInfo(ref line, out defName, out lineNumber);

                ++currentLine;
                if (line.StartsWith("}")) {
                    EnumInfo ret = new EnumInfo { Name = enumName };
                    ret.Values.AddRange(enumValues);
                    globals.AddTypeInfo(enumName, ret);
                    return;
                } else if (line.Contains(',')) {
                    int sub = line.IndexOf(',');
                    enumValues.Add(line.Substring(0, sub));
                }
            }
        }
Exemple #23
0
 public EnumListDataFieldVM(ModuleDef ownerModule, Action <DataFieldVM> onUpdated)
     : this(ownerModule, EnumInfo.CreateNullArray(null), onUpdated)
 {
 }
        /// <summary>
        ///   Generates additional enumerations used by the import or export methods.
        /// </summary>
        /// <returns><see cref="EnumInfo"/> array represnenting additional fields needed by the import/export methods. Can be empty.</returns>
        /// <exception cref="InvalidOperationException">An attempt was made to generate a boolean parsing method, but none of the valid boolean string pairs were allowed. At least one boolean string pair (Ex: 'true/false', 'yes/no', or '0/1') must be allowed.</exception>
        public override EnumInfo[] GenerateAdditionalEnums()
        {
            if (TypeLookup.Count == 0)
                throw new InvalidOperationException("An attempt was made to generate enum code, but the number of enumerated items is zero.");
            ValidateLookup();

            EnumInfo enumInfo = new EnumInfo
            (
                "public",
                GetEnumTypeName(mInfo.PropertyName),
                string.Format("Enumerates the possible values of {0}.", mInfo.PropertyName)
            );

            // Get all the enumerated type names and their associated strings.
            Dictionary<string, string[]> lookup = GetEnumNamesWithValues();
            foreach(string key in lookup.Keys)
                enumInfo.Values.Add(new EnumValueInfo(key, null, GetEnumDescription(lookup[key])));

            List<EnumInfo> enumList = new List<EnumInfo>();
            enumList.Add(enumInfo);

            foreach(string key in lookup.Keys)
            {
                if(lookup[key].Length > 1)
                {
                    // This enumerated item has multiple strings that will parse to it so create an individual enum for it.
                    enumInfo = new EnumInfo
                    (
                        "public",
                        string.Format("{0}Items", key),
                        string.Format("Enumerates the possible string values that can be parse to {0}.", key)
                    );

                    for (int i = 0; i < lookup[key].Length; i++)
                        enumInfo.Values.Add(new EnumValueInfo(string.Format("Option{0}", i.ToString()), null, string.Format("Specified when the '{0}' string is found in the XML.", lookup[key][i])));
                    enumList.Add(enumInfo);
                }
            }

            return enumList.ToArray();
        }
Exemple #25
0
 public EnumListDataFieldVM(ModuleDef ownerModule, EnumInfo value, Action <DataFieldVM> onUpdated)
     : base(ownerModule, value, onUpdated)
 {
 }
        private void BuildEnumFile(EnumInfo enumInfo)
        {
            foreach (Configuration.FileInfo fileInfo in _configuration.EnumFileInfos)
            {
                string name = enumInfo.type.Name;
                string templateFileName = Path.Combine(_configuration.TemplateRoot, fileInfo.template);

                string targetFileName = Path.Combine(_configuration.TargetRoot, Replace(fileInfo.target, DefinedPlaceholder.DOMAIN_ENUMNAME, name));
                targetFileName = Replacer.Replace(_configuration.ProjectReplaceInfos, targetFileName);

                CheckExistenceTemplateFile(templateFileName);
                CheckExistenceDestinationFile(targetFileName, fileInfo.overwrite);

                Replacer replacer = new Replacer(templateFileName);

                // for each enum value
                /* --- still not needed at the moment --- */

                // common
                replacer.Replace(DefinedPlaceholder.DOMAIN_ENUMNAME, name);
                ReplaceCommon(replacer, enumInfo.type);

                replacer.Save(targetFileName);
            }
        }
Exemple #27
0
        public override bool Perform(Node node)
        {
            if (!base.Perform(node))
            {
                return(false);
            }
            if (node.fromSave)
            {
                return(true);
            }
            var input = node.inputPorts[0].GetData <Type>();
            // Action targets
            var targets        = node.inputPorts[1].GetDataList <TypeMethod>();
            var foundPorts     = FoundPorts(node);
            var targetMethods  = targets.ConvertAll(t => t.method);
            var ToilGenerators = new List <(MethodInfo generator, List <MethodInfo> actions)>();

            // Search for Toil generators
            foreach (Type type in input)
            {
                foreach (MethodInfo method in AccessTools.GetDeclaredMethods(type).Where(t => t.ReturnType == typeof(Toil)))
                {
                    if (SearchToilGenerator(method, targetMethods, out List <MethodInfo> ActionsFound))
                    {
                        ToilGenerators.Add((method, ActionsFound));
                    }
                }
            }
            // Search for Toils in MakeNewToils
            foreach (Type type in input)
            {
                var MakeNewToils = AccessTools.Method(type, "MakeNewToils");
                foreach (Type nType in type.GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (nType.GetInterfaces()?.Any(t => t == typeof(IEnumerator <Toil>)) == true)
                    {
                        var interfaceMap = nType.GetInterfaceMap(typeof(IEnumerator));
                        var MoveNext     = AccessTools.Method(nType, "MoveNext");
                        var get_Current  = nType.GetInterfaceMap(typeof(IEnumerator <Toil>)).TargetMethods.First();
                        var Current      = GetFieldInfo(get_Current);
                        var enumInfo     = new EnumInfo(Current, null);
                        if (SearchMoveNext(MoveNext, targetMethods, ToilGenerators, ref enumInfo, out var SearchResults, out var toilInfo))
                        {
                            foundPorts[0].AddData(type);
                            ResultA(foundPorts).AddData(new TypeMethod(type, nType, MoveNext));
                            ResultB(foundPorts).AddData(SearchResults);
                            ResultC(foundPorts).AddData(toilInfo);
                            var actions = SearchResults.SelectMany(t => t.target).ToList();
                            actions.RemoveDuplicates();
                            ResultD(foundPorts).AddData(actions);
                            NodeUtility.enumerableItems.SetOrAdd(MoveNext, toilInfo);
                            ResultE(foundPorts).AddData(enumInfo);
                        }
                        break;
                    }
                }
            }
            var foundActions = ResultB(foundPorts).GetData <List <EnumItemPos <SavedList <MethodInfo> > > >().SelectMany(t => t.SelectMany(tt => tt.target)).ToList();

            foundActions.RemoveDuplicates();
            foundPorts[1].SetData(targets.Where(t => foundActions.Contains(t.method)).ToList());
            return(true);
        }
        private void BuildGlobalFiles(ClassInfo[] classInfos, EnumInfo[] enumInfos)
        {
            foreach (Configuration.FileInfo fileInfo in _configuration.AllGlobalFileInfos)
            {
                string templateFileName = Path.Combine(_configuration.TemplateRoot, fileInfo.template);

                string targetFileName = Path.Combine(_configuration.TargetRoot, fileInfo.target);
                targetFileName = Replacer.Replace(_configuration.ProjectReplaceInfos, targetFileName);

                CheckExistenceTemplateFile(templateFileName);
                CheckExistenceDestinationFile(targetFileName, fileInfo.overwrite);

                IBusinessObjectClass[] businessObjectClasses = new IBusinessObjectClass[classInfos.Length];

                for (int index = 0; index < classInfos.Length; index++)
                    businessObjectClasses[index] = classInfos[index].objectClass;

                Replacer replacer = new Replacer(templateFileName);

                // for each class
                replacer.Include(
                        DefinedPlaceholder.INCLUDE_FOREACHCLASS,
                        GetClassInfos(businessObjectClasses));

                replacer.Repeat(
                        DefinedPlaceholder.REPEAT_FOREACHCLASS_BEGIN,
                        DefinedPlaceholder.REPEAT_FOREACHCLASS_END,
                        GetClassInfos(businessObjectClasses));

                // for each enum
                replacer.Include(
                        DefinedPlaceholder.INCLUDE_FOREACHENUM,
                        GetEnumInfos(enumInfos));

                replacer.Repeat(
                        DefinedPlaceholder.REPEAT_FOREACHENUM_BEGIN,
                        DefinedPlaceholder.REPEAT_FOREACHENUM_END,
                        GetEnumInfos(enumInfos));

                // common
                ReplaceCommon(replacer, classInfos[0].type);

                replacer.Save(targetFileName);
            }
        }
        /// <summary>
        /// 递归获取 Body 参数说明
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isShowRequired"></param>
        /// <returns></returns>
        private object GetModelInfo(string key, bool isShowRequired = true)
        {
            if (key == null)
            {
                return(null);
            }
            if (key != null && Schemas.ContainsKey(key) == false)
            {
                return(key);
            }
            var schema = Schemas.SingleOrDefault(x => x.Key == key).Value;

            if (schema.Properties.Any() == false)
            {
                return new EnumInfo()
                       {
                           枚举范围 = GetEnumValues(key),
                           枚举描述 = schema.Description,
                           枚举类型 = schema.Format,
                           枚举名称 = key
                       }
            }
            ;
            var properties = new Dictionary <string, object>();

            foreach (var item in schema.Properties)
            {
                object obj = "object";

                if (item.Value.IsObject(Schemas))
                {
                    var objKey = item.Value.Reference.Id;
                    if (objKey == key)
                    {
                        obj = objKey;
                    }
                    else
                    {
                        obj = GetModelInfo(objKey, isShowRequired);
                    }
                }
                else if (item.Value.IsArray())
                {
                    var arrayKey = "";
                    if (item.Value.IsBaseTypeArray())
                    {
                        arrayKey = item.Value.Items.Type;
                    }
                    else
                    {
                        arrayKey = item.Value.Items.Reference.Id;
                    }
                    obj = new[] { GetModelInfo(arrayKey, isShowRequired) };
                }
                else if (item.Value.IsEnum(Schemas))
                {
                    var enumKey = item.Value.Reference.Id;
                    var enumObj = GetEnumSchema(enumKey);
                    obj = new EnumInfo()
                    {
                        枚举范围 = GetEnumValues(enumKey),
                        枚举类型 = enumObj.Format,
                        枚举名称 = enumKey,
                        枚举描述 = enumObj.Description
                    };
                }
                else
                {
                    obj = item.Value.Format ?? item.Value.Type;
                }

                if (isShowRequired)
                {
                    var requestModelInfo = new RequestModelInfo
                    {
                        参数类型 = obj,
                        描述   = item.Value.Description,
                        是否必传 = schema.Required.Any(x => x == item.Key),
                        可空类型 = item.Value.Nullable
                    };
                    properties.Add(item.Key, requestModelInfo);
                }
                else
                {
                    var responseModelInfo = new ResponseModelInfo
                    {
                        参数类型 = obj,
                        描述   = item.Value.Description,
                        可空类型 = item.Value.Nullable
                    };
                    properties.Add(item.Key, responseModelInfo);
                }
            }
            return(properties);
        }
        private Replacer.ReplaceInfo[] GetEnumInfos(EnumInfo[] enums)
        {
            Replacer.ReplaceInfo[] enumInfos = new Replacer.ReplaceInfo[enums.Length];

            for (int index = 0; index < enums.Length; index++)
            {
                enumInfos[index].replaceInfos = new string[] {
                        Placeholder.ToString(DefinedPlaceholder.DOMAIN_ENUMNAME), enums[index].type.Name };
            }

            return enumInfos;
        }
        private static ApiModel ParseSwagger(SwaggerModel obj)
        {
            ApiModel result = new ApiModel();

            // Loop through all paths and spit them out to the console
            foreach (var path in (from p in obj.paths orderby p.Key select p))
            {
                foreach (var verb in path.Value)
                {
                    // Set up our API
                    ApiInfo api = new ApiInfo();
                    api.URI         = path.Key;
                    api.HttpVerb    = verb.Key;
                    api.Comment     = verb.Value.summary;
                    api.Params      = new List <ParameterInfo>();
                    api.QueryParams = new List <ParameterInfo>();
                    api.Category    = verb.Value.tags.FirstOrDefault();
                    api.OperationId = verb.Value.operationId.Replace("ApiV2", "");

                    // Now figure out all the URL parameters
                    foreach (var parameter in verb.Value.parameters)
                    {
                        // Query String Parameters
                        if (parameter.paramIn == "query")
                        {
                            api.QueryParams.Add(new ParameterInfo()
                            {
                                Comment   = parameter.description ?? "",
                                ParamName = parameter.name,
                                TypeName  = ResolveType(parameter, parameter.schema)
                            });

                            // URL Path parameters
                        }
                        else if (parameter.paramIn == "path")
                        {
                            api.Params.Add(new ParameterInfo()
                            {
                                Comment   = parameter.description ?? "",
                                ParamName = parameter.name,
                                TypeName  = ResolveType(parameter, parameter.schema)
                            });

                            // Body parameters
                        }
                        else if (parameter.paramIn == "body")
                        {
                            api.BodyParam = new ParameterInfo()
                            {
                                Comment   = parameter.description ?? "",
                                ParamName = "model",
                                TypeName  = ResolveType(parameter, parameter.schema)
                            };
                        }

                        // Is this property an enum?
                        if (parameter.EnumDataType != null)
                        {
                            ExtractEnum(result.Enums, parameter);
                        }
                    }

                    // Now figure out the response type
                    SwaggerResult ok = null;
                    if (verb.Value.responses.TryGetValue("200", out ok))
                    {
                        api.TypeName = ResolveType(null, ok.schema);
                    }
                    else if (verb.Value.responses.TryGetValue("201", out ok))
                    {
                        api.TypeName = ResolveType(null, ok.schema);
                    }

                    // Done with this API
                    result.Methods.Add(api);
                }
            }

            // Loop through all the schemas
            foreach (var def in obj.definitions)
            {
                var m = new ModelInfo()
                {
                    SchemaName = def.Key,
                    Comment    = def.Value.description,
                    Properties = new List <ParameterInfo>()
                };
                foreach (var prop in def.Value.properties)
                {
                    if (!prop.Value.required && def.Value.required != null)
                    {
                        prop.Value.required = def.Value.required.Contains(prop.Key);
                    }
                    m.Properties.Add(new ParameterInfo()
                    {
                        Comment   = prop.Value.description,
                        ParamName = prop.Key,
                        TypeName  = ResolveType(prop.Value, null)
                    });

                    // Is this property an enum?
                    if (prop.Value.EnumDataType != null)
                    {
                        ExtractEnum(result.Enums, prop.Value);
                    }
                }

                result.Models.Add(m);
            }

            // Now add the enums we know we need.
            // Because of the complex way this Dictionary<> is rendered in Swagger, it's hard to pick up the correct values.
            var tat = new EnumInfo()
            {
                EnumDataType = "TransactionAddressType",
                Items        = new List <EnumItem>()
            };

            tat.AddItem("ShipFrom", "This is the location from which the product was shipped");
            tat.AddItem("ShipTo", "This is the location to which the product was shipped");
            tat.AddItem("PointOfOrderAcceptance", "Location where the order was accepted; typically the call center, business office where purchase orders are accepted, server locations where orders are processed and accepted");
            tat.AddItem("PointOfOrderOrigin", "Location from which the order was placed; typically the customer's home or business location");
            tat.AddItem("SingleLocation", "Only used if all addresses for this transaction were identical; e.g. if this was a point-of-sale physical transaction");
            result.Enums.Add(tat);

            // Here's your processed API
            return(result);
        }
        public override EnumInfo[] GenerateAdditionalEnums()
        {
            if (!AllowBuild && !AllowRevision)
                return new EnumInfo[0];

            EnumInfo[] enums = new EnumInfo[1];
            enums[0] = new EnumInfo(
                "public",
                GetEnumTypeName(mInfo.PropertyName),
                "Enumerates the various version types that can be parsed into a version"
            );
            enums[0].Values.Add(new EnumValueInfo("MajorMinor", null, "Only the major and minor part were provided."));

            if(AllowBuild || AllowRevision)
                enums[0].Values.Add(new EnumValueInfo("MajorMinorBuild", null, "The major, minor, and build were provided."));

            if(AllowRevision)
                enums[0].Values.Add(new EnumValueInfo("MajorMinorBuildRevision", null, "The major, minor, build, and revision were provided."));
            return enums;
        }
 public Dictionary <PaymentCycle, string> GetCycles()
 {
     return(EnumInfo <PaymentCycle>
            .GetValues()
            .ToDictionary(o => o.Key, o => o.Value));
 }
Exemple #34
0
        private void SerializeBtn_Click(object sender, EventArgs e)
        {
            //var data = new ComplexObject
            //{
            //    Name = "Sample",
            //    Identifier = Guid.NewGuid(),
            //    Settings = new SerializableDictionary<string, string>
            //    {
            //        {"Name", "Fola"},
            //        {"Company", "MaritzCX"},
            //        {"Project", "Pledge"}
            //    }
            //};

            //var dataXml = data.SerializeToXml();

            //MessageBox.Show(@"Done");
            var data = EnumInfo.ParseEnum<EvaluationOrder>();
            var result = new EnumInfo(ResultType.Exception);

            MessageBox.Show($"{result.Value}");
        }
Exemple #35
0
 /// <summary>
 /// Execute this template against the specified model
 /// </summary>
 /// <param name="model"></param>
 /// <param name="m"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 public virtual string ExecuteTemplate(SwaggerInfo api, MethodInfo method, ModelInfo model, EnumInfo enumInfo)
 {
     Buffer.Clear();
     SwaggerModel = api;
     MethodModel  = method;
     ClassModel   = model;
     EnumModel    = enumInfo;
     Execute();
     return(Buffer.ToString());
 }