Ejemplo n.º 1
0
        private static ClientGeneratorModel GetGeneratorModel(string wszInputFilePath, RamlInfo ramlInfo)
        {
            var rootName = NetNamingMapper.GetObjectName(Path.GetFileNameWithoutExtension(wszInputFilePath));

            if (!rootName.ToLower().Contains("api"))
            {
                rootName += "Api";
            }
            var model = new ClientGeneratorService(ramlInfo.RamlDocument, rootName).BuildModel();

            return(model);
        }
Ejemplo n.º 2
0
        public static string DecodeRaml1Type(string type)
        {
            // TODO: can I handle this better ?
            if (type.Contains("(") || type.Contains("|"))
            {
                return("object");
            }

            if (type.EndsWith("[][]")) // array of arrays
            {
                var strippedType = type.Substring(0, type.Length - 4);
                if (NewNetTypeMapper.Map(strippedType) == null)
                {
                    strippedType = NetNamingMapper.GetObjectName(strippedType);
                }

                var decodeRaml1Type = CollectionTypeHelper.GetCollectionType(CollectionTypeHelper.GetCollectionType(strippedType));
                return(decodeRaml1Type);
            }

            if (type.EndsWith("[]")) // array
            {
                var strippedType = type.Substring(0, type.Length - 2);

                if (NewNetTypeMapper.Map(strippedType) == null)
                {
                    strippedType = NetNamingMapper.GetObjectName(strippedType);
                }

                var decodeRaml1Type = CollectionTypeHelper.GetCollectionType(strippedType);
                return(decodeRaml1Type);
            }

            if (type.EndsWith("{}")) // Map
            {
                var subtype = type.Substring(0, type.Length - 2);
                var netType = NewNetTypeMapper.Map(subtype);
                if (netType != null)
                {
                    return("IDictionary<string, " + netType + ">");
                }

                return("IDictionary<string, " + NetNamingMapper.GetObjectName(subtype) + ">");
            }

            if (CollectionTypeHelper.IsCollection(type))
            {
                return(type);
            }

            return(NetNamingMapper.GetObjectName(type));
        }
Ejemplo n.º 3
0
 private ApiEnum CreateEnum(ScalarShape scalar, IDictionary <string, ApiEnum> existingEnums, IDictionary <string, string> warnings, IDictionary <string, ApiEnum> newEnums)
 {
     return(new ApiEnum
     {
         Name = NetNamingMapper.GetObjectName(scalar.Name),
         Description = scalar.Description,
         Values = scalar.Values.Distinct()
                  .Select(p => new PropertyBase {
             Name = NetNamingMapper.GetEnumValueName(p), OriginalName = p.Replace("\\", "\\\\")
         })
                  .ToArray()
     });
 }
Ejemplo n.º 4
0
        private static string GetCollectionType(Property prop, string itemType)
        {
            if (NewNetTypeMapper.IsPrimitiveType(itemType))
            {
                return(CollectionTypeHelper.GetCollectionType(itemType));
            }

            if (CollectionTypeHelper.IsCollection(itemType))
            {
                return(CollectionTypeHelper.GetCollectionType(itemType));
            }

            return(CollectionTypeHelper.GetCollectionType(NetNamingMapper.GetObjectName(itemType)));
        }
Ejemplo n.º 5
0
        private void ParseComplexTypes(IDictionary <string, ApiObject> objects, Newtonsoft.JsonV4.Schema.JsonSchema schema, Newtonsoft.JsonV4.Schema.JsonSchema propertySchema, Property prop, KeyValuePair <string, Newtonsoft.JsonV4.Schema.JsonSchema> property, IDictionary <string, ApiEnum> enums)
        {
            if (propertySchema.Type.HasValue &&
                (propertySchema.Type == Newtonsoft.JsonV4.Schema.JsonSchemaType.Object || propertySchema.Type.Value.ToString().Contains("Object")) &&
                propertySchema.Properties != null)
            {
                if (!string.IsNullOrWhiteSpace(schema.Id) && ids.Contains(schema.Id))
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(schema.Id))
                {
                    ids.Add(schema.Id);
                }

                var type = string.IsNullOrWhiteSpace(property.Value.Id) ? property.Key : property.Value.Id;
                ParseObject(type, propertySchema.Properties, objects, enums, propertySchema);
                prop.Type = NetNamingMapper.GetObjectName(type);
            }
            else if (propertySchema.Type.HasValue &&
                     propertySchema.Type == Newtonsoft.JsonV4.Schema.JsonSchemaType.Object && propertySchema.OneOf != null && propertySchema.OneOf.Count > 0 && schema.Definitions != null && schema.Definitions.Count > 0)
            {
                string baseTypeName = NetNamingMapper.GetObjectName(property.Key);

                if (schemaObjects.ContainsKey(baseTypeName) || objects.ContainsKey(baseTypeName) || otherObjects.ContainsKey(baseTypeName))
                {
                    return;
                }

                objects.Add(baseTypeName,
                            new ApiObject
                {
                    Name       = baseTypeName,
                    Properties = new List <Property>()
                });

                foreach (var innerSchema in propertySchema.OneOf)
                {
                    var definition = schema.Definitions.FirstOrDefault(k => k.Value == innerSchema);
                    ParseObject(property.Key + definition.Key, innerSchema.Properties, objects, enums, innerSchema, baseTypeName);
                }

                prop.Type = baseTypeName;
            }
            else if (propertySchema.Type == Newtonsoft.JsonV4.Schema.JsonSchemaType.Array)
            {
                ParseArray(objects, propertySchema, prop, property, enums);
            }
        }
        public void Generate(EndPoint resource, string url, ClientGeneratorMethod clientGeneratorMethod,
                             IDictionary <string, ApiObject> uriParameterObjects, IDictionary <string, Parameter> parentUriParameters)
        {
            var parameters = GetUriParameters(resource, url, parentUriParameters).ToArray();

            clientGeneratorMethod.UriParameters = parameters;

            if (!parameters.Any())
            {
                return;
            }

            var name = NetNamingMapper.GetObjectName(url) + "UriParameters";

            clientGeneratorMethod.UriParametersType = name;
            if (uriParameterObjects.ContainsKey(name))
            {
                return;
            }

            var properties = new List <Property>();

            if (resource.Parameters != null)
            {
                properties.AddRange(queryParametersParser.ConvertParametersToProperties(resource.Parameters));
            }

            var urlParameters     = ExtractParametersFromUrl(url).ToArray();
            var matchedParameters = MatchParameters(parentUriParameters, urlParameters);

            foreach (var urlParameter in matchedParameters)
            {
                var property = ConvertGeneratorParamToProperty(urlParameter);
                if (properties.All(p => !String.Equals(property.Name, p.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    properties.Add(property);
                }
            }

            var apiObject = new ApiObject
            {
                Name        = name,
                Description = "Uri Parameters for resource " + resource.Path,
                Properties  = properties
            };

            uriParameterObjects.Add(name, apiObject);
        }
Ejemplo n.º 7
0
        private static string GetType(KeyValuePair <string, JsonSchema> property, bool isEnum, string enumName)
        {
            if (isEnum)
            {
                return(enumName);
            }

            var type = NetTypeMapper.Map(property.Value.Type);

            if (!string.IsNullOrWhiteSpace(type))
            {
                if (type == "string" || (property.Value.Required != null && property.Value.Required.Value))
                {
                    return(type);
                }

                return(type + "?");
            }

            if (HasMultipleTypes(property))
            {
                return(HandleMultipleTypes(property));
            }

            if (!string.IsNullOrWhiteSpace(property.Value.Id))
            {
                return(NetNamingMapper.GetObjectName(property.Value.Id));
            }

            // if it is a "body less" array then I assume it's an array of strings
            if (property.Value.Type == JsonSchemaType.Array && (property.Value.Items == null || !property.Value.Items.Any()))
            {
                return(CollectionTypeHelper.GetCollectionType("string"));
            }

            // if it is a "body less" object then use object as the type
            if (property.Value.Type == JsonSchemaType.Object && (property.Value.Properties == null || !property.Value.Properties.Any()))
            {
                return("object");
            }

            if (property.Value == null)
            {
                return(null);
            }

            return(NetNamingMapper.GetObjectName(property.Key));
        }
Ejemplo n.º 8
0
        private void ParseArray(IDictionary <string, ApiObject> objects, Newtonsoft.JsonV4.Schema.JsonSchema schema, Property prop, KeyValuePair <string, Newtonsoft.JsonV4.Schema.JsonSchema> property, IDictionary <string, ApiEnum> enums)
        {
            var netType = NetTypeMapper.Map(schema.Items.First().Type);

            if (netType != null)
            {
                prop.Type = CollectionTypeHelper.GetCollectionType(netType);
            }
            else
            {
                prop.Type = CollectionTypeHelper.GetCollectionType(NetNamingMapper.GetObjectName(property.Key));
                foreach (var item in schema.Items)
                {
                    ParseObject(property.Key, item.Properties, objects, enums, item);
                }
            }
        }
Ejemplo n.º 9
0
        private void CreateMultipleType(ClientGeneratorMethod generatedMethod)
        {
            var properties = BuildProperties(generatedMethod);

            var name = NetNamingMapper.GetObjectName("Multiple" + generatedMethod.Name + "Header");

            var apiObject = new ApiObject
            {
                Name        = name,
                Description = "Multiple Header Types " + string.Join(", ", properties.Select(p => p.Name)),
                Properties  = properties,
                IsMultiple  = true
            };

            responseHeadersObjects.Add(new KeyValuePair <string, ApiObject>(name, apiObject));

            generatedMethod.ResponseHeaderType = ClientGeneratorMethod.ModelsNamespacePrefix + name;
        }
Ejemplo n.º 10
0
        public ApiObject Parse(string key, string schema, IDictionary <string, ApiObject> objects, string modelsNamespace)
        {
            var codeNamespace = Process(schema, modelsNamespace);

            var code = GenerateCode(codeNamespace);

            if (HasDuplicatedObjects(objects, codeNamespace))
            {
                return(null);
            }

            if (codeNamespace.Types.Count == 0)
            {
                return(null);
            }

            return(new ApiObject {
                Name = NetNamingMapper.GetObjectName(key), GeneratedCode = code
            });
        }
Ejemplo n.º 11
0
        private string ParseObject(string key, IDictionary <string, JsonSchema> schema, IDictionary <string, ApiObject> objects, IDictionary <string, ApiEnum> enums)
        {
            if (schema == null)
            {
                return(null);
            }

            var obj = new ApiObject
            {
                Name       = NetNamingMapper.GetObjectName(key),
                Properties = ParseSchema(schema, objects, enums)
            };

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

            if (!obj.Properties.Any())
            {
                return(null);
            }

            // Avoid duplicated keys and names or no properties
            if (objects.ContainsKey(key) || objects.Any(o => o.Value.Name == obj.Name) ||
                otherObjects.ContainsKey(key) || otherObjects.Any(o => o.Value.Name == obj.Name) ||
                schemaObjects.ContainsKey(key) || schemaObjects.Any(o => o.Value.Name == obj.Name))
            {
                if (UniquenessHelper.HasSameProperties(obj, objects, key, otherObjects, schemaObjects))
                {
                    return(key);
                }

                obj.Name = UniquenessHelper.GetUniqueName(objects, obj.Name, otherObjects, schemaObjects);
                key      = UniquenessHelper.GetUniqueKey(objects, key, otherObjects);
            }

            objects.Add(key, obj);
            return(key);
        }
Ejemplo n.º 12
0
        private static string GetType(KeyValuePair <string, Newtonsoft.JsonV4.Schema.JsonSchema> property, bool isEnum, string enumName, ICollection <string> requiredProps)
        {
            if (property.Value.OneOf != null && property.Value.OneOf.Count > 0)
            {
                return(NetNamingMapper.GetObjectName(property.Key));
            }

            if (isEnum)
            {
                return(enumName);
            }

            var type = NetTypeMapper.Map(property.Value.Type);

            if (!string.IsNullOrWhiteSpace(type))
            {
                if (type == "string" || (requiredProps != null && requiredProps.Contains(property.Key)))
                {
                    return(type);
                }

                return(type + "?");
            }

            if (HasMultipleTypes(property))
            {
                return(HandleMultipleTypes(property));
            }

            if (!string.IsNullOrWhiteSpace(property.Value.Id))
            {
                return(NetNamingMapper.GetObjectName(property.Value.Id));
            }

            return(NetNamingMapper.GetObjectName(property.Key));
        }
 public void Should_Avoid_Brackets_In_Object_Name()
 {
     Assert.Equal("Sales", NetNamingMapper.GetObjectName("sales[]"));
     Assert.Equal("Salesperson", NetNamingMapper.GetObjectName("(sales|person)[]"));
 }
 public void Should_Convert_Object_Names()
 {
     Assert.Equal("GetSalesId", NetNamingMapper.GetObjectName("get-/sales/{id}"));
 }
 public void Should_Avoid_Single_Quote_In_Object_Name()
 {
     Assert.Equal("GetSalesId", NetNamingMapper.GetObjectName("get-/sales('{id}')"));
     Assert.Equal("GetSalesId", NetNamingMapper.GetObjectName("get-/sales'id'"));
 }
Ejemplo n.º 16
0
 private bool ResponseHasKey(string key)
 {
     return(schemaObjects.ContainsKey(key) || schemaResponseObjects.ContainsKey(key) ||
            schemaObjects.ContainsKey(NetNamingMapper.GetObjectName(key)) ||
            schemaResponseObjects.ContainsKey(NetNamingMapper.GetObjectName(key)));
 }
Ejemplo n.º 17
0
        private Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> > ParseObject(Guid id, string key, Shape shape,
                                                                                                                                IDictionary <string, ApiObject> existingObjects, bool isRootType)
        {
            if (AlreadyExists(existingObjects, existingEnums, shape.Id))
            {
                return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >
                           (newObjects, newEnums, new Dictionary <Guid, string>()));
            }

            // if is array of scalar or array of object there's no new object, except when is a root type
            if (!isRootType && shape is ArrayShape array && (array.Items is ScalarShape || array.Items is AnyShape))
            {
                return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >
                           (newObjects, newEnums, new Dictionary <Guid, string>()));
            }

            var linkedType = new Dictionary <Guid, string>();

            var apiObj = new ApiObject
            {
                Id          = id,
                AmfId       = shape.Id,
                BaseClass   = GetBaseClass(shape),
                IsArray     = shape is ArrayShape,
                IsScalar    = shape is ScalarShape,
                IsUnionType = shape is UnionShape,
                Name        = NetNamingMapper.GetObjectName(key),
                Type        = NetNamingMapper.GetObjectName(key),
                Description = shape.Description,
                Example     = MapExample(shape)
            };

            if (isRootType && apiObj.IsScalar)
            {
                apiObj.Type = NewNetTypeMapper.GetNetType(shape, existingObjects);
            }

            if (isRootType && apiObj.IsArray && shape is ArrayShape arrShape)
            {
                var itemShape = arrShape.Items;
                if (itemShape is NodeShape)
                {
                    var itemId = Guid.NewGuid();
                    ParseObject(itemId, itemShape.Name, itemShape, existingObjects, false);

                    apiObj.Type = NewNetTypeMapper.GetNetType(shape, existingObjects);
                }
                else
                {
                    //if (newObjects.ContainsKey(itemShape.Id))
                    //    apiObj.Type = CollectionTypeHelper.GetCollectionType(newObjects[itemShape.Id].Type);
                    //else if(existingObjects.ContainsKey(itemShape.Id))
                    //    apiObj.Type = CollectionTypeHelper.GetCollectionType(existingObjects[itemShape.Id].Type);
                    //else
                    apiObj.Type = NewNetTypeMapper.GetNetType(shape, existingObjects);
                }
            }

            if (shape is NodeShape node && node.Properties.Count() == 1 && node.Properties.First().Path != null && node.Properties.First().Path.StartsWith("/") &&
                node.Properties.First().Path.EndsWith("/"))
            {
                apiObj.IsMap = true;
                var valueType = "object";
                if (node.Properties.First().Range != null)
                {
                    valueType = NewNetTypeMapper.GetNetType(node.Properties.First().Range, existingObjects);
                }

                apiObj.Type = $"Dictionary<string, {valueType}>";
                AddNewObject(shape, apiObj);
                return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >(newObjects, newEnums, linkedType));
            }

            apiObj.Properties = MapProperties(shape, apiObj.Name).ToList();

            ApiObject match = null;

            if (existingObjects.Values.Any(o => o.Name == apiObj.Name) || newObjects.Values.Any(o => o.Name == apiObj.Name))
            {
                if (UniquenessHelper.HasSameProperties(apiObj, existingObjects, key, newObjects, emptyDic))
                {
                    return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >(newObjects, newEnums, linkedType));
                }

                match = HandleNameDuplication(id, apiObj, key, linkedType);
            }

            if (existingObjects.Values.Any(o => o.Type == apiObj.Type) || newObjects.Values.Any(o => o.Type == apiObj.Type))
            {
                if (UniquenessHelper.HasSameProperties(apiObj, existingObjects, key, newObjects, emptyDic))
                {
                    return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >(newObjects, newEnums, linkedType));
                }

                match = HandleTypeDuplication(id, apiObj, key, linkedType);
            }

            if (match != null)
            {
                return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >(newObjects, newEnums, linkedType));
            }

            //if (match == null)
            //{
            //    match = UniquenessHelper.FirstOrDefaultWithSameProperties(apiObj, existingObjects, key, newObjects, emptyDic);
            //    if (match != null)
            //    {
            //        if (!linkedType.ContainsKey(id))
            //            linkedType.Add(id, match.Type);
            //    }
            //}

            if (shape.Inherits != null && shape.Inherits.Count() == 1)
            {
                var baseClass = NewNetTypeMapper.GetNetType(shape.Inherits.First(), existingObjects, newObjects, existingEnums, newEnums);
                if (!string.IsNullOrWhiteSpace(baseClass))
                {
                    apiObj.BaseClass = CollectionTypeHelper.GetConcreteType(baseClass);
                }
            }

            AddNewObject(shape, apiObj);

            return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum>, IDictionary <Guid, string> >(newObjects, newEnums, linkedType));
        }
Ejemplo n.º 18
0
        private Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum> > ParseObject(string key, Shape shape,
                                                                                                    IDictionary <string, ApiObject> existingObjects, bool isRootType)
        {
            var apiObj = new ApiObject
            {
                BaseClass   = GetBaseClass(shape),
                IsArray     = shape is ArrayShape,
                IsScalar    = shape is ScalarShape,
                IsUnionType = shape is UnionShape,
                Name        = NetNamingMapper.GetObjectName(key),
                Type        = NetNamingMapper.GetObjectName(key),
                Description = shape.Description,
                Example     = MapExample(shape)
            };

            if (isRootType && (apiObj.IsArray || apiObj.IsScalar))
            {
                apiObj.Type = NewNetTypeMapper.GetNetType(shape, existingObjects);
            }

            if (shape is NodeShape node && node.Properties.Count() == 1 && node.Properties.First().Path.StartsWith("/") &&
                node.Properties.First().Path.EndsWith("/"))
            {
                apiObj.IsMap = true;
                var valueType = "object";
                if (node.Properties.First().Range != null)
                {
                    valueType = NewNetTypeMapper.GetNetType(node.Properties.First().Range, existingObjects);
                }

                apiObj.Type = $"Dictionary<string, {valueType}>";
                new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum> >(newObjects, newEnums);
            }

            apiObj.Properties = MapProperties(shape, apiObj.Name).ToList();

            if (existingObjects.Values.Any(o => o.Name == apiObj.Name))
            {
                if (UniquenessHelper.HasSameProperties(apiObj, existingObjects, key, new Dictionary <string, ApiObject>(), new Dictionary <string, ApiObject>()))
                {
                    return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum> >(newObjects, newEnums));
                }

                apiObj.Name = UniquenessHelper.GetUniqueName(existingObjects, apiObj.Name, new Dictionary <string, ApiObject>(), new Dictionary <string, ApiObject>());
                foreach (var prop in apiObj.Properties)
                {
                    prop.ParentClassName = apiObj.Name;
                }
            }
            if (existingObjects.Values.Any(o => o.Type == apiObj.Type))
            {
                if (UniquenessHelper.HasSameProperties(apiObj, existingObjects, key, new Dictionary <string, ApiObject>(), new Dictionary <string, ApiObject>()))
                {
                    return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum> >(newObjects, newEnums));
                }

                apiObj.Type = UniquenessHelper.GetUniqueName(existingObjects, apiObj.Type, new Dictionary <string, ApiObject>(), new Dictionary <string, ApiObject>());
            }

            if (!newObjects.ContainsKey(apiObj.Type))
            {
                newObjects.Add(apiObj.Type, apiObj);
            }

            return(new Tuple <IDictionary <string, ApiObject>, IDictionary <string, ApiEnum> >(newObjects, newEnums));
        }
Ejemplo n.º 19
0
        public static string GetNetType(Shape shape, IDictionary <string, ApiObject> existingObjects = null,
                                        IDictionary <string, ApiObject> newObjects = null, IDictionary <string, ApiEnum> existingEnums = null, IDictionary <string, ApiEnum> newEnums = null)
        {
            if (!string.IsNullOrWhiteSpace(shape.LinkTargetName))
            {
                return(NetNamingMapper.GetObjectName(GetTypeFromLinkOrId(shape.LinkTargetName)));
            }

            if (shape is ScalarShape scalar)
            {
                if (shape.Values != null && shape.Values.Any())
                {
                    var key = GetTypeFromLinkOrId(shape.Id);
                    if (existingEnums != null && existingEnums.ContainsKey(key))
                    {
                        return(existingEnums[key].Name);
                    }
                    if (newEnums != null && newEnums.ContainsKey(key))
                    {
                        return(newEnums[key].Name);
                    }
                }
                return(GetNetType(scalar.DataType.Substring(scalar.DataType.LastIndexOf('#') + 1), scalar.Format));
            }
            if (shape is ArrayShape array)
            {
                return(CollectionTypeHelper.GetCollectionType(GetNetType(array.Items, existingObjects, newObjects, existingEnums, newEnums)));
            }

            if (shape is FileShape file)
            {
                return(TypeStringConversion["file"]);
            }

            if (shape.Id.Contains("#/declarations"))
            {
                var key = GetTypeFromLinkOrId(shape.Id);
                if (existingObjects != null && (existingObjects.ContainsKey(key) ||
                                                existingObjects.Keys.Any(k => k.ToLowerInvariant() == key.ToLowerInvariant())))
                {
                    if (existingObjects.ContainsKey(key))
                    {
                        return(existingObjects[key].Type);
                    }

                    return(existingObjects.First(kv => kv.Key.ToLowerInvariant() == key.ToLowerInvariant()).Value.Type);
                }
                if (newObjects != null && newObjects.ContainsKey(key))
                {
                    return(newObjects[key].Type);
                }
            }

            if (shape.Inherits.Count() == 1)
            {
                if (shape is NodeShape nodeShape)
                {
                    if (nodeShape.Properties.Count() == 0)
                    {
                        return(GetNetType(nodeShape.Inherits.First(), existingObjects, newObjects, existingEnums, newEnums));
                    }
                }
                if (shape.Inherits.First() is ArrayShape arrayShape)
                {
                    return(CollectionTypeHelper.GetCollectionType(GetNetType(arrayShape.Items, existingObjects, newObjects, existingEnums, newEnums)));
                }

                if (shape is AnyShape any)
                {
                    var key = NetNamingMapper.GetObjectName(any.Inherits.First().Name);
                    if (existingObjects != null && existingObjects.ContainsKey(key))
                    {
                        return(key);
                    }
                    if (newObjects != null && newObjects.ContainsKey(key))
                    {
                        return(key);
                    }
                }
            }
            if (shape.Inherits.Count() > 0)
            {
                //TODO: check
            }

            if (shape.GetType() == typeof(AnyShape))
            {
                return(GetNetType("any", null));
            }

            if (shape is UnionShape)
            {
                return("object");
            }

            return(NetNamingMapper.GetObjectName(shape.Name));
        }
Ejemplo n.º 20
0
        public ApiObject Parse(string key, string jsonSchema, IDictionary <string, ApiObject> objects, IDictionary <string, string> warnings,
                               IDictionary <string, ApiEnum> enums, IDictionary <string, ApiObject> otherObjects, IDictionary <string, ApiObject> schemaObjects)
        {
            this.otherObjects  = otherObjects;
            this.schemaObjects = schemaObjects;
            var obj = new ApiObject
            {
                Name       = NetNamingMapper.GetObjectName(key),
                Properties = new List <Property>(),
                JSONSchema = jsonSchema.Replace(Environment.NewLine, "").Replace("\r\n", "").Replace("\n", "")
                             .Replace("\\", "\\\\").Replace("\"", "\\\"")
                             // .Replace("\\/", "\\\\/").Replace("\"", "\\\"").Replace("\\\\\"", "\\\\\\\"")
            };
            JsonSchema schema = null;

            Newtonsoft.JsonV4.Schema.JsonSchema v4Schema = null;
            if (jsonSchema.Contains("\"oneOf\""))
            {
                v4Schema = ParseV4Schema(key, jsonSchema, warnings, objects);
            }
            else
            {
                schema = ParseV3OrV4Schema(key, jsonSchema, warnings, ref v4Schema, objects);
            }

            if (schema == null && v4Schema == null)
            {
                return(obj);
            }

            if (schema != null)
            {
                if (schema.Type == JsonSchemaType.Array)
                {
                    obj.IsArray = true;
                    if (schema.Items != null && schema.Items.Any())
                    {
                        if (schema.Items.First().Properties != null)
                        {
                            ParseProperties(objects, obj.Properties, schema.Items.First().Properties, enums);
                        }
                        else
                        {
                            obj.Type = NetTypeMapper.Map(schema.Items.First().Type);
                        }
                    }
                }
                else
                {
                    ParseProperties(objects, obj.Properties, schema.Properties, enums);
                    AdditionalProperties(obj.Properties, schema);
                }
            }
            else
            {
                if (v4Schema.Type == Newtonsoft.JsonV4.Schema.JsonSchemaType.Array)
                {
                    obj.IsArray = true;
                    if (v4Schema.Items != null && v4Schema.Items.Any())
                    {
                        if (v4Schema.Items.First().Properties != null)
                        {
                            ParseProperties(objects, obj.Properties, v4Schema.Items.First(), enums);
                        }
                        else
                        {
                            obj.Type = NetTypeMapper.Map(v4Schema.Items.First().Type);
                        }
                    }
                }
                else
                {
                    ParseProperties(objects, obj.Properties, v4Schema, enums);
                }
            }
            return(obj);
        }
Ejemplo n.º 21
0
        private string DecodeResponseRaml1Type(string type)
        {
            // TODO: can I handle this better ?
            if (type.Contains("(") || type.Contains("|"))
            {
                return("string");
            }

            if (type.EndsWith("[][]")) // array of arrays
            {
                var subtype = type.Substring(0, type.Length - 4);
                if (NewNetTypeMapper.IsPrimitiveType(subtype))
                {
                    subtype = NewNetTypeMapper.Map(subtype);
                }
                else
                {
                    subtype = NetNamingMapper.GetObjectName(subtype);
                }

                return(CollectionTypeHelper.GetCollectionType(CollectionTypeHelper.GetCollectionType(subtype)));
            }

            if (type.EndsWith("[]")) // array
            {
                var subtype = type.Substring(0, type.Length - 2);
                if (NewNetTypeMapper.IsPrimitiveType(subtype))
                {
                    subtype = NewNetTypeMapper.Map(subtype);
                }
                else
                {
                    subtype = NetNamingMapper.GetObjectName(subtype);
                }

                return(CollectionTypeHelper.GetCollectionType(subtype));
            }

            if (type.EndsWith("{}")) // Map
            {
                var subtype = type.Substring(0, type.Length - 2);
                var netType = NewNetTypeMapper.Map(subtype);
                if (!string.IsNullOrWhiteSpace(netType))
                {
                    return("IDictionary<string, " + netType + ">");
                }

                var objectType = GetReturnTypeFromName(subtype);
                if (!string.IsNullOrWhiteSpace(objectType))
                {
                    return("IDictionary<string, " + objectType + ">");
                }

                return("IDictionary<string, object>");
            }

            if (NewNetTypeMapper.IsPrimitiveType(type))
            {
                return(NewNetTypeMapper.Map(type));
            }

            return(type);
        }
Ejemplo n.º 22
0
        public GeneratorParameter GetRequestParameter(string key, Operation method, EndPoint resource, string fullUrl, IEnumerable <string> defaultMediaTypes)
        {
            if (method.Request == null || !method.Request.Payloads.Any())
            {
                return new GeneratorParameter {
                           Name = "content", Type = "string"
                }
            }
            ;

            var mimeType = GetMimeType(method.Request.Payloads, defaultMediaTypes);
            var type     = NewNetTypeMapper.GetNetType(mimeType, schemaObjects, null, enums);

            if (RamlTypesHelper.IsPrimitiveOrSchemaObject(type, schemaObjects))
            {
                return(new GeneratorParameter //TODO: check
                {
                    Name = string.IsNullOrWhiteSpace(mimeType.Name) ? GetParameterName(type) : GetParameterName(mimeType.Name),
                    Description = mimeType.Description,
                    Type = type
                });
            }

            var apiObjectByKey = GetRequestApiObjectByKey(key);

            if (apiObjectByKey != null)
            {
                return(CreateGeneratorParameter(apiObjectByKey));
            }

            apiObjectByKey = GetRequestApiObjectByKey(NetNamingMapper.GetObjectName(key));
            if (apiObjectByKey != null)
            {
                return(CreateGeneratorParameter(apiObjectByKey));
            }

            var requestKey = key + GeneratorServiceBase.RequestContentSuffix;

            apiObjectByKey = GetRequestApiObjectByKey(requestKey);
            if (apiObjectByKey != null)
            {
                return(CreateGeneratorParameter(apiObjectByKey));
            }

            if (linkKeysWithObjectNames.ContainsKey(key))
            {
                var linkedKey = linkKeysWithObjectNames[key];
                apiObjectByKey = GetRequestApiObjectByKey(linkedKey);
                if (apiObjectByKey != null)
                {
                    return(CreateGeneratorParameter(apiObjectByKey));
                }
            }

            if (linkKeysWithObjectNames.ContainsKey(requestKey))
            {
                var linkedKey = linkKeysWithObjectNames[requestKey];
                apiObjectByKey = GetRequestApiObjectByKey(linkedKey);
                if (apiObjectByKey != null)
                {
                    return(CreateGeneratorParameter(apiObjectByKey));
                }
            }

            return(new GeneratorParameter {
                Name = "content", Type = "string"
            });

            //if (mimeType != null)
            //{
            //    if (mimeType.Type != "object" && !string.IsNullOrWhiteSpace(mimeType.Type))
            //    {
            //        var apiObject = GetRequestApiObjectWhenNamed(method, resource, mimeType.Type, fullUrl);
            //        if (apiObject != null)
            //        {
            //            var generatorParameter = new GeneratorParameter
            //            {
            //                Name = apiObject.Name.ToLower(),
            //                Type = GetParamType(mimeType, apiObject),
            //                //Type = DecodeRequestRaml1Type(RamlTypesHelper.GetTypeFromApiObject(apiObject)),
            //                Description = apiObject.Description
            //            };
            //            return generatorParameter;
            //        }
            //    }
            //    if (!string.IsNullOrWhiteSpace(mimeType.Schema))
            //    {
            //        var apiObject = GetRequestApiObjectWhenNamed(method, resource, mimeType.Schema, fullUrl);
            //        if (apiObject != null)
            //            return CreateGeneratorParameter(apiObject);
            //    }
            //}

            //if (resource.Type != null && resource.Type.Any() &&
            //    resourceTypes.Any(rt => rt.ContainsKey(resource.GetSingleType())))
            //{
            //    var verb = RamlTypesHelper.GetResourceTypeVerb(method, resource, resourceTypes);
            //    if (verb != null && verb.Body != null && !string.IsNullOrWhiteSpace(verb.Body.Schema))
            //    {
            //        var apiObject = GetRequestApiObjectWhenNamed(method, resource, verb.Body.Schema, fullUrl);
            //        if (apiObject != null)
            //            return CreateGeneratorParameter(apiObject);
            //    }

            //    if (verb != null && verb.Body != null && !string.IsNullOrWhiteSpace(verb.Body.Type))
            //    {
            //        var apiObject = GetRequestApiObjectWhenNamed(method, resource,  verb.Body.Type, fullUrl);
            //        if (apiObject != null)
            //        {
            //            var generatorParameter = new GeneratorParameter
            //            {
            //                Name = apiObject.Name.ToLower(),
            //                Type = DecodeRequestRaml1Type(RamlTypesHelper.GetTypeFromApiObject(apiObject)),
            //                Description = apiObject.Description
            //            };
            //            return generatorParameter;
            //        }

            //        return new GeneratorParameter { Name = "content", Type = DecodeRequestRaml1Type(verb.Body.Type) };
            //    }
            //}

            //if (mimeType != null)
            //{
            //    string type;
            //    if(!string.IsNullOrWhiteSpace(mimeType.Type))
            //        type = mimeType.Type;
            //    else
            //        type = mimeType.Schema;

            //    if (!string.IsNullOrWhiteSpace(type))
            //    {
            //        var raml1Type = DecodeRequestRaml1Type(type);

            //        if (!string.IsNullOrWhiteSpace(raml1Type))
            //            return new GeneratorParameter {Name = "content", Type = raml1Type};
            //    }
            //}

            //return new GeneratorParameter { Name = "content", Type = "string" };
        }
 private void SetNamespace(string fileName)
 {
     Namespace = VisualStudioAutomationHelper.GetDefaultNamespace(ServiceProvider) + "." +
                 NetNamingMapper.GetObjectName(Path.GetFileNameWithoutExtension(fileName));
 }
 public void Should_Remove_QuestionMark_From_Object_Name()
 {
     Assert.Equal("Optional", NetNamingMapper.GetObjectName("optional?"));
 }
Ejemplo n.º 25
0
        private Property MapProperty(PropertyShape p, string parentClassName)
        {
            var name = GetPropertyName(p);
            var prop = new Property(parentClassName)
            {
                Name     = NetNamingMapper.GetPropertyName(name),
                Required = p.Required,
                Type     = NetNamingMapper.GetObjectName(name),
                InheritanceProvenance = p.InheritanceProvenance
            };

            if (p.Range == null)
            {
                return(prop);
            }

            prop.OriginalName = p.Range.Name;

            prop.AmfId = p.Range.Id;

            prop.Description = p.Range.Description;
            prop.Example     = MapExample(p.Range);
            prop.Type        = NewNetTypeMapper.GetNetType(p.Range, existingObjects, newObjects, existingEnums, newEnums);

            if (p.Range is ScalarShape scalar)
            {
                prop.Pattern   = scalar.Pattern;
                prop.MaxLength = scalar.MaxLength;
                prop.MinLength = scalar.MinLength;
                prop.Maximum   = string.IsNullOrWhiteSpace(scalar.Maximum) ? (double?)null : Convert.ToDouble(scalar.Maximum);
                prop.Minimum   = string.IsNullOrWhiteSpace(scalar.Minimum) ? (double?)null : Convert.ToDouble(scalar.Minimum);
                if (scalar.Values != null && scalar.Values.Any())
                {
                    prop.IsEnum = true;

                    var apiEnum = CreateEnum(scalar, existingEnums, warnings, newEnums);

                    string amfId = apiEnum.AmfId;
                    if (string.IsNullOrWhiteSpace(amfId))
                    {
                        amfId = prop.AmfId ?? prop.Name;
                    }

                    prop.Type = apiEnum.Name;

                    if (newEnums.ContainsKey(amfId))
                    {
                        return(prop);
                    }

                    if (existingEnums.Values.Any(o => o.Name == apiEnum.Name) || newEnums.Values.Any(o => o.Name == apiEnum.Name))
                    {
                        if (UniquenessHelper.HasSamevalues(apiEnum, existingEnums, newEnums))
                        {
                            return(prop);
                        }

                        apiEnum.Name = UniquenessHelper.GetUniqueName(apiEnum.Name, existingEnums, newEnums);
                        prop.Type    = apiEnum.Name;
                    }
                    newEnums.Add(amfId, apiEnum);
                }
                return(prop);
            }

            //if (existingObjects.ContainsKey(prop.Type) || newObjects.ContainsKey(prop.Type))
            //    return prop;

            if (p.Range is NodeShape)
            {
                if (existingObjects.ContainsKey(p.Range.Id))
                {
                    prop.Type = existingObjects[p.Range.Id].Type;
                    return(prop);
                }

                if (newObjects.ContainsKey(p.Range.Id))
                {
                    prop.Type = newObjects[p.Range.Id].Type;
                    return(prop);
                }

                var id = Guid.NewGuid();
                prop.TypeId = id;
                var tuple = ParseObject(id, prop.Name, p.Range, existingObjects, warnings, existingEnums);
                prop.Type = NetNamingMapper.GetObjectName(prop.Name);
            }
            if (p.Range is ArrayShape array)
            {
                if (array.Items is ScalarShape)
                {
                    return(prop);
                }

                if (!string.IsNullOrWhiteSpace(array.Items.LinkTargetName))
                {
                    return(prop);
                }

                var itemType = NewNetTypeMapper.GetNetType(array.Items, existingObjects, newObjects, existingEnums, newEnums);

                GetCollectionType(prop, itemType);

                if (array.Items is NodeShape && itemType == "Items")
                {
                    itemType  = NetNamingMapper.GetObjectName(array.Name);
                    prop.Type = CollectionTypeHelper.GetCollectionType(NetNamingMapper.GetObjectName(array.Name));
                }

                if (existingObjects.ContainsKey(array.Id))
                {
                    return(prop);
                }

                if (array.Items is ScalarShape || array.Items.GetType() == typeof(AnyShape))
                {
                    return(prop);
                }

                var newId = Guid.NewGuid();
                prop.TypeId = newId;
                ParseObject(newId, array.Name, array.Items, existingObjects, warnings, existingEnums);
            }

            foreach (var parent in p.Range.Inherits)
            {
                if (!(parent is ScalarShape) && !NewNetTypeMapper.IsPrimitiveType(prop.Type) &&
                    !(CollectionTypeHelper.IsCollection(prop.Type) && NewNetTypeMapper.IsPrimitiveType(CollectionTypeHelper.GetBaseType(prop.Type))) &&
                    string.IsNullOrWhiteSpace(parent.LinkTargetName))
                {
                    var newId = Guid.NewGuid();
                    ParseObject(newId, prop.Name, parent, existingObjects, warnings, existingEnums);
                }
            }
            return(prop);
        }
 public void Should_Remove_MediaTypeExtension_From_Method_Name()
 {
     Assert.Equal("Users", NetNamingMapper.GetObjectName("users{mediaTypeExtension}"));
 }
Ejemplo n.º 27
0
        private Property MapProperty(PropertyShape p, string parentClassName)
        {
            var prop = new Property(parentClassName)
            {
                Name     = NetNamingMapper.GetObjectName(GetNameFromPath(p.Path)),
                Required = p.Required,
                Type     = NetNamingMapper.GetObjectName(GetNameFromPath(p.Path)) //TODO: check
            };

            if (p.Range == null)
            {
                return(prop);
            }

            prop.Name        = NetNamingMapper.GetObjectName(string.IsNullOrWhiteSpace(p.Path) ? p.Range.Name : GetNameFromPath(p.Path));
            prop.Description = p.Range.Description;
            prop.Example     = MapExample(p.Range);
            prop.Type        = NewNetTypeMapper.GetNetType(p.Range, existingObjects, newObjects, existingEnums, newEnums);

            if (p.Range is ScalarShape scalar)
            {
                prop.Pattern   = scalar.Pattern;
                prop.MaxLength = scalar.MaxLength;
                prop.MinLength = scalar.MinLength;
                prop.Maximum   = string.IsNullOrWhiteSpace(scalar.Maximum) ? (double?)null : Convert.ToDouble(scalar.Maximum);
                prop.Minimum   = string.IsNullOrWhiteSpace(scalar.Minimum) ? (double?)null : Convert.ToDouble(scalar.Minimum);
                if (scalar.Values != null && scalar.Values.Any())
                {
                    // enum ??
                    prop.IsEnum = true;
                    var apiEnum = ParseEnum(scalar, existingEnums, warnings, newEnums);
                    if (!newEnums.ContainsKey(apiEnum.Name))
                    {
                        newEnums.Add(apiEnum.Name, apiEnum);
                    }

                    prop.Type = apiEnum.Name;
                }
                return(prop);
            }

            if (existingObjects.ContainsKey(prop.Type) || newObjects.ContainsKey(prop.Type))
            {
                return(prop);
            }

            if (p.Range is NodeShape)
            {
                var tuple = ParseObject(prop.Name, p.Range, existingObjects, warnings, existingEnums);
                prop.Type = NetNamingMapper.GetObjectName(prop.Name);
            }
            if (p.Range is ArrayShape array)
            {
                if (array.Items is ScalarShape)
                {
                    return(prop);
                }

                var itemType = NewNetTypeMapper.GetNetType(array.Items, existingObjects, newObjects, existingEnums, newEnums);

                prop.Type = CollectionTypeHelper.GetCollectionType(NetNamingMapper.GetObjectName(itemType));

                if (array.Items is NodeShape && itemType == "Items")
                {
                    itemType  = NetNamingMapper.GetObjectName(array.Name);
                    prop.Type = CollectionTypeHelper.GetCollectionType(NetNamingMapper.GetObjectName(array.Name));
                }

                if (existingObjects.ContainsKey(itemType) || newObjects.ContainsKey(itemType))
                {
                    return(prop);
                }

                ParseObject(array.Name, array.Items, existingObjects, warnings, existingEnums);
            }

            foreach (var parent in p.Range.Inherits)
            {
                if (!(parent is ScalarShape) && !NewNetTypeMapper.IsPrimitiveType(prop.Type) &&
                    !(CollectionTypeHelper.IsCollection(prop.Type) && NewNetTypeMapper.IsPrimitiveType(CollectionTypeHelper.GetBaseType(prop.Type))) &&
                    string.IsNullOrWhiteSpace(parent.LinkTargetName))
                {
                    ParseObject(prop.Name, parent, existingObjects, warnings, existingEnums);
                }
            }
            return(prop);
        }
 public void Should_Avoid_Parentheses_In_Object_Name()
 {
     Assert.Equal("GetSalesId", NetNamingMapper.GetObjectName("get-/sales({id})"));
     Assert.Equal("GetSalesId", NetNamingMapper.GetObjectName("get-/sales(id)"));
 }
Ejemplo n.º 29
0
        protected string GetUniqueObjectName(RAML.Parser.Model.EndPoint resource, RAML.Parser.Model.EndPoint parent)
        {
            string objectName;

            if (resource.Path.StartsWith("/{") && resource.Path.EndsWith("}"))
            {
                objectName = NetNamingMapper.Capitalize(GetObjectNameForParameter(resource));
            }
            else
            {
                if (resource.Path == "/")
                {
                    objectName = "RootUrl";
                }
                else
                {
                    objectName = NetNamingMapper.GetObjectName(resource.Path);
                }

                if (classesNames.Contains(objectName))
                {
                    objectName = NetNamingMapper.Capitalize(GetObjectNameForParameter(resource));
                }
            }

            if (string.IsNullOrWhiteSpace(objectName))
            {
                throw new InvalidOperationException("object name is null for " + resource.Path);
            }

            if (!classesNames.Contains(objectName))
            {
                return(objectName);
            }

            if (parent == null || string.IsNullOrWhiteSpace(parent.Path))
            {
                return(GetUniqueObjectName(objectName));
            }

            if (resource.Path.StartsWith("/{") && parent.Path.EndsWith("}"))
            {
                objectName = NetNamingMapper.Capitalize(GetObjectNameForParameter(parent)) + objectName;
            }
            else
            {
                objectName = NetNamingMapper.GetObjectName(parent.Path) + objectName;
                if (classesNames.Contains(objectName))
                {
                    objectName = NetNamingMapper.Capitalize(GetObjectNameForParameter(parent));
                }
            }

            if (string.IsNullOrWhiteSpace(objectName))
            {
                throw new InvalidOperationException("object name is null for " + resource.Path);
            }

            if (!classesNames.Contains(objectName))
            {
                return(objectName);
            }

            return(GetUniqueObjectName(objectName));
        }
        public void Scaffold(string ramlSource, RamlChooserActionParams parameters)
        {
            var data = parameters.Data;

            if (data == null || data.RamlDocument == null)
            {
                return;
            }

            var model = new WebApiGeneratorService(data.RamlDocument, parameters.ControllersNamespace, parameters.ModelsNamespace).BuildModel();

            var dte  = ServiceProvider.GetService(typeof(SDTE)) as DTE;
            var proj = VisualStudioAutomationHelper.GetActiveProject(dte);

            var contractsFolderItem = VisualStudioAutomationHelper.AddFolderIfNotExists(proj, ContractsFolderName);
            var ramlItem            =
                contractsFolderItem.ProjectItems.Cast <ProjectItem>()
                .First(i => i.Name.ToLowerInvariant() == parameters.TargetFileName.ToLowerInvariant());
            var contractsFolderPath = Path.GetDirectoryName(proj.FullName) + Path.DirectorySeparatorChar +
                                      ContractsFolderName + Path.DirectorySeparatorChar;

            var templates = new[]
            {
                ControllerBaseTemplateName,
                ControllerInterfaceTemplateName,
                ControllerImplementationTemplateName,
                ModelTemplateName,
                EnumTemplateName
            };

            if (!templatesManager.ConfirmWhenIncompatibleServerTemplate(contractsFolderPath, templates))
            {
                return;
            }

            var extensionPath = Path.GetDirectoryName(GetType().Assembly.Location) + Path.DirectorySeparatorChar;

            AddOrUpdateModels(parameters, contractsFolderPath, ramlItem, model, contractsFolderItem, extensionPath);

            AddOrUpdateEnums(parameters, contractsFolderPath, ramlItem, model, contractsFolderItem, extensionPath);

            AddOrUpdateControllerBase(parameters, contractsFolderPath, ramlItem, model, contractsFolderItem, extensionPath);

            AddOrUpdateControllerInterfaces(parameters, contractsFolderPath, ramlItem, model, contractsFolderItem, extensionPath);

            AddOrUpdateControllerImplementations(parameters, contractsFolderPath, proj, model, contractsFolderItem, extensionPath);

            AddJsonSchemaParsingErrors(model.Warnings, contractsFolderPath, contractsFolderItem, ramlItem);

            if (parameters.GenerateUnitTests.HasValue && parameters.GenerateUnitTests.Value)
            {
                var testsProj = VisualStudioAutomationHelper.GetProject(dte, parameters.TestsProjectName);

                parameters.TestsNamespace = VisualStudioAutomationHelper.GetDefaultNamespace(testsProj) + "." +
                                            NetNamingMapper.GetObjectName(Path.GetFileNameWithoutExtension(parameters.RamlFilePath));

                var unitTestsScaffoldService = UnitTestsScaffoldServiceBase.GetScaffoldService(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
                unitTestsScaffoldService.InstallDependencies(testsProj);
                unitTestsScaffoldService.ScaffoldToProject(parameters, testsProj);
            }
        }