Esempio n. 1
0
        public override IType NormalizeTypeReference(IType type)
        {
            if (type == null)
            {
                return(null);
            }
            var enumType = type as EnumType;

            if (enumType != null && enumType.Name.Length == 0)
            {
                type = new PrimaryType(KnownPrimaryType.String)
                {
                    Name = "str"
                };
            }

            // Using Any instead of Contains since object hash is bound to a property which is modified during normalization
            if (_normalizedTypes.Any(item => type.Equals(item)))
            {
                return(_normalizedTypes.First(item => type.Equals(item)));
            }

            _normalizedTypes.Add(type);
            if (type is PrimaryType)
            {
                return(NormalizePrimaryType(type as PrimaryType));
            }
            if (type is SequenceType)
            {
                return(NormalizeSequenceType(type as SequenceType));
            }
            if (type is DictionaryType)
            {
                return(NormalizeDictionaryType(type as DictionaryType));
            }
            if (type is CompositeType)
            {
                return(NormalizeCompositeType(type as CompositeType));
            }
            if (type is EnumType)
            {
                return(NormalizeEnumType(type as EnumType));
            }


            throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture,
                                                          "Type {0} is not supported.", type.GetType()));
        }
Esempio n. 2
0
        public static String ImportedFrom(PrimaryType primaryType)
        {
            if (primaryType == null)
            {
                return(null);
            }

            if (primaryType == PrimaryType.Date ||
                primaryType.Name == "LocalDate")
            {
                return("org.joda.time.LocalDate");
            }
            else if (primaryType == PrimaryType.DateTime ||
                     primaryType.Name == "DateTime")
            {
                return("org.joda.time.DateTime");
            }
            else if (primaryType == PrimaryType.Decimal ||
                     primaryType.Name == "Decimal")
            {
                return("java.math.BigDecimal");
            }
            else if (primaryType == PrimaryType.DateTimeRfc1123 ||
                     primaryType.Name == "DateTimeRfc1123")
            {
                return("com.microsoft.rest.DateTimeRfc1123");
            }
            else if (primaryType == PrimaryType.Stream ||
                     primaryType.Name == "InputStream")
            {
                return("java.io.InputStream");
            }
            else if (primaryType == PrimaryType.ByteArray ||
                     primaryType.Name == "ByteArray")
            {
                return("org.apache.commons.codec.binary.Base64");
            }
            else if (primaryType == PrimaryType.TimeSpan ||
                     primaryType.Name == "Period")
            {
                return("org.joda.time.Period");
            }
            else
            {
                return(null);
            }
        }
Esempio n. 3
0
        public static string ImportPrimaryType(PrimaryType primaryType)
        {
            if (primaryType == null)
            {
                return(null);
            }

            if (primaryType.Type == KnownPrimaryType.Date ||
                primaryType.Name == "LocalDate")
            {
                return("org.joda.time.LocalDate");
            }
            else if (primaryType.Type == KnownPrimaryType.DateTime ||
                     primaryType.Name == "DateTime")
            {
                return("org.joda.time.DateTime");
            }
            else if (primaryType.Type == KnownPrimaryType.Decimal ||
                     primaryType.Name == "Decimal")
            {
                return("java.math.BigDecimal");
            }
            else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123 ||
                     primaryType.Name == "DateTimeRfc1123")
            {
                return("com.microsoft.rest.DateTimeRfc1123");
            }
            else if (primaryType.Type == KnownPrimaryType.Stream ||
                     primaryType.Name == "InputStream")
            {
                return("java.io.InputStream");
            }
            else if (primaryType.Type == KnownPrimaryType.TimeSpan ||
                     primaryType.Name == "Period")
            {
                return("org.joda.time.Period");
            }
            else if (primaryType.Type == KnownPrimaryType.Uuid || primaryType.Name == "Uuid")
            {
                return("java.util.UUID");
            }
            else
            {
                return(null);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Normalizes primary type.
        /// </summary>
        /// <param name="primaryType">Primary type to normalize.</param>
        /// <returns>Normalized primary type.</returns>
        private IType NormalizePrimaryType(PrimaryType primaryType)
        {
            if (primaryType == PrimaryType.Boolean)
            {
                primaryType.Name = "Boolean";
            }
            else if (primaryType == PrimaryType.ByteArray)
            {
                primaryType.Name = "Array";
            }
            else if (primaryType == PrimaryType.DateTime)
            {
                primaryType.Name = "DateTime";
            }
            else if (primaryType == PrimaryType.Double)
            {
                primaryType.Name = "Float";
            }
            else if (primaryType == PrimaryType.Int)
            {
                primaryType.Name = "Number";
            }
            else if (primaryType == PrimaryType.Long)
            {
                primaryType.Name = "Bignum";
            }
            else if (primaryType == PrimaryType.Stream)
            {
                //TODO: verify this
                primaryType.Name = "System.IO.Stream";
            }
            else if (primaryType == PrimaryType.String)
            {
                primaryType.Name = "String";
            }
            else if (primaryType == PrimaryType.TimeSpan)
            {
                primaryType.Name = "Duration";
            }
            else if (primaryType == PrimaryType.Object)
            {
                primaryType.Name = "Object";
            }

            return(primaryType);
        }
Esempio n. 5
0
        /// <summary>
        /// Determines if the given IType is a value type in C#
        /// </summary>
        /// <param name="type">The type to check</param>
        /// <returns>True if the type maps to a C# value type, otherwise false</returns>
        public static bool IsValueType(this IType type)
        {
            PrimaryType primaryType = type as PrimaryType;
            EnumType    enumType    = type as EnumType;

            return(enumType != null ||
                   (primaryType != null &&
                    (primaryType.Type == KnownPrimaryType.Boolean ||
                     primaryType.Type == KnownPrimaryType.DateTime ||
                     primaryType.Type == KnownPrimaryType.Date ||
                     primaryType.Type == KnownPrimaryType.Decimal ||
                     primaryType.Type == KnownPrimaryType.Double ||
                     primaryType.Type == KnownPrimaryType.Int ||
                     primaryType.Type == KnownPrimaryType.Long ||
                     primaryType.Type == KnownPrimaryType.TimeSpan ||
                     primaryType.Type == KnownPrimaryType.DateTimeRfc1123)));
        }
Esempio n. 6
0
 /// <summary>
 /// Returns the TypeScript type string for the specified primary type
 /// </summary>
 /// <param name="primary">primary type to query</param>
 /// <returns>The TypeScript type correspoinding to this model primary type</returns>
 private static string PrimaryTSType(this PrimaryType primary)
 {
     if (primary == PrimaryType.Boolean)
     {
         return("boolean");
     }
     else if (primary == PrimaryType.Double || primary == PrimaryType.Decimal || primary == PrimaryType.Int || primary == PrimaryType.Long)
     {
         return("number");
     }
     else if (primary == PrimaryType.String)
     {
         return("string");
     }
     else if (primary == PrimaryType.Date || primary == PrimaryType.DateTime || primary == PrimaryType.DateTimeRfc1123)
     {
         return("Date");
     }
     else if (primary == PrimaryType.Object)
     {
         return("any");   // TODO: test this
     }
     else if (primary == PrimaryType.ByteArray)
     {
         return("Buffer");
     }
     else if (primary == PrimaryType.Stream)
     {
         return("stream.Readable");
     }
     else if (primary == PrimaryType.TimeSpan)
     {
         return("moment.Duration"); //TODO: test this, add include for it
     }
     else if (primary == PrimaryType.Credentials)
     {
         return("ServiceClientCredentials"); //TODO: test this, add include for it
     }
     else
     {
         throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                                                         "Type '{0}' not implemented", primary));
     }
 }
Esempio n. 7
0
        public override string EscapeDefaultValue(string defaultValue, IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            PrimaryType primaryType = type as PrimaryType;

            if (defaultValue != null && primaryType != null)
            {
                if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
                {
                    return(QuoteValue(defaultValue, quoteChar: "'"));
                }
                else if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
                {
                    return(defaultValue.ToLowerInvariant());
                }
                else
                {
                    if (primaryType.KnownPrimaryType == KnownPrimaryType.Date ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.DateTime ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123 ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan)
                    {
                        return("Date.parse('" + defaultValue + "')");
                    }

                    if (primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray)
                    {
                        return("'" + defaultValue + "'.bytes.pack('C*')");
                    }
                }
            }

            EnumType enumType = type as EnumType;

            if (defaultValue != null && enumType != null)
            {
                return(QuoteValue(defaultValue, quoteChar: "'"));
            }
            return(defaultValue);
        }
Esempio n. 8
0
        public override string EscapeDefaultValue(string defaultValue, IType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            PrimaryType primaryType = type as PrimaryType;

            if (defaultValue != null && primaryType != null)
            {
                if (primaryType.Type == KnownPrimaryType.String)
                {
                    return(CodeNamer.QuoteValue(defaultValue));
                }
                else if (primaryType.Type == KnownPrimaryType.Boolean)
                {
                    if (defaultValue == "true")
                    {
                        return("True");
                    }
                    else
                    {
                        return("False");
                    }
                }
                else
                {
                    if (primaryType.Type == KnownPrimaryType.Date ||
                        primaryType.Type == KnownPrimaryType.DateTime ||
                        primaryType.Type == KnownPrimaryType.DateTimeRfc1123 ||
                        primaryType.Type == KnownPrimaryType.TimeSpan)
                    {
                        return("isodate.parse_date(\"" + defaultValue + "\")");
                    }

                    if (primaryType.Type == KnownPrimaryType.ByteArray)
                    {
                        return("bytearray(\"" + defaultValue + "\", encoding=\"utf-8\")");
                    }
                }
            }
            return(defaultValue);
        }
        public AzureCSharpFluentCodeNamer(Settings settings)
            : base(settings)
        {
            _innerTypes = new HashSet <CompositeType>();

            _resourceType = new CompositeType
            {
                Name           = "Microsoft.Rest.Azure.Resource",
                SerializedName = "Resource",
            };

            var stringType = new PrimaryType(KnownPrimaryType.String)
            {
                Name = "string"
            };

            _resourceType.Properties.Add(new Property {
                Name = "location", SerializedName = "location", Type = stringType
            });
            _resourceType.Properties.Add(new Property {
                Name = "id", SerializedName = "id", Type = stringType
            });
            _resourceType.Properties.Add(new Property {
                Name = "name", SerializedName = "name", Type = stringType
            });
            _resourceType.Properties.Add(new Property {
                Name = "type", SerializedName = "type", Type = stringType
            });
            _resourceType.Properties.Add(new Property {
                Name = "tags", SerializedName = "tags", Type = new DictionaryType {
                    ValueType = stringType, NameFormat = "System.Collections.Generic.IDictionary<string, {0}>"
                }
            });

            _subResourceType = new CompositeType
            {
                Name           = "Microsoft.Rest.Azure.SubResource",
                SerializedName = "SubResource"
            };
            _subResourceType.Properties.Add(new Property {
                Name = "id", SerializedName = "id", Type = stringType
            });
        }
Esempio n. 10
0
        public override string EscapeDefaultValue(string defaultValue, IType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            PrimaryType primaryType = type as PrimaryType;

            if (defaultValue != null)
            {
                if (type is CompositeType)
                {
                    return("new " + type.Name + "()");
                }
                else if (primaryType != null)
                {
                    if (primaryType.Type == KnownPrimaryType.String)
                    {
                        return(CodeNamer.QuoteValue(defaultValue));
                    }
                    else if (primaryType.Type == KnownPrimaryType.Boolean)
                    {
                        return(defaultValue.ToLowerInvariant());
                    }
                    else
                    {
                        if (primaryType.Type == KnownPrimaryType.Date ||
                            primaryType.Type == KnownPrimaryType.DateTime ||
                            primaryType.Type == KnownPrimaryType.DateTimeRfc1123 ||
                            primaryType.Type == KnownPrimaryType.TimeSpan ||
                            primaryType.Type == KnownPrimaryType.ByteArray ||
                            primaryType.Type == KnownPrimaryType.Base64Url ||
                            primaryType.Type == KnownPrimaryType.UnixTime)
                        {
                            return("Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<" + primaryType.Name.TrimEnd('?') +
                                   ">(" + CodeNamer.QuoteValue("\"" + defaultValue + "\"") + ", this.Client.SerializationSettings)");
                        }
                    }
                }
            }
            return(defaultValue);
        }
Esempio n. 11
0
        private AttributeTypePrimitive(PrimaryType primaryType) : base(primaryType)
        {
            switch (primaryType)
            {
            case PrimaryType.Boolean:
            case PrimaryType.Contact:
            case PrimaryType.Double:
            case PrimaryType.Duration:
            case PrimaryType.Int:
            case PrimaryType.Null:
            case PrimaryType.String:
            case PrimaryType.Time:
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(primaryType), primaryType,
                                                      "This class can represent a primitive type only (boolean, int etc.).");
            }
        }
Esempio n. 12
0
        /// <summary>
        /// If the element type of a sequenece or value type of a dictionary
        /// contains one of the following special types then it needs to be
        /// deserialized. The special types are: Date, DateTime, ByteArray
        /// and CompositeType
        /// </summary>
        /// <param name="type">The type to determine if special deserialization is required</param>
        /// <returns>True if special deserialization is required. False, otherwise.</returns>
        private static bool IsSpecialDeserializationRequired(IType type)
        {
            PrimaryType[]  validTypes = new PrimaryType[] { PrimaryType.DateTime, PrimaryType.Date, PrimaryType.ByteArray };
            SequenceType   sequence   = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            bool           result     = false;

            if (sequence != null &&
                (validTypes.Any(t => t == sequence.ElementType) || sequence.ElementType is CompositeType))
            {
                result = true;
            }
            else if (dictionary != null &&
                     (validTypes.Any(t => t == dictionary.ValueType) || dictionary.ValueType is CompositeType))
            {
                result = true;
            }

            return(result);
        }
Esempio n. 13
0
 public static string GetEmptyCheck(this PrimaryType type, string valueReference, bool asEmpty)
 {
     if (type.IsPrimaryType(KnownPrimaryType.ByteArray))
     {
         return(string.Format(asEmpty
                                 ? "{0} == nil || len({0}) == 0"
                                 : "{0} != nil && len({0}) > 0", valueReference));
     }
     else if (type.IsPrimaryType(KnownPrimaryType.String))
     {
         return(string.Format(asEmpty
                                 ? "len({0}) == 0"
                                 : "len({0}) > 0", valueReference));
     }
     else
     {
         return(string.Format(asEmpty
                                 ? "{0} == nil"
                                 : "{0} != nil", valueReference));
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Generate code to perform validation on a parameter or property
        /// </summary>
        /// <param name="type">The type to validate</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="valueReference">A reference to the value being validated</param>
        /// <param name="isRequired">True if the parameter is required.</param>
        /// <param name="modelReference">A reference to the models array</param>
        /// <returns>The code to validate the reference of the given type</returns>
        public static string ValidateType(this IModelType type, IChild scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            CompositeType  composite  = type as CompositeType;
            SequenceType   sequence   = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType    primary    = type as PrimaryType;
            EnumType       enumType   = type as EnumType;

            if (primary != null)
            {
                return(primary.ValidatePrimaryType(scope, valueReference, isRequired));
            }
            else if (enumType != null && enumType.Values.Any())
            {
                if (enumType.ModelAsString)
                {
                    return(New <PrimaryType>(KnownPrimaryType.String).ValidatePrimaryType(scope, valueReference, isRequired));
                }
                return(enumType.ValidateEnumType(scope, valueReference, isRequired));
            }
            else if (composite != null && composite.Properties.Any())
            {
                return(ValidateCompositeType(scope, valueReference, isRequired));
            }
            else if (sequence != null)
            {
                return(sequence.ValidateSequenceType(scope, valueReference, isRequired, modelReference));
            }
            else if (dictionary != null)
            {
                return(dictionary.ValidateDictionaryType(scope, valueReference, isRequired, modelReference));
            }

            return(null);
        }
    public string GetMatchingPrimaryKey()
    {
        if (PrimaryType is null)
        {
            return(string.Empty);
        }

        /*
         * This is turning out to be difficult. What is unfortunate is that we have no "good" way to get the primary
         * key information for this type. At this stage we don't have enough processed to be able to query the model
         * for the primary key(s) of this type. We can basically do an ad-hoc query here manually to come up with
         * the primary key. Unfortunately, we then have primary-key detection logic in two places, here, and also
         * in the column data factory that does primary key detection as well.
         */

        /*
         * Also, this method is trying to allow us to link two types together without specifying the primary key.
         * So, this really only works when there is a single primary key and that primary key has the same type
         * as this foreign key column.
         * So, we should be able to loop through all properties, select the Single that is a primary key, check the
         * data type against this column, and if we still have a match then that is our primary key we want to use.
         */
        var properties = PrimaryType.GetProperties()
                         .Select(prop => new
        {
            Property       = prop,
            PrimaryKeyInfo = ColumnDataFactory
                             .GetPrimaryKeyInfo(prop),
            ColumnName = ColumnDataFactory.GetColumnName(prop)
        })
                         .Where(z => z.PrimaryKeyInfo != null && z.PrimaryKeyInfo.IsPrimaryKey)
                         .ToList();

        return(properties.Count switch
        {
            0 => String.Empty,
            1 => properties[0].ColumnName.Name,
            _ => String.Empty
        });
Esempio n. 16
0
        public override string EscapeDefaultValue(string defaultValue, IType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            PrimaryType primaryType = type as PrimaryType;

            if (defaultValue != null && primaryType != null)
            {
                if (primaryType.Type == KnownPrimaryType.String)
                {
                    return(CodeNamer.QuoteValue(defaultValue, quoteChar: "'"));
                }
                else if (primaryType.Type == KnownPrimaryType.Boolean)
                {
                    return(defaultValue.ToLowerInvariant());
                }
                else
                {
                    if (primaryType.Type == KnownPrimaryType.Date ||
                        primaryType.Type == KnownPrimaryType.DateTime ||
                        primaryType.Type == KnownPrimaryType.DateTimeRfc1123)
                    {
                        return("new Date('" + defaultValue + "')");
                    }
                    else if (primaryType.Type == KnownPrimaryType.TimeSpan)
                    {
                        return("moment.duration('" + defaultValue + "')");
                    }
                    else if (primaryType.Type == KnownPrimaryType.ByteArray)
                    {
                        return("new Buffer('" + defaultValue + "')");
                    }
                }
            }
            return(defaultValue);
        }
Esempio n. 17
0
        public override string EscapeDefaultValue(string defaultValue, IType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            PrimaryType primaryType = type as PrimaryType;

            if (defaultValue != null)
            {
                if (type is CompositeType)
                {
                    return(type.Name + "{}");
                }
                else if (primaryType != null)
                {
                    if (primaryType.Type == KnownPrimaryType.String ||
                        primaryType.Type == KnownPrimaryType.Uuid ||
                        primaryType.Type == KnownPrimaryType.TimeSpan)
                    {
                        return(CodeNamer.QuoteValue(defaultValue));
                    }
                    else if (primaryType.Type == KnownPrimaryType.Boolean)
                    {
                        return(defaultValue.ToLowerInvariant());
                    }
                    else if (primaryType.Type == KnownPrimaryType.ByteArray)
                    {
                        return("[]bytearray(\"" + defaultValue + "\")");
                    }
                    else
                    {
                        //TODO: handle imports for package types.
                    }
                }
            }
            return(defaultValue);
        }
Esempio n. 18
0
 public static IType WrapPrimitiveType(IType type)
 {
     if (type is PrimaryType)
     {
         var primaryType = new PrimaryType();
         if (type.Name == "boolean")
         {
             primaryType.Name = "Boolean";
         }
         else if (type.Name == "double")
         {
             primaryType.Name = "Double";
         }
         else if (type.Name == "int")
         {
             primaryType.Name = "Integer";
         }
         else if (type.Name == "long")
         {
             primaryType.Name = "Long";
         }
         else
         {
             return(type);
         }
         return(primaryType);
     }
     else if (type == null)
     {
         var newType = new PrimaryType();
         newType.Name = "Void";
         return(newType);
     }
     else
     {
         return(type);
     }
 }
Esempio n. 19
0
        private static void MakeTypeNullable(IType type)
        {
            PrimaryType primaryType = type as PrimaryType;
            EnumType    enumType    = type as EnumType;

            if (primaryType != null)
            {
                if (primaryType.Name != null &&
                    !primaryType.Name.EndsWith("?", StringComparison.OrdinalIgnoreCase) &&
                    primaryType.IsValueType())
                {
                    primaryType.Name += "?";
                }
            }
            else if (enumType != null)
            {
                if (enumType.Name != null &&
                    !enumType.Name.EndsWith("?", StringComparison.OrdinalIgnoreCase))
                {
                    enumType.Name += "?";
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Format the value of a sequence given the modeled element format.
        /// </summary>
        /// <param name="parameter">The parameter to format</param>
        /// <returns>A reference to the formatted parameter value</returns>
        public static string GetFormattedReferenceValue(this Parameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            SequenceType sequence = parameter.ModelType as SequenceType;

            if (sequence == null)
            {
                return(parameter.ModelType.ToString(parameter.Name));
            }

            PrimaryType primaryType = sequence.ElementType as PrimaryType;
            EnumType    enumType    = sequence.ElementType as EnumType;

            if (enumType != null && enumType.ModelAsString)
            {
                primaryType = New <PrimaryType>(KnownPrimaryType.String);
            }

            return($"{parameter.Name}.join('{parameter.CollectionFormat.GetSeparator()}')");
        }
Esempio n. 21
0
        /// <summary>
        /// Format the value of a sequence given the modeled element format.  Note that only sequences of strings are supported
        /// </summary>
        /// <param name="parameter">The parameter to format</param>
        /// <param name="clientReference">The reference to the client</param>
        /// <returns>A reference to the formatted parameter value</returns>
        public static string GetFormattedReferenceValue(this Parameter parameter, string clientReference)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            SequenceType sequence = parameter.Type as SequenceType;

            if (sequence == null)
            {
                return(parameter.Type.ToString(clientReference, parameter.Name));
            }

            PrimaryType primaryType = sequence.ElementType as PrimaryType;
            EnumType    enumType    = sequence.ElementType as EnumType;

            if (enumType != null && enumType.ModelAsString)
            {
                primaryType = new PrimaryType(KnownPrimaryType.String)
                {
                    Name = "string"
                };
            }

            if (primaryType == null || primaryType.Type != KnownPrimaryType.String)
            {
                throw new InvalidOperationException(
                          string.Format(CultureInfo.InvariantCulture,
                                        "Cannot generate a formatted sequence from a " +
                                        "non-string List parameter {0}", parameter));
            }

            return(string.Format(CultureInfo.InvariantCulture,
                                 "string.Join(\"{0}\", {1})", parameter.CollectionFormat.GetSeparator(), parameter.Name));
        }
Esempio n. 22
0
        /// <summary>
        /// Format the value of a sequence given the modeled element format.
        /// </summary>
        /// <param name="parameter">The parameter to format</param>
        /// <returns>return the separator</returns>
        public static string NeedsFormattedSeparator(Parameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            SequenceType sequence = parameter.ModelType as SequenceType;

            if (sequence == null)
            {
                return(null);
            }

            PrimaryType primaryType = sequence.ElementType as PrimaryType;
            EnumType    enumType    = sequence.ElementType as EnumType;

            if (enumType != null)
            {
                primaryType = New <PrimaryType>(KnownPrimaryType.String);
            }

            return(parameter.CollectionFormat.GetSeparator());
        }
Esempio n. 23
0
        private TypeBase ParsePrimaryType(PrimaryType putType, PrimaryType getType)
        {
            var combinedType = putType ?? getType;

            switch (combinedType.KnownPrimaryType)
            {
            case KnownPrimaryType.Boolean:
                return(builtInTypes[BuiltInTypeKind.Bool]);

            case KnownPrimaryType.Int:
            case KnownPrimaryType.Long:
            case KnownPrimaryType.UnixTime:
            case KnownPrimaryType.Double:
            case KnownPrimaryType.Decimal:
                return(builtInTypes[BuiltInTypeKind.Int]);

            case KnownPrimaryType.Object:
                return(builtInTypes[BuiltInTypeKind.Any]);

            case KnownPrimaryType.ByteArray:
                return(builtInTypes[BuiltInTypeKind.Array]);

            case KnownPrimaryType.Base64Url:
            case KnownPrimaryType.Date:
            case KnownPrimaryType.DateTime:
            case KnownPrimaryType.String:
            case KnownPrimaryType.TimeSpan:
            case KnownPrimaryType.Uuid:
            case KnownPrimaryType.DateTimeRfc1123:
                return(builtInTypes[BuiltInTypeKind.String]);

            default:
                Debug.Assert(false, "Unrecognized known property type: " + combinedType.KnownPrimaryType);
                return(builtInTypes[BuiltInTypeKind.Any]);
            }
        }
        public static string GetPythonTypeHint(IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            PrimaryType primaryType = type as PrimaryType;

            if (primaryType != null)
            {
                switch (primaryType.KnownPrimaryType)
                {
                case KnownPrimaryType.Base64Url:
                    return("bytes");

                case KnownPrimaryType.ByteArray:
                    return("bytearray");

                case KnownPrimaryType.Boolean:
                    return("bool");

                case KnownPrimaryType.Double:
                    return("float");

                case KnownPrimaryType.Long:
                case KnownPrimaryType.Int:
                    return("int");

                case KnownPrimaryType.Uuid:
                case KnownPrimaryType.String:
                    return("str");
                }
            }
            // FIXME needs to do all of them using "typing"
            return(null);
        }
Esempio n. 25
0
 public void SetValue(string value)
 {
     this.SetObjectValue(value);
     this.DataType = PrimaryType.STRING;
 }
Esempio n. 26
0
 public void SetValue(double value)
 {
     this.SetDoubleValue(value);
     this.DataType = PrimaryType.DOUBLE;
 }
Esempio n. 27
0
 public void SetValue(long value)
 {
     this.SetLongValue(value);
     this.DataType = PrimaryType.LONG;
 }
Esempio n. 28
0
 public void SetValue(int value)
 {
     this.SetLongValue(value);
     this.DataType = PrimaryType.INT;
 }
Esempio n. 29
0
 public void SetValue(bool value)
 {
     this.SetLongValue(value ? 1 : 0);
     this.DataType = PrimaryType.BOOL;
 }
Esempio n. 30
0
 public void SetValue(TimeSpan value)
 {
     this.SetObjectValue(value);
     this.DataType = PrimaryType.TIMESPAN;
 }
Esempio n. 31
0
        private static JsonSchema ParsePrimaryType(Property property, PrimaryType primaryType)
        {
            JsonSchema result = new JsonSchema()
            {
                Format = primaryType.Format
            };

            switch (primaryType.KnownPrimaryType)
            {
            case KnownPrimaryType.Boolean:
                result.JsonType = "boolean";
                break;

            case KnownPrimaryType.Int:
            case KnownPrimaryType.Long:
                result.JsonType = "integer";
                break;

            case KnownPrimaryType.Double:
            case KnownPrimaryType.Decimal:
                result.JsonType = "number";
                break;

            case KnownPrimaryType.Object:
                result.JsonType = "object";
                break;

            case KnownPrimaryType.ByteArray:
                result.JsonType = "array";
                result.Items    = new JsonSchema()
                {
                    JsonType = "integer"
                };
                break;

            case KnownPrimaryType.Base64Url:
            case KnownPrimaryType.Date:
            case KnownPrimaryType.DateTime:
            case KnownPrimaryType.String:
            case KnownPrimaryType.TimeSpan:
                result.JsonType = "string";
                break;

            case KnownPrimaryType.Uuid:
                result.JsonType = "string";
                result.Pattern  = @"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$";
                break;

            default:
                Debug.Assert(false, "Unrecognized known property type: " + primaryType.KnownPrimaryType);
                break;
            }

            if (property != null)
            {
                result.Description = property.Documentation;

                if (property.DefaultValue != null)
                {
                    result.AddEnum(property.DefaultValue);
                }

                if (property.Constraints.Count > 0)
                {
                    foreach (KeyValuePair <Constraint, string> entry in property.Constraints)
                    {
                        switch (entry.Key)
                        {
                        case Constraint.InclusiveMinimum:
                            Debug.Assert(result.JsonType == "integer" || result.JsonType == "number", "Expected to only find an InclusiveMinimum constraint on an integer or number property.");
                            result.Minimum = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                            break;

                        case Constraint.InclusiveMaximum:
                            Debug.Assert(result.JsonType == "integer" || result.JsonType == "number", "Expected to only find an InclusiveMaximum constraint on an integer or number property.");
                            result.Maximum = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                            break;

                        case Constraint.Pattern:
                            Debug.Assert(result.JsonType == "string", "Expected to only find a Pattern constraint on a string property.");
                            result.Pattern = entry.Value;
                            break;

                        case Constraint.MinLength:
                            Debug.Assert(result.JsonType == "string" || result.JsonType == "array", "Expected to only find a MinLength constraint on a string or array property.");
                            result.MinLength = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                            break;

                        case Constraint.MaxLength:
                            Debug.Assert(result.JsonType == "string" || result.JsonType == "array", "Expected to only find a MaxLength constraint on a string or array property.");
                            result.MaxLength = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                            break;

                        default:
                            Debug.Fail("Unrecognized property Constraint: " + entry.Key);
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 32
0
 public AttributeType(PrimaryType primaryType)
 {
     PrimaryType = primaryType;
 }
Esempio n. 33
0
        public string GetDeserializationString(IType type, string valueReference = "result.body")
        {
            CompositeType  composite  = type as CompositeType;
            SequenceType   sequence   = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType    primary    = type as PrimaryType;
            EnumType       enumType   = type as EnumType;
            var            builder    = new IndentedStringBuilder("  ");

            if (primary != null)
            {
                if (primary == PrimaryType.DateTime ||
                    primary == PrimaryType.Date)
                {
                    builder.AppendLine("{0} = new Date({0});", valueReference);
                }
                else if (primary == PrimaryType.ByteArray)
                {
                    builder.AppendLine("{0} = new Buffer({0}, 'base64');", valueReference);
                }
            }
            else if (IsSpecialDeserializationRequired(sequence))
            {
                builder.AppendLine("for (var i = 0; i < {0}.length; i++) {{", valueReference)
                .Indent()
                .AppendLine("if ({0}[i] !== null && {0}[i] !== undefined) {{", valueReference)
                .Indent();
                // Loop through the sequence if each property is Date, DateTime or ByteArray
                // as they need special treatment for deserialization
                if (sequence.ElementType == PrimaryType.DateTime ||
                    sequence.ElementType == PrimaryType.Date)
                {
                    builder.AppendLine("{0}[i] = new Date({0}[i]);", valueReference);
                }
                else if (sequence.ElementType == PrimaryType.ByteArray)
                {
                    builder.AppendLine("{0}[i] = new Buffer({0}[i], 'base64');", valueReference);
                }
                else if (sequence.ElementType is CompositeType)
                {
                    builder.AppendLine(GetDeserializationString(sequence.ElementType,
                                                                string.Format(CultureInfo.InvariantCulture, "{0}[i]", valueReference)));
                }

                builder.Outdent()
                .AppendLine("}")
                .Outdent()
                .AppendLine("}");
            }
            else if (IsSpecialDeserializationRequired(dictionary))
            {
                builder.AppendLine("for (var property in {0}) {{", valueReference)
                .Indent()
                .AppendLine("if ({0}[property] !== null && {0}[property] !== undefined) {{", valueReference)
                .Indent();
                if (dictionary.ValueType == PrimaryType.DateTime ||
                    dictionary.ValueType == PrimaryType.Date)
                {
                    builder.AppendLine("{0}[property] = new Date({0}[property]);", valueReference);
                }
                else if (dictionary.ValueType == PrimaryType.ByteArray)
                {
                    builder.AppendLine("{0}[property] = new Buffer({0}[property], 'base64');", valueReference);
                }
                else if (dictionary.ValueType is CompositeType)
                {
                    builder.AppendLine(GetDeserializationString(dictionary.ValueType,
                                                                string.Format(CultureInfo.InvariantCulture, "{0}[property]", valueReference)));
                }
                builder.Outdent()
                .AppendLine("}")
                .Outdent()
                .AppendLine("}");
            }
            else if (composite != null)
            {
                if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator))
                {
                    builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && client._models.discriminators[{0}['{1}']]) {{",
                                       valueReference,
                                       composite.PolymorphicDiscriminator)
                    .Indent()
                    .AppendLine("{0} = client._models.discriminators[{0}['{1}']].deserialize({0});",
                                valueReference,
                                composite.PolymorphicDiscriminator)
                    .Outdent()
                    .AppendLine("} else {")
                    .Indent()
                    .AppendLine("throw new Error('No discriminator field \"{0}\" was found in response.');",
                                composite.PolymorphicDiscriminator)
                    .Outdent()
                    .AppendLine("}");
                }
                else
                {
                    builder.AppendLine("{0} = client._models['{1}'].deserialize({0});", valueReference, type.Name);
                }
            }
            else if (enumType != null)
            {
                //Do No special deserialization
            }
            else
            {
                return(string.Empty);
            }
            return(builder.ToString());
        }
        /// <summary>
        /// Constructs blueprint of the given <paramref name="primary"/>.
        /// </summary>
        /// <param name="primary">PrimaryType for which mapper being generated.</param>
        /// <returns>Mapper for the <paramref name="primary"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for PrimaryType.
        /// type: {
        ///   name: 'Boolean'                               -- This value should be one of the KnownPrimaryType
        /// }
        /// </example>
        private static string ContructMapperForPrimaryType(this PrimaryType primary)
        {
            if (primary == null)
            {
                throw new ArgumentNullException(nameof(primary));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            if (primary.Type == KnownPrimaryType.Boolean)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Double)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Double'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long ||
                     primary.Type == KnownPrimaryType.Decimal)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.String || primary.Type == KnownPrimaryType.Uuid)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.ByteArray)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Base64Url)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Date)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.DateTime)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.DateTimeRfc1123)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.TimeSpan)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.UnixTime)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Object)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}");
            }
            else if (primary.Type == KnownPrimaryType.Stream)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}");
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} is not a supported primary Type for {1}.", primary.Type, primary.SerializedName));
            }

            return(builder.ToString());
        }
Esempio n. 35
0
 public void SetValue(Regex value)
 {
     this.SetObjectValue(value);
     this.DataType = PrimaryType.REGEX;
 }
Esempio n. 36
0
 public void SetValue(DateTime value)
 {
     this.SetObjectValue(value);
     this.DataType = PrimaryType.DATETIME;
 }
        private void LoadPrimary(PrimaryType type)
        {
            RadComboBox cmbType;
            RadComboBox cmbPrimary;
            string chkText = null;
            switch (type)
            {
                case PrimaryType.School:
                    cmbType = schoolDropdown;
                    cmbPrimary = cmbPrimarySchool;
                    chkText = "schoolCheckBox";
                    break;
                case PrimaryType.UserType:
                    cmbType = userTypeDropdown;
                    cmbPrimary = cmbPrimaryUser;
                    chkText = "userTypeCheckbox";
                    break;
                default:
                    cmbType = null;
                    cmbPrimary = null;
                    chkText = null;
                    break;
            }


            cmbPrimary.Items.Clear();
            foreach (RadComboBoxItem item in cmbType.Items)
            {
                if (((CheckBox)item.FindControl(chkText)).Checked)
                {
                    RadComboBoxItem newItem = new RadComboBoxItem(item.Text, item.Value);
                    cmbPrimary.Items.Add(newItem);
                }
            }

            switch(type)
            {
                case PrimaryType.School:
                    if (cmbPrimary.FindItemByValue(_selectedStaff.LegacySchoolID.ToString()) != null)
                    {
                        cmbPrimary.FindItemByValue(_selectedStaff.LegacySchoolID.ToString()).Selected = true;
                    }
                    break;
                case PrimaryType.UserType:
                    if (cmbPrimary.FindItemByText(_selectedStaff.LegacyRole, true) != null)
                    {
                        cmbPrimary.FindItemByText(_selectedStaff.LegacyRole, true).Selected = true;
                    }
                    break;
                default:
                    break;
            }
        }
Esempio n. 38
0
        /// <summary>
        /// The visitor method for building service types. This is called when an instance of this class is
        /// visiting a _swaggerModeler to build a service type.
        /// </summary>
        /// <param name="serviceTypeName">name for the service type</param>
        /// <returns>built service type</returns>
        public virtual IModelType BuildServiceType(string serviceTypeName)
        {
            PrimaryType type = SwaggerObject.ToType();

            Debug.Assert(type != null);

            if (type.KnownPrimaryType == KnownPrimaryType.Object && SwaggerObject.KnownFormat == KnownFormat.file)
            {
                type = New <PrimaryType>(KnownPrimaryType.Stream);
            }
            type.XmlProperties = (SwaggerObject as Schema)?.Xml;
            type.Format        = SwaggerObject.Format;
            if (SwaggerObject.Enum != null && type.KnownPrimaryType == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject)))
            {
                var enumType = New <EnumType>();
                SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue {
                    Name = v, SerializedName = v
                }));
                if (SwaggerObject.Extensions.ContainsKey(Core.Model.XmsExtensions.Enum.Name))
                {
                    var enumObject = SwaggerObject.Extensions[Core.Model.XmsExtensions.Enum.Name] as Newtonsoft.Json.Linq.JContainer;
                    if (enumObject != null)
                    {
                        enumType.SetName(enumObject["name"].ToString());
                        if (enumObject["modelAsString"] != null)
                        {
                            enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
                        }
                    }
                    enumType.SerializedName = enumType.Name;
                    if (string.IsNullOrEmpty(enumType.Name))
                    {
                        throw new InvalidOperationException(
                                  string.Format(CultureInfo.InvariantCulture,
                                                "{0} extension needs to specify an enum name.",
                                                Core.Model.XmsExtensions.Enum.Name));
                    }
                    var existingEnum =
                        Modeler.CodeModel.EnumTypes.FirstOrDefault(
                            e => e.Name.RawValue.EqualsIgnoreCase(enumType.Name.RawValue));
                    if (existingEnum != null)
                    {
                        if (!existingEnum.StructurallyEquals(enumType))
                        {
                            throw new InvalidOperationException(
                                      string.Format(CultureInfo.InvariantCulture,
                                                    "Swagger document contains two or more {0} extensions with the same name '{1}' and different values.",
                                                    Core.Model.XmsExtensions.Enum.Name,
                                                    enumType.Name));
                        }
                        // Use the existing one!
                        enumType = existingEnum;
                    }
                    else
                    {
                        Modeler.CodeModel.Add(enumType);
                    }
                }
                else
                {
                    enumType.ModelAsString = true;
                    enumType.SetName(string.Empty);
                    enumType.SerializedName = string.Empty;
                }
                enumType.XmlProperties = (SwaggerObject as Schema)?.Xml;
                return(enumType);
            }
            if (SwaggerObject.Type == DataType.Array)
            {
                string itemServiceTypeName;
                if (SwaggerObject.Items.Reference != null)
                {
                    itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath();
                }
                else
                {
                    itemServiceTypeName = serviceTypeName + "Item";
                }

                var elementType =
                    SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName);
                return(New <SequenceType>(new
                {
                    ElementType = elementType,
                    Extensions = SwaggerObject.Items.Extensions,
                    XmlProperties = (SwaggerObject as Schema)?.Xml,
                    ElementXmlProperties = SwaggerObject.Items?.Xml
                }));
            }
            if (SwaggerObject.AdditionalProperties != null)
            {
                string dictionaryValueServiceTypeName;
                if (SwaggerObject.AdditionalProperties.Reference != null)
                {
                    dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
                }
                else
                {
                    dictionaryValueServiceTypeName = serviceTypeName + "Value";
                }
                return(New <DictionaryType>(new
                {
                    ValueType =
                        SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
                        .BuildServiceType((dictionaryValueServiceTypeName)),
                    Extensions = SwaggerObject.AdditionalProperties.Extensions,
                    XmlProperties = (SwaggerObject as Schema)?.Xml
                }));
            }

            return(type);
        }
Esempio n. 39
0
        public static string GetPythonSerializationType(IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            Dictionary <KnownPrimaryType, string> typeNameMapping = new Dictionary <KnownPrimaryType, string>()
            {
                { KnownPrimaryType.DateTime, "iso-8601" },
                { KnownPrimaryType.DateTimeRfc1123, "rfc-1123" },
                { KnownPrimaryType.TimeSpan, "duration" },
                { KnownPrimaryType.UnixTime, "unix-time" },
                { KnownPrimaryType.Base64Url, "base64" },
                { KnownPrimaryType.Decimal, "Decimal" }
            };
            PrimaryType primaryType = type as PrimaryType;

            if (primaryType != null)
            {
                if (typeNameMapping.ContainsKey(primaryType.KnownPrimaryType))
                {
                    return(typeNameMapping[primaryType.KnownPrimaryType]);
                }
                else
                {
                    return(type.Name);
                }
            }

            SequenceType sequenceType = type as SequenceType;

            if (sequenceType != null)
            {
                IModelType  innerType        = sequenceType.ElementType;
                PrimaryType innerPrimaryType = innerType as PrimaryType;
                string      innerTypeName;
                if (innerPrimaryType != null && typeNameMapping.ContainsKey(innerPrimaryType.KnownPrimaryType))
                {
                    innerTypeName = typeNameMapping[innerPrimaryType.KnownPrimaryType];
                }
                else
                {
                    innerTypeName = GetPythonSerializationType(innerType);
                }
                return("[" + innerTypeName + "]");
            }

            DictionaryType dictType = type as DictionaryType;

            if (dictType != null)
            {
                IModelType  innerType        = dictType.ValueType;
                PrimaryType innerPrimaryType = innerType as PrimaryType;
                string      innerTypeName;
                if (innerPrimaryType != null && typeNameMapping.ContainsKey(innerPrimaryType.KnownPrimaryType))
                {
                    innerTypeName = typeNameMapping[innerPrimaryType.KnownPrimaryType];
                }
                else
                {
                    innerTypeName = GetPythonSerializationType(innerType);
                }
                return("{" + innerTypeName + "}");
            }

            EnumType enumType = type as EnumType;

            if (enumType != null && enumType.ModelAsString)
            {
                return("str");
            }

            // CompositeType or EnumType
            return(type.Name);
        }