Exemplo n.º 1
0
        public static void PopulateProperty(Property property, SwaggerObject swaggerObject)
        {
            if (swaggerObject == null)
            {
                throw new ArgumentNullException("swaggerObject");
            }
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }
            property.DefaultValue = swaggerObject.Default;

            if (IsSwaggerObjectConstant(swaggerObject, property.IsRequired))
            {
                property.DefaultValue = swaggerObject.Enum.TokensToStrings().First();
                property.IsConstant   = true;
            }

            property.Documentation = swaggerObject.Description;

            // tag the paramter with all the extensions from the swagger object
            property.Extensions.AddRange(swaggerObject.Extensions);

            SetConstraints(property.Constraints, swaggerObject);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Determines if a constraint is supported for the SwaggerObject Type
        /// </summary>
        /// <param name="constraintName"></param>
        /// <returns></returns>
        public static bool IsConstraintSupported(this SwaggerObject swaggerObject, string constraintName)
        {
            switch (swaggerObject.Type)
            {
            case DataType.Array:
                return(constraintName.EqualsIgnoreCase(Constraint.MinItems.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.MaxItems.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.UniqueItems.ToString()));

            case DataType.Integer:
            case DataType.Number:
                return(constraintName.EqualsIgnoreCase(Constraint.ExclusiveMaximum.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.ExclusiveMinimum.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.MultipleOf.ToString()) ||
                       constraintName.EqualsIgnoreCase("minimum") || constraintName.EqualsIgnoreCase("maximum"));

            case DataType.String:
                return(constraintName.EqualsIgnoreCase(Constraint.MinLength.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.MaxLength.ToString()) ||
                       constraintName.EqualsIgnoreCase(Constraint.Pattern.ToString()));

            default:
                return(false);
            }
        }
Exemplo n.º 3
0
        public static void PopulateParameter(IVariable parameter, SwaggerObject swaggerObject)
        {
            if (swaggerObject == null)
            {
                throw new ArgumentNullException("swaggerObject");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }
            parameter.IsRequired   = swaggerObject.IsRequired;
            parameter.DefaultValue = swaggerObject.Default;

            if (IsSwaggerObjectConstant(swaggerObject))
            {
                parameter.DefaultValue = swaggerObject.Enum[0];
                parameter.IsConstant   = true;
            }

            parameter.Documentation    = swaggerObject.Description;
            parameter.CollectionFormat = swaggerObject.CollectionFormat;

            // tag the paramter with all the extensions from the swagger object
            parameter.Extensions.AddRange(swaggerObject.Extensions);

            SetConstraints(parameter.Constraints, swaggerObject);
        }
Exemplo n.º 4
0
        public static void PopulateParameter(IParameter parameter, SwaggerObject swaggerObject)
        {
            if (swaggerObject == null)
            {
                throw new ArgumentNullException("swaggerObject");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }
            parameter.IsRequired   = swaggerObject.IsRequired;
            parameter.DefaultValue = swaggerObject.Default;

            if (IsSwaggerObjectConstant(swaggerObject))
            {
                parameter.DefaultValue = swaggerObject.Enum[0];
                parameter.IsConstant   = true;
            }

            var compositeType = parameter.Type as CompositeType;

            if (compositeType != null && compositeType.ComposedProperties.Any())
            {
                if (compositeType.ComposedProperties.All(p => p.IsConstant))
                {
                    parameter.DefaultValue = "{}";
                    parameter.IsConstant   = true;
                }
            }


            parameter.Documentation    = swaggerObject.Description;
            parameter.CollectionFormat = swaggerObject.CollectionFormat;
            var enumType = parameter.Type as EnumType;

            if (enumType != null)
            {
                if (parameter.Documentation == null)
                {
                    parameter.Documentation = string.Empty;
                }
                else
                {
                    parameter.Documentation = parameter.Documentation.TrimEnd('.') + ". ";
                }
                parameter.Documentation += "Possible values include: " +
                                           string.Join(", ", enumType.Values.Select(v =>
                                                                                    string.Format(CultureInfo.InvariantCulture,
                                                                                                  "'{0}'", v.Name)));
            }
            swaggerObject.Extensions.ForEach(e => parameter.Extensions[e.Key] = e.Value);

            SetConstraints(parameter.Constraints, swaggerObject);
        }
        public static List <string> ReadAdditionalHeaders(SwaggerObject swaggerObject)
        {
            List <string> list = new List <string>();

            foreach (var secutiryDefinitions in swaggerObject.securityDefinitions)
            {
                list.Add(secutiryDefinitions.Value.name);
            }

            return(list);
        }
Exemplo n.º 6
0
 private static bool IsExpandableEnum(SwaggerObject swaggerObject)
 {
     if (swaggerObject.Extensions.ContainsKey(CodeGenerator.EnumObject))
     {
         var enumObject = swaggerObject.Extensions[CodeGenerator.EnumObject] as Newtonsoft.Json.Linq.JContainer;
         if (enumObject != null)
         {
             if (enumObject["modelAsString"] != null)
             {
                 return(bool.Parse(enumObject["modelAsString"].ToString()));
             }
         }
     }
     return(false);
 }
Exemplo n.º 7
0
        public override async Task Generate(CodeModel codeModel)
        {
            var @namespace = Class.CreateName(codeModel.Namespace);

            var phpGroups = codeModel.Operations
                            .Where(o => o.Name.RawValue != string.Empty)
                            .Select(o => new PhpFunctionGroup(@namespace, o));

            var phpFunctions = codeModel.Operations
                               .Where(o => o.Name.RawValue == string.Empty)
                               .SelectMany(o => o.Methods.Select(m => new PhpOperation(m)));

            var swaggerObjectData = PHP.Const(
                SwaggerObjectData,
                PHP.FromJson(SwaggerObject.Create(codeModel)));

            var client = PHP.Class(
                name: Class.CreateName(@namespace, codeModel.Name),
                constructor: PHP.Constructor(
                    parameters: ClientConstructorParameters,
                    body: PHP
                    .Statements(CreateClient)
                    .Concat(phpGroups.Select(g => g.Create))
                    .Concat(phpFunctions.SelectMany(f => f.ConstructorStatements))),
                functions: phpGroups
                .Select(o => o.Function)
                .Concat(phpFunctions.Select(f => f.Function)),
                properties: phpGroups
                .Select(o => o.Property)
                .Concat(phpFunctions.Select(f => f.Property)),
                consts: PHP.Consts(swaggerObjectData));

            foreach (var class_ in phpGroups
                     .Select(o => o.Class)
                     .Concat(ImmutableArray.Create(client)))
            {
                await Write(
                    string.Join("\n", class_.ToCodeText(Indent)),
                    class_.Name.FileName,
                    false);
            }
        }
Exemplo n.º 8
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;
            var xMsEnum = SwaggerObject.Extensions.GetValue <JToken>(Core.Model.XmsExtensions.Enum.Name);

            if ((SwaggerObject.Enum != null || xMsEnum != null) && type.KnownPrimaryType == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject)))
            {
                var enumType = New <EnumType>();
                if (SwaggerObject.Enum != null)
                {
                    SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue {
                        Name = v, SerializedName = v
                    }));
                }
                if (xMsEnum != null)
                {
                    var enumObject = xMsEnum as JContainer;
                    if (enumObject != null)
                    {
                        enumType.SetName(enumObject["name"].ToString());
                        if (enumObject["modelAsString"] != null)
                        {
                            enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
                        }
                        var valueOverrides = enumObject["values"] as JArray;
                        if (valueOverrides != null)
                        {
                            enumType.Values.Clear();
                            foreach (var valueOverride in valueOverrides)
                            {
                                var value       = valueOverride["value"];
                                var description = valueOverride["description"];
                                var name        = valueOverride["name"] ?? value;
                                enumType.Values.Add(new EnumValue
                                {
                                    Name           = (string)name,
                                    SerializedName = (string)value,
                                    Description    = (string)description
                                });
                            }
                        }
                    }
                    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: {2} vs. {3}",
                                                    Core.Model.XmsExtensions.Enum.Name,
                                                    enumType.Name,
                                                    string.Join(",", existingEnum.Values.Select(x => x.SerializedName)),
                                                    string.Join(",", enumType.Values.Select(x => x.SerializedName))));
                        }
                        // Use the existing one!
                        enumType = existingEnum;
                    }
                    else
                    {
                        Modeler.CodeModel.Add(enumType);
                    }
                }
                else
                {
                    enumType.ModelAsString = true;
                    enumType.SetName(string.Empty);
                }
                enumType.XmlProperties = (SwaggerObject as Schema)?.Xml;
                return(enumType);
            }
            if (SwaggerObject.Type == DataType.Array)
            {
                if (SwaggerObject.Items == null)
                {
                    throw new Exception($"Invalid Swagger: Missing 'items' definition of an 'array' type.");
                }

                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);
        }
Exemplo n.º 9
0
        private SwaggerObjectBase Build(JToken token)
        {
            // Fetch from cache first
            var location = GetLocation(token);
            SwaggerObjectBase existingObject;
            if (_documentObjectCache.TryGetValue(location, out existingObject))
            {
                return existingObject;
            }

            var jObject = token as JObject;
            if (jObject != null)
            {
                // Only one $ref is allowed inside a swagger JObject
                JToken referenceToken;
                if (jObject.TryGetValue("$ref", out referenceToken))
                {
                    if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
                    {
                        throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
                    }

                    var formatted = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
                    var deferredObject = new SwaggerReferenceObject
                    {
                        DeferredReference = formatted.Item1,
                        ReferenceName = formatted.Item2,
                        Location = location
                    };

                    // For swagger, other properties are still allowed besides $ref, e.g.
                    // "schema": {
                    //   "$ref": "#/definitions/foo"
                    //   "example": { }
                    // }
                    // Use Token property to keep other properties
                    // These properties cannot be referenced
                    jObject.Remove("$ref");
                    deferredObject.Token = jObject;
                    _documentObjectCache.Add(location, deferredObject);
                    return deferredObject;
                }

                var swaggerObject = new SwaggerObject { Location = location };
                foreach (KeyValuePair<string, JToken> property in jObject)
                {
                    swaggerObject.Dictionary.Add(property.Key, Build(property.Value));
                }

                _documentObjectCache.Add(location, swaggerObject);
                return swaggerObject;
            }

            var jArray = token as JArray;
            if (jArray != null)
            {
                var swaggerArray = new SwaggerArray { Location = location };
                foreach (var property in jArray)
                {
                    swaggerArray.Array.Add(Build(property));
                }

                return swaggerArray;
            }

            return new SwaggerValue
            {
                Location = location,
                Token = token
            };
        }
Exemplo n.º 10
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 IType BuildServiceType(string serviceTypeName)
        {
            PrimaryType type = SwaggerObject.ToType();

            if (type == PrimaryType.Object && "file".Equals(SwaggerObject.Format, StringComparison.OrdinalIgnoreCase))
            {
                type = PrimaryType.Stream;
            }
            if (SwaggerObject.Enum != null &&
                type == PrimaryType.String &&
                (SwaggerObject.Enum.Count > 1 || IsExpandableEnum(SwaggerObject)))
            {
                var enumType = new EnumType();
                SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue {
                    Name = v, SerializedName = v
                }));
                if (SwaggerObject.Extensions.ContainsKey(CodeGenerator.EnumObject))
                {
                    var enumObject = SwaggerObject.Extensions[CodeGenerator.EnumObject] as Newtonsoft.Json.Linq.JContainer;
                    if (enumObject != null)
                    {
                        enumType.Name = 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.",
                                                CodeGenerator.EnumObject));
                    }
                    var existingEnum =
                        Modeler.ServiceClient.EnumTypes.FirstOrDefault(
                            e => e.Name.Equals(enumType.Name, StringComparison.OrdinalIgnoreCase));
                    if (existingEnum != null)
                    {
                        if (!existingEnum.Equals(enumType))
                        {
                            throw new InvalidOperationException(
                                      string.Format(CultureInfo.InvariantCulture,
                                                    "Swagger document contains two or more {0} extensions with the same name '{1}' and different values.",
                                                    CodeGenerator.EnumObject,
                                                    enumType.Name));
                        }
                    }
                    else
                    {
                        Modeler.ServiceClient.EnumTypes.Add(enumType);
                    }
                }
                else
                {
                    enumType.ModelAsString  = true;
                    enumType.Name           = string.Empty;
                    enumType.SerializedName = string.Empty;
                }
                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
                {
                    ElementType = elementType
                });
            }
            if (SwaggerObject.AdditionalProperties != null)
            {
                string dictionaryValueServiceTypeName;
                if (SwaggerObject.AdditionalProperties.Reference != null)
                {
                    dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
                }
                else
                {
                    dictionaryValueServiceTypeName = serviceTypeName + "Value";
                }
                return(new DictionaryType
                {
                    ValueType =
                        SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
                        .BuildServiceType((dictionaryValueServiceTypeName))
                });
            }

            return(type);
        }
Exemplo n.º 11
0
 internal static bool DefinesInlineProperties(this SwaggerObject entity)
 {
     return(entity.Description != null ||
            entity.Items != null ||
            entity.Type != null);
 }
Exemplo n.º 12
0
 /// <summary>
 ///     Determines if the default value appears in the enum
 /// </summary>
 internal static bool EnumContainsDefault(this SwaggerObject entity)
 {
     return(entity.Enum.Contains(entity.Default));
 }
Exemplo n.º 13
0
 private static void RemoveReferenceDefinitions(SwaggerObject root)
 {
     // Remove definitions and parameters which has been added into _documentObjectCache
     if (root.Dictionary.ContainsKey(DefinitionsKey))
     {
         root.Dictionary.Remove(DefinitionsKey);
     }
     if (root.Dictionary.ContainsKey(ParametersKey))
     {
         root.Dictionary.Remove(ParametersKey);
     }
 }
Exemplo n.º 14
0
 public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler)
 {
     SwaggerObject = swaggerObject;
     Modeler       = modeler;
 }
Exemplo n.º 15
0
 private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject)
 {
     return(swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired);
 }
        public static List <ViewModelClass> ReadViewModels(SwaggerObject swaggerObject, string apiNameSpace, string clientNameSpace)
        {
            List <ViewModelClass> viewModelList = new List <ViewModelClass>();

            foreach (var definition in swaggerObject.definitions)
            {
                ViewModelClass viewModelClass = new ViewModelClass();

                viewModelClass.NameOfClass = TranslateNameSpace(definition.Key, apiNameSpace, clientNameSpace);

                foreach (var property in definition.Value.properties)
                {
                    if (!string.IsNullOrEmpty(property.Value.type) &&
                        property.Value.type.Equals("object"))
                    {
                        // INNER VIEW MODEL CLASS DETECTED
                        ViewModelClass innerViewModelClass = new ViewModelClass();

                        string nameOfClassAdjusted = definition.Key + char.ToUpper(property.Key[0]) + property.Key.Substring(1);

                        innerViewModelClass.NameOfClass = TranslateNameSpace(nameOfClassAdjusted, apiNameSpace, clientNameSpace);

                        foreach (var innerProperty in property.Value.properties)
                        {
                            string CSharpType = TranslateCSharpType(innerProperty.Value.type,
                                                                    innerProperty.Value.format,
                                                                    innerProperty.Value._ref,
                                                                    innerProperty.Value.items,
                                                                    apiNameSpace,
                                                                    clientNameSpace);

                            innerViewModelClass.Properties.Add(new ViewModelProperty
                            {
                                Name = innerProperty.Key,
                                Type = CSharpType
                            });
                        }

                        viewModelList.Add(innerViewModelClass);

                        viewModelClass.Properties.Add(new ViewModelProperty
                        {
                            Name = property.Key,
                            Type = innerViewModelClass.NameOfClass
                        });
                    }
                    else
                    {
                        string CSharpType = TranslateCSharpType(property.Value.type,
                                                                property.Value.format,
                                                                property.Value._ref,
                                                                property.Value.items,
                                                                apiNameSpace,
                                                                clientNameSpace);

                        viewModelClass.Properties.Add(new ViewModelProperty
                        {
                            Name = property.Key,
                            Type = CSharpType
                        });
                    }
                }

                viewModelList.Add(viewModelClass);
            }

            return(viewModelList);
        }
        public static List <ServiceClass> ReadServices(SwaggerObject swaggerObject, string apiNameSpace, string clientNameSpace)
        {
            List <ServiceClass> serviceList = new List <ServiceClass>();

            foreach (var path in swaggerObject.paths)
            {
                if (path.Value.parameters != null)
                {
                    // TODO: Check what value comes
                }

                if (path.Value.get != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.get);

                    AddServiceMethod(ref serviceClass, HttpVerb.GET, path.Key, path.Value.get, apiNameSpace, clientNameSpace);
                }

                if (path.Value.post != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.post);

                    AddServiceMethod(ref serviceClass, HttpVerb.POST, path.Key, path.Value.post, apiNameSpace, clientNameSpace);
                }

                if (path.Value.put != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.put);

                    AddServiceMethod(ref serviceClass, HttpVerb.PUT, path.Key, path.Value.put, apiNameSpace, clientNameSpace);
                }

                if (path.Value.delete != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.delete);

                    AddServiceMethod(ref serviceClass, HttpVerb.DELETE, path.Key, path.Value.delete, apiNameSpace, clientNameSpace);
                }

                if (path.Value.patch != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.patch);

                    AddServiceMethod(ref serviceClass, HttpVerb.PATCH, path.Key, path.Value.patch, apiNameSpace, clientNameSpace);
                }

                if (path.Value.options != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.options);

                    AddServiceMethod(ref serviceClass, HttpVerb.OPTIONS, path.Key, path.Value.options, apiNameSpace, clientNameSpace);
                }

                if (path.Value.head != null)
                {
                    var serviceClass = GetOrGenerateServiceClass(ref serviceList, path.Value.head);

                    AddServiceMethod(ref serviceClass, HttpVerb.HEAD, path.Key, path.Value.head, apiNameSpace, clientNameSpace);
                }
            }

            return(serviceList);
        }
Exemplo n.º 18
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, bool required)
        {
            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;
            var xMsEnum = SwaggerObject.Extensions.GetValue <JToken>(Core.Model.XmsExtensions.Enum.Name);

            if (xMsEnum != null && SwaggerObject.Enum == null)
            {
                throw new InvalidOperationException($"Found 'x-ms-enum' without 'enum' on the same level. Please either add an 'enum' restriction or remove 'x-ms-enum'.");
            }
            if (SwaggerObject.Enum != null && type.KnownPrimaryType == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject, required)))
            {
                if (SwaggerObject.Enum.Count == 0)
                {
                    throw new InvalidOperationException($"Found an 'enum' with no values. Please remove this (unsatisfiable) restriction or add values.");
                }

                var enumType = New <EnumType>();
                // Set the underlying type. This helps to determine whether the values in EnumValue are of type string, number, etc.
                enumType.UnderlyingType = type;
                SwaggerObject.Enum.OfType <JValue>().Select(x => (string)x).ForEach(v => enumType.Values.Add(new EnumValue {
                    Name = v, SerializedName = v
                }));
                if (xMsEnum is JContainer enumObject)
                {
                    var enumName = "" + enumObject["name"];
                    if (string.IsNullOrEmpty(enumName))
                    {
                        throw new InvalidOperationException($"{Core.Model.XmsExtensions.Enum.Name} extension needs to specify an enum name.");
                    }
                    enumType.SetName(enumName);

                    if (enumObject["modelAsString"] != null)
                    {
                        enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
                    }

                    enumType.OldModelAsString = (enumObject["oldModelAsString"] != null)? bool.Parse(enumObject["oldModelAsString"].ToString()) : false;
                    if (enumType.OldModelAsString)
                    {
                        enumType.ModelAsString = true;
                    }

                    var valueOverrides = enumObject["values"] as JArray;
                    if (valueOverrides != null)
                    {
                        var valuesBefore = new HashSet <string>(enumType.Values.Select(x => x.SerializedName));
                        enumType.Values.Clear();
                        foreach (var valueOverride in valueOverrides)
                        {
                            var value       = valueOverride["value"];
                            var description = valueOverride["description"];
                            var name        = valueOverride["name"] ?? value;

                            var enumVal = new EnumValue
                            {
                                Name           = (string)name,
                                SerializedName = (string)value,
                                Description    = (string)description
                            };

                            if (valueOverride["allowedValues"] is JArray allowedValues)
                            {
                                // set the allowedValues if any
                                foreach (var allowedValue in allowedValues)
                                {
                                    enumVal.AllowedValues.Add(allowedValue.ToString());
                                }
                            }

                            enumType.Values.Add(enumVal);
                        }
                        var valuesAfter = new HashSet <string>(enumType.Values.Select(x => x.SerializedName));
                        // compare values
                        if (!valuesBefore.SetEquals(valuesAfter))
                        {
                            throw new InvalidOperationException($"Values specified by 'enum' mismatch those specified by 'x-ms-enum' (name: '{enumName}'): "
                                                                + string.Join(", ", valuesBefore.Select(x => $"'{x}'"))
                                                                + " vs "
                                                                + string.Join(", ", valuesAfter.Select(x => $"'{x}'")));
                        }
                    }

                    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: {2} vs. {3}",
                                                    Core.Model.XmsExtensions.Enum.Name,
                                                    enumType.Name,
                                                    string.Join(",", existingEnum.Values.Select(x => x.SerializedName)),
                                                    string.Join(",", enumType.Values.Select(x => x.SerializedName))));
                        }
                        // Use the existing one!
                        enumType = existingEnum;
                    }
                    else
                    {
                        Modeler.CodeModel.Add(enumType);
                    }
                }
                else
                {
                    enumType.ModelAsString = true;
                    enumType.SetName(string.Empty);
                }
                enumType.XmlProperties = (SwaggerObject as Schema)?.Xml;
                return(enumType);
            }
            if (SwaggerObject.Type == DataType.Array)
            {
                if (SwaggerObject.Items == null)
                {
                    throw new Exception($"Invalid Swagger: Missing 'items' definition of an 'array' type.");
                }

                string itemServiceTypeName;
                if (SwaggerObject.Items.Reference != null)
                {
                    itemServiceTypeName = SwaggerObject.Items.Reference.StripComponentsSchemaPath();
                }
                else
                {
                    itemServiceTypeName = serviceTypeName + "Item";
                }

                var elementType =
                    SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName, false);
                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.StripComponentsSchemaPath();
                }
                else
                {
                    dictionaryValueServiceTypeName = serviceTypeName + "Value";
                }
                return(New <DictionaryType>(new
                {
                    ValueType =
                        SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
                        .BuildServiceType(dictionaryValueServiceTypeName, false),
                    Extensions = SwaggerObject.AdditionalProperties.Extensions,
                    XmlProperties = (SwaggerObject as Schema)?.Xml
                }));
            }

            return(type);
        }
Exemplo n.º 19
0
 private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject, bool isRequired)
 => swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && isRequired;
Exemplo n.º 20
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 IType BuildServiceType(string serviceTypeName)
        {
            PrimaryType type = SwaggerObject.ToType();

            if (SwaggerObject.Enum != null && SwaggerObject.Enum.Any() && type == PrimaryType.String)
            {
                var enumType = new EnumType();
                SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue {
                    Name = v, SerializedName = v
                }));
                if (SwaggerObject.Extensions.ContainsKey("x-ms-enum"))
                {
                    enumType.IsExpandable   = false;
                    enumType.Name           = SwaggerObject.Extensions["x-ms-enum"] as string;
                    enumType.SerializedName = enumType.Name;
                    if (string.IsNullOrEmpty(enumType.Name))
                    {
                        throw new InvalidOperationException("x-ms-enum extension needs to specify an enum name.");
                    }
                    var existingEnum =
                        Modeler.ServiceClient.EnumTypes.FirstOrDefault(
                            e => e.Name.Equals(enumType.Name, StringComparison.OrdinalIgnoreCase));
                    if (existingEnum != null)
                    {
                        if (!existingEnum.Equals(enumType))
                        {
                            throw new InvalidOperationException(
                                      string.Format(CultureInfo.InvariantCulture,
                                                    "Swagger document contains two or more x-ms-enum extensions with the same name '{0}' and different values.",
                                                    enumType.Name));
                        }
                    }
                    else
                    {
                        Modeler.ServiceClient.EnumTypes.Add(enumType);
                    }
                }
                else
                {
                    enumType.IsExpandable   = true;
                    enumType.Name           = string.Empty;
                    enumType.SerializedName = string.Empty;
                }
                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
                {
                    ElementType = elementType
                });
            }
            if (SwaggerObject.AdditionalProperties != null)
            {
                string dictionaryValueServiceTypeName;
                if (SwaggerObject.AdditionalProperties.Reference != null)
                {
                    dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
                }
                else
                {
                    dictionaryValueServiceTypeName = serviceTypeName + "Value";
                }
                return(new DictionaryType
                {
                    ValueType =
                        SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
                        .BuildServiceType((dictionaryValueServiceTypeName))
                });
            }

            return(type);
        }
Exemplo n.º 21
0
        public static void SetConstraints(Dictionary <Constraint, string> constraints, SwaggerObject swaggerObject)
        {
            if (constraints == null)
            {
                throw new ArgumentNullException("constraints");
            }
            if (swaggerObject == null)
            {
                throw new ArgumentNullException("swaggerObject");
            }

            if (!string.IsNullOrEmpty(swaggerObject.Maximum) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum)) &&
                !swaggerObject.ExclusiveMaximum)

            {
                constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum;
            }
            if (!string.IsNullOrEmpty(swaggerObject.Maximum) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum)) &&
                swaggerObject.ExclusiveMaximum &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMaximum)))
            {
                constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum;
            }
            if (!string.IsNullOrEmpty(swaggerObject.Minimum) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum)) &&
                !swaggerObject.ExclusiveMinimum)
            {
                constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum;
            }
            if (!string.IsNullOrEmpty(swaggerObject.Minimum) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum)) &&
                swaggerObject.ExclusiveMinimum &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMinimum)))
            {
                constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum;
            }
            if (!string.IsNullOrEmpty(swaggerObject.MaxLength) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxLength)))
            {
                constraints[Constraint.MaxLength] = swaggerObject.MaxLength;
            }
            if (!string.IsNullOrEmpty(swaggerObject.MinLength) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinLength)))
            {
                constraints[Constraint.MinLength] = swaggerObject.MinLength;
            }
            if (!string.IsNullOrEmpty(swaggerObject.Pattern) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.Pattern)))
            {
                constraints[Constraint.Pattern] = swaggerObject.Pattern;
            }
            if (!string.IsNullOrEmpty(swaggerObject.MaxItems) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxItems)))
            {
                constraints[Constraint.MaxItems] = swaggerObject.MaxItems;
            }
            if (!string.IsNullOrEmpty(swaggerObject.MinItems) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinItems)))
            {
                constraints[Constraint.MinItems] = swaggerObject.MinItems;
            }
            if (!string.IsNullOrEmpty(swaggerObject.MultipleOf) &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.MultipleOf)))
            {
                constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf;
            }
            if (swaggerObject.UniqueItems &&
                swaggerObject.IsConstraintSupported(nameof(swaggerObject.UniqueItems)))
            {
                constraints[Constraint.UniqueItems] = "true";
            }
        }
Exemplo n.º 22
0
 /// <summary>
 ///     Determines if the SwaggerObject has both a default and an enum defined
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 internal static bool HasDefaultAndEnum(this SwaggerObject entity)
 {
     return(!string.IsNullOrEmpty(entity.Default) && entity.Enum != null);
 }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            string configFileName = "config.json";

            if (!File.Exists(configFileName))
            {
                var streamWriter = File.CreateText(configFileName);

                // Unload the file
                streamWriter.Dispose();
            }

            var configFile = File.OpenText(configFileName);

            ConfigurationData config = JsonConvert.DeserializeObject <ConfigurationData>(configFile.ReadToEnd());

            // Unload the file
            configFile.Dispose();

            if (config == null)
            {
                config = new ConfigurationData()
                {
                    APIUrl          = "",
                    APISwaggerUrl   = "",
                    APINameSpace    = "",
                    ClientNameSpace = "",
                    FolderPath      = ""
                };
            }
            else
            {
                Console.WriteLine("--- DETECTED A CONFIGURATION FILE IN THE SYSTEM");

                Console.WriteLine("> API URL: " + config.APIUrl);

                Console.WriteLine("> API URL FROM SWAGGER FILE: " + config.APISwaggerUrl);

                Console.WriteLine("> API NAMESPACE: " + config.APINameSpace);

                Console.WriteLine("> CLIENT NAMESPACE: " + config.ClientNameSpace);

                Console.WriteLine("> FOLDER: " + config.FolderPath);

                Console.WriteLine();
            }

            Console.WriteLine("--- GETTING THE CONFIGURATION FROM THE USER");

            string inputFromUser = "";

            Console.WriteLine("> ENTER THE API URL: (EXAMPLE: \"http://api.yourwebsite.com/\")");
            inputFromUser = Console.ReadLine();

            if (!string.IsNullOrWhiteSpace(inputFromUser))
            {
                config.APIUrl = inputFromUser;
            }

            Console.WriteLine("> ENTER THE API URL FROM SWAGGER FILE: (EXAMPLE: \"http://api.yourwebsite.com/swagger/docs/v1\")");
            inputFromUser = Console.ReadLine();

            if (!string.IsNullOrWhiteSpace(inputFromUser))
            {
                config.APISwaggerUrl = inputFromUser;
            }

            Console.WriteLine("> ENTER THE API NAMESPACE: (EXAMPLE: \"ExampleNameSpace\")");
            inputFromUser = Console.ReadLine();

            if (!string.IsNullOrWhiteSpace(inputFromUser))
            {
                config.APINameSpace = inputFromUser;
            }

            Console.WriteLine("> ENTER THE CLIENT NAMESPACE: (EXAMPLE: \"ExampleNameSpace.Web.MyClientAPI\")");
            inputFromUser = Console.ReadLine();

            if (!string.IsNullOrWhiteSpace(inputFromUser))
            {
                config.ClientNameSpace = inputFromUser;
            }

            Console.WriteLine("> ENTER THE FOLDER: (EXAMPLE: \"C:\\TEMP_SWAGGER\\\")");
            inputFromUser = Console.ReadLine();

            if (!string.IsNullOrWhiteSpace(inputFromUser))
            {
                config.FolderPath = inputFromUser;
            }

            if (!config.FolderPath.EndsWith("\\"))
            {
                config.FolderPath = config.FolderPath + "\\";
            }

            File.WriteAllText(configFileName, JsonConvert.SerializeObject(config));

            Console.WriteLine("--- CONFIGURATION INSERTED");

            Console.WriteLine("--- GETTING THE JSON FILE FROM SWAGGER");

            SwaggerObject swaggerObject = GetSwaggerObject(config.APISwaggerUrl);

            Console.WriteLine("- JSON File Loaded");

            Console.WriteLine("--- GROUPING THE DATA FROM THE JSON FILE");

            DateTime executionDateTime = DateTime.Now;

            var services = SwaggerReader.ReadServices(swaggerObject, config.APINameSpace, config.ClientNameSpace);

            Console.WriteLine("> SERVICES (Quantity: " + services.Count + ")");
            Console.WriteLine("");

            foreach (var serviceClass in services)
            {
                Console.WriteLine(serviceClass.ToString());
            }

            Console.WriteLine("> EXECUTION TIME: " + (DateTime.Now - executionDateTime).TotalSeconds + " SECONDS");
            Console.WriteLine("");
            Console.WriteLine("> PRESS ANY KEY TO GENERATE THE FILES...");

            Console.ReadLine();

            executionDateTime = DateTime.Now;

            var viewModels = SwaggerReader.ReadViewModels(swaggerObject, config.APINameSpace, config.ClientNameSpace);

            Console.WriteLine("> VIEW MODELS (Quantity: " + viewModels.Count + ")");
            Console.WriteLine("");

            foreach (var viewModelClass in viewModels)
            {
                Console.WriteLine(viewModelClass.ToString());
            }

            Console.WriteLine("> EXECUTION TIME: " + (DateTime.Now - executionDateTime).TotalSeconds + " SECONDS");
            Console.WriteLine("");
            Console.WriteLine("> PRESS ANY KEY TO GENERATE THE FILES...");

            Console.ReadLine();

            Infrastructure infrastructure = new Infrastructure();

            infrastructure.AdditionalHeaderParameters = SwaggerReader.ReadAdditionalHeaders(swaggerObject);

            executionDateTime = DateTime.Now;

            ConfigureFolder(config.FolderPath);

            Console.WriteLine("> CREATING THE SERVICES FILES");
            Console.WriteLine("");

            SwaggerWriter.WriteServices(services, infrastructure, config.APIUrl, config.APINameSpace, config.ClientNameSpace, config.FolderPath);

            Console.WriteLine("");
            Console.WriteLine("> CREATING THE VIEW MODELS FILES");
            Console.WriteLine("");

            SwaggerWriter.WriteViewModels(viewModels, config.APINameSpace, config.ClientNameSpace, config.FolderPath);

            Console.WriteLine("");
            Console.WriteLine("> EXECUTION TIME: " + (DateTime.Now - executionDateTime).TotalSeconds + " SECONDS");
            Console.WriteLine("");
            Console.WriteLine("> PROCCESS EXECUTED WITH SUCCESS");

            Console.ReadLine();
        }