/// <summary>
        /// Gets the OpenAPI reference ID.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="isDictionary">Value indicating whether the type is <see cref="Dictionary{TKey, TValue}"/> or not.</param>
        /// <param name="isList">Value indicating whether the type is <see cref="List{T}"/> or not.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the OpenAPI reference ID.</returns>
        public static string GetOpenApiReferenceId(this Type type, bool isDictionary, bool isList, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (isDictionary)
            {
                var name = type.Name.EndsWith("[]") ? "Dictionary_" + type.GetOpenApiSubTypeName(namingStrategy) : type.Name.Split('`').First() + "_" + type.GetOpenApiSubTypeName(namingStrategy);
                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }
            if (isList)
            {
                var name = type.Name.EndsWith("[]") ? "List_" + type.GetOpenApiSubTypeName(namingStrategy) : type.Name.Split('`').First() + "_" + type.GetOpenApiSubTypeName(namingStrategy);
                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }

            if (type.IsGenericType)
            {
                return(namingStrategy.GetPropertyName(type.Name.Split('`').First(), false) + "_" +
                       string.Join("_", type.GenericTypeArguments.Select(a => namingStrategy.GetPropertyName(a.Name, false))));
            }

            return(namingStrategy.GetPropertyName(type.Name, hasSpecifiedName: false));
        }
Пример #2
0
        /// <summary>
        /// Gets the name of the sub type of the given <see cref="Type"/>.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the name of the sub type of the given <see cref="Type"/>.</returns>
        public static string GetOpenApiSubTypeName(this Type type, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (type.IsDictionaryType())
            {
                var name = type.GetGenericArguments()[1].Name;

                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }

            if (type.BaseType == typeof(Array))
            {
                var name = type.GetElementType().Name;

                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }

            if (type.IsArrayType())
            {
                var name = type.GetGenericArguments()[0].Name;

                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }

            return(null);
        }
        public static NewtonsoftJsonSerializer Create(JsonNamingStrategy namingStrategy)
        {
            Newtonsoft.Json.Serialization.NamingStrategy chosenStrategy;
            switch (namingStrategy)
            {
            case JsonNamingStrategy.Default:
                chosenStrategy = new DefaultNamingStrategy();
                break;

            case JsonNamingStrategy.CamelCase:
                chosenStrategy = new CamelCaseNamingStrategy();
                break;

            case JsonNamingStrategy.SnakeCase:
                chosenStrategy = new SnakeCaseNamingStrategy();
                break;

            default:
                throw new ArgumentOutOfRangeException(
                          $"Unhandled JsonNamingStrategy: {namingStrategy}");
            }

            return(new NewtonsoftJsonSerializer(new Newtonsoft.Json.JsonSerializer()
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.None,
                ContractResolver = new DefaultContractResolver()
                {
                    NamingStrategy = chosenStrategy
                }
            }));
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var            resource       = (Resource)value;
            NamingStrategy namingStrategy = null;

            if (serializer.ContractResolver is DefaultContractResolver resolver)
            {
                namingStrategy = resolver.NamingStrategy;
            }
            if (namingStrategy == null)
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            writer.WriteStartObject();

            foreach (var jToken in JToken.FromObject(resource.Value))
            {
                var item = (JProperty)jToken;
                writer.WritePropertyName(namingStrategy.GetPropertyName(item.Name, false));
                item.Value.WriteTo(writer);
            }

            writer.WritePropertyName(namingStrategy.GetPropertyName(nameof(resource.Links), false));
            serializer.Serialize(writer, resource.Links);

            writer.WriteEndObject();
        }
Пример #5
0
        public JsonDeserializer(NamingConvention namingConvention = NamingConvention.CamelHump)
        {
            _jsonSettings = new JsonSerializerSettings();

            NamingStrategy selectedNamingStrategy;

            switch (namingConvention)
            {
            case NamingConvention.CamelHump:
                selectedNamingStrategy = new CamelCaseNamingStrategy(true, false);
                break;

            case NamingConvention.SnakeCase:
                selectedNamingStrategy = new SnakeCaseNamingStrategy(true, false);
                break;

            default:
                selectedNamingStrategy = new DefaultNamingStrategy();
                break;
            }

            _jsonSettings.ContractResolver = new PrivateSetterContractResolver
            {
                NamingStrategy = selectedNamingStrategy
            };
        }
Пример #6
0
        public void DifferentStrategyEquality()
        {
            NamingStrategy s1 = new SnakeCaseNamingStrategy();
            NamingStrategy s2 = new DefaultNamingStrategy();

            Assert.IsFalse(s1.Equals(s2));
            Assert.IsFalse(s1.GetHashCode() == s2.GetHashCode());
        }
Пример #7
0
        public void DefaultNamingStrategyEquality()
        {
            var s1 = new DefaultNamingStrategy();
            var s2 = new DefaultNamingStrategy();

            Assert.IsTrue(s1.Equals(s2));
            Assert.IsTrue(s1.GetHashCode() == s2.GetHashCode());
        }
Пример #8
0
        /// <inheritdoc />
        public IDocument Build(Assembly assembly, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            var paths = new OpenApiPaths();

            var methods = this._helper.GetHttpTriggerMethods(assembly);

            foreach (var method in methods)
            {
                var trigger = this._helper.GetHttpTriggerAttribute(method);
                if (trigger.IsNullOrDefault())
                {
                    continue;
                }

                var function = this._helper.GetFunctionNameAttribute(method);
                if (function.IsNullOrDefault())
                {
                    continue;
                }

                var path = this._helper.GetHttpEndpoint(function, trigger);
                if (path.IsNullOrWhiteSpace())
                {
                    continue;
                }

                var verb = this._helper.GetHttpVerb(trigger);

                var item       = this._helper.GetOpenApiPath(path, paths);
                var operations = item.Operations;

                var operation = this._helper.GetOpenApiOperation(method, function, verb);
                if (operation.IsNullOrDefault())
                {
                    continue;
                }

                operation.Parameters  = this._helper.GetOpenApiParameters(method, trigger);
                operation.RequestBody = this._helper.GetOpenApiRequestBody(method);
                operation.Responses   = this._helper.GetOpenApiResponseBody(method);

                operations[verb] = operation;
                item.Operations  = operations;

                paths[path] = item;
            }

            this._document.Paths = paths;
            this._document.Components.Schemas         = this._helper.GetOpenApiSchemas(methods, namingStrategy);
            this._document.Components.SecuritySchemes = this._helper.GetOpenApiSecuritySchemes();

            return(this);
        }
Пример #9
0
 public AutumnSettings()
 {
     PageSizeField   = CDefaultPageSizeFieldName;
     PageNumberField = CDefaultPageNumberFieldName;
     PageSize        = CDefaultPageSize;
     SortField       = CDefaultSortFieldName;
     QueryField      = CDefaultQueryFieldName;
     NamingStrategy  = new DefaultNamingStrategy();
 }
        public void Given_DefaultNamingStrategy_When_GetOpenApiTypeName_Invoked_Then_It_Should_Return_Result()
        {
            var type     = typeof(int);
            var strategy = new DefaultNamingStrategy();

            var result = TypeExtensions.GetOpenApiTypeName(type, strategy);

            result.Should().Be("Int32");
        }
        public void Given_DefaultNamingStrategy_When_Instantiated_Then_It_Should_Return_Result()
        {
            var namingStrategy = new DefaultNamingStrategy();
            var example        = new FakeExample();

            var result = example.Build(namingStrategy).Examples;

            result["first"].Value.Should().BeOfType <OpenApiString>();
            (result["first"].Value as OpenApiString).Value.Should().Contain("{\"Number\":");
        }
Пример #12
0
        public void Given_Int16Type_When_Instantiated_Then_It_Should_Return_Result(string exampleName, short exampleValue)
        {
            var namingStrategy = new DefaultNamingStrategy();
            var example        = new FakeInt16ParameterExample();

            var result = example.Build(namingStrategy).Examples;

            result[exampleName].Value.Should().BeOfType <OpenApiInteger>();
            (result[exampleName].Value as OpenApiInteger).Value.Should().Be(exampleValue);
        }
Пример #13
0
        public void Given_Uint64Type_When_Instantiated_Then_It_Should_Return_Result(string exampleName, ulong exampleValue)
        {
            var namingStrategy = new DefaultNamingStrategy();
            var example        = new FakeUint64ParameterExample();

            var result = example.Build(namingStrategy).Examples;

            result[exampleName].Value.Should().BeOfType <OpenApiDouble>();
            (result[exampleName].Value as OpenApiDouble).Value.Should().Be(exampleValue);
        }
Пример #14
0
        public void Given_DateTimeOffsetType_When_Instantiated_Then_It_Should_Return_Result(string exampleName, string exampleValue)
        {
            var namingStrategy = new DefaultNamingStrategy();
            var example        = new FakeDateTimeOffsetParameterExample();

            var result = example.Build(namingStrategy).Examples;

            result[exampleName].Value.Should().BeOfType <OpenApiDateTime>();
            (result[exampleName].Value as OpenApiDateTime).Value.Should().Be(DateTimeOffset.Parse(exampleValue));
        }
Пример #15
0
        public void CreatesNameWithourRidAndEnv()
        {
            var expectValue = "myresource";

            var             context        = new ResourceContext();
            INamingStrategy namingStrategy = new DefaultNamingStrategy(context);
            var             name           = namingStrategy.GenerateName(expectValue);

            name.OutputShould().Be(expectValue);
        }
        public void GetOpenApiSchemas_Result_Should_Contain_Schema_For_Function_Classes()
        {
            var namingStrategy    = new DefaultNamingStrategy();
            var filter            = new RouteConstraintFilter();
            var acceptor          = new OpenApiSchemaAcceptor();
            var documentHelper    = new DocumentHelper(filter, acceptor);
            var visitorCollection = VisitorCollection.CreateInstance();

            var methods = typeof(FakeFunctions).GetMethods().ToList();

            var schemas = documentHelper.GetOpenApiSchemas(methods, namingStrategy, visitorCollection);

            schemas.Should().NotBeNull();
            schemas.Count.Should().Be(6);

            schemas.Should().ContainKey("FakeClassModel");

            schemas["FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeClassModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeOtherClassModel");

            schemas["FakeOtherClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeOtherClassModel"].Type.Should().Be("object");

            schemas["FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeClassModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeListModel");

            schemas["FakeListModel"].Properties.Count.Should().Be(1);
            schemas["FakeListModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeStringModel");
            schemas["FakeStringModel"].Properties.Count.Should().Be(2);
            schemas["FakeStringModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeGenericModel_FakeClassModel");

            schemas["FakeGenericModel_FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeGenericModel_FakeClassModel"].Type.Should().Be("object");
            schemas["FakeGenericModel_FakeClassModel"].Properties.Should().ContainKey("Name");
            schemas["FakeGenericModel_FakeClassModel"].Properties.Should().ContainKey("Value");
            schemas["FakeGenericModel_FakeClassModel"].Properties["Value"].Properties.Should().ContainKey("Number");
            schemas["FakeGenericModel_FakeClassModel"].Properties["Value"].Properties.Should().ContainKey("Text");

            schemas.Should().ContainKey("FakeGenericModel_FakeOtherClassModel");

            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeGenericModel_FakeOtherClassModel"].Type.Should().Be("object");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Should().ContainKey("Name");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Should().ContainKey("Value");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties["Value"].Properties.Should().ContainKey("FirstName");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties["Value"].Properties.Should().ContainKey("LastName");
        }
Пример #17
0
        public void CreatesNameWithEnv()
        {
            var             baseName       = "myresource";
            var             env            = "dev";
            var             expectValue    = $"{baseName}-{env}";
            var             context        = new ResourceContext(null, env);
            INamingStrategy namingStrategy = new DefaultNamingStrategy(context);
            var             name           = namingStrategy.GenerateName(baseName);

            name.OutputShould().Be(expectValue);
        }
        public void Given_Property_When_DefaultJsonProperyAnnotation_Invoked_Then_It_Should_Return_ElementName()
        {
            var name           = "FakePropertyNoAnnotation";
            var property       = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().NotBeNullOrEmpty();
            result.Should().Be(name);
        }
        public void Given_Property_When_GetJsonPropertyName_Invoked_Then_It_Should_Return_JsonPropertyName()
        {
            var name             = "FakeProperty2";
            var jsonPropertyName = "anotherFakeProperty";
            var property         = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy   = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().Be(jsonPropertyName);
        }
        /// <summary>
        /// Gets the display name of the enum value.
        /// </summary>
        /// <param name="enum">Enum value.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Display name of the enum value.</returns>
        public static string ToDisplayName(this Enum @enum, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            var type   = @enum.GetType();
            var member = type.GetMember(@enum.ToString()).First();

            return(member.ToDisplayName(namingStrategy));
        }
Пример #21
0
        public void Given_That_When_AddNamingStrategy_Invoked_Then_It_Should_Return_Result()
        {
            var field    = typeof(Document).GetField("_strategy", BindingFlags.Instance | BindingFlags.NonPublic);
            var strategy = new DefaultNamingStrategy();
            var helper   = new Mock <IDocumentHelper>();
            var doc      = new Document(helper.Object);

            var result = doc.AddNamingStrategy(strategy);

            field.GetValue(result).Should().NotBeNull();
            field.GetValue(result).Should().BeOfType <DefaultNamingStrategy>();
        }
Пример #22
0
        /// <summary>
        /// Gets the type name applied by <see cref="NamingStrategy"/>.
        /// </summary>
        /// <param name="type">Type to check.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the type name applied by <see cref="NamingStrategy"/>.</returns>
        public static string GetOpenApiTypeName(this Type type, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            var typeName = type.IsGenericType ? type.GetOpenApiGenericRootName() : type.Name;
            var name     = namingStrategy.GetPropertyName(typeName, hasSpecifiedName: false);

            return(name);
        }
Пример #23
0
        public void CreatesNameWithRid()
        {
            var baseName    = "myresource";
            var rid         = "42dh33gh";
            var expectValue = $"{baseName}-{rid}";

            var context = new ResourceContext(rid);

            INamingStrategy namingStrategy = new DefaultNamingStrategy(context);
            var             name           = namingStrategy.GenerateName(baseName);

            name.OutputShould().Be(expectValue);
        }
        public TelemetryContractResolver(string shardId) : base()
        {
            //For some reason the xbox shards use a different naming strategy to the PC shards
            var isXbox = shardId.ToLowerInvariant().Contains("xbox");

            if (isXbox)
            {
                NamingStrategy = new DefaultNamingStrategy();
            }
            else
            {
                NamingStrategy = new CamelCaseNamingStrategy();
            }
        }
        /// <summary>
        /// Gets the display name of the enum value.
        /// </summary>
        /// <param name="enum">Enum value.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Display name of the enum value.</returns>
        public static string ToDisplayName(this Enum @enum, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            var type      = @enum.GetType();
            var member    = type.GetMember(@enum.ToString()).First();
            var attribute = member.GetCustomAttribute <DisplayAttribute>(inherit: false);
            var name      = attribute == null? @enum.ToString() : attribute.Name;

            return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
        }
        /// <summary>
        /// Converts <see cref="OpenApiPayloadAttribute"/> to <see cref="OpenApiMediaType"/>.
        /// </summary>
        /// <typeparam name="T">Type of payload attribute inheriting <see cref="OpenApiPayloadAttribute"/>.</typeparam>
        /// <param name="attribute">OpenApi payload attribute.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <returns><see cref="OpenApiMediaType"/> instance.</returns>
        public static OpenApiMediaType ToOpenApiMediaType <T>(this T attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null) where T : OpenApiPayloadAttribute
        {
            attribute.ThrowIfNullOrDefault();

            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (collection.IsNullOrDefault())
            {
                collection = VisitorCollection.CreateInstance();
            }

            var type = attribute.BodyType;

            // Generate schema based on the type.
            var schema = collection.PayloadVisit(type, namingStrategy);

            // Add deprecated attribute.
            if (attribute is OpenApiRequestBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiRequestBodyAttribute).Deprecated;
            }
            if (attribute is OpenApiResponseWithBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiResponseWithBodyAttribute).Deprecated;
            }

            // For array and dictionary object, the reference has already been added by the visitor.
            if (type.IsReferentialType() && !type.IsOpenApiNullable() && !type.IsOpenApiArray() && !type.IsOpenApiDictionary())
            {
                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = attribute.BodyType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
                };

                schema.Reference = reference;
            }

            var mediaType = new OpenApiMediaType()
            {
                Schema = schema
            };

            return(mediaType);
        }
Пример #27
0
        /// <summary>
        /// 重写修改属性
        /// </summary>
        /// <param name="member"></param>
        /// <param name="property"></param>
        protected override void ModifyProperty(MemberInfo member, JsonProperty property)
        {
            //NamingStrategy = new CamelCaseNamingStrategy();
            NamingStrategy = new DefaultNamingStrategy();

            //不是时间类型直接返回
            if (property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?))
            {
                return;
            }
            //设置时间格式
            property.Converter = new AbpDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
        }
        /// <summary>
        /// Gets the name from <see cref="JsonPropertyAttribute"/> instance.
        /// </summary>
        /// <param name="element"><see cref="PropertyInfo"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the name from <see cref="JsonPropertyAttribute"/> instance.</returns>
        public static string GetJsonPropertyName(this PropertyInfo element, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (element.HasJsonPropertyAttribute())
            {
                var name = element.GetCustomAttribute <JsonPropertyAttribute>().PropertyName ?? namingStrategy.GetPropertyName(element.Name, hasSpecifiedName: false);

                return(name);
            }

            return(namingStrategy.GetPropertyName(element.Name, hasSpecifiedName: false));
        }
        /// <summary>
        /// Gets the Open API reference ID.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="isDictionary">Value indicating whether the type is <see cref="Dictionary{TKey, TValue}"/> or not.</param>
        /// <param name="isList">Value indicating whether the type is <see cref="List{T}"/> or not.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the Open API reference ID.</returns>
        public static string GetOpenApiReferenceId(this Type type, bool isDictionary, bool isList, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (isDictionary || isList)
            {
                var name = type.GetOpenApiSubTypeName(namingStrategy);

                return(namingStrategy.GetPropertyName(name, hasSpecifiedName: false));
            }

            return(namingStrategy.GetPropertyName(type.Name, hasSpecifiedName: false));
        }
        /// <summary>
        /// Converts the given <see cref="Type"/> instance to the list of underlying enum name.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <returns>Returns the list of underlying enum name.</returns>
        public static List <IOpenApiAny> ToOpenApiStringCollection(this Type type, NamingStrategy namingStrategy = null)
        {
            if (!type.IsUnflaggedEnumType())
            {
                return(null);
            }

            // namingStrategy null check
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }
            // namingStrategy null check

            var members = type.GetMembers(BindingFlags.Public | BindingFlags.Static);
            var names   = members.Select(p => p.ToDisplayName(namingStrategy));

            return(names.Select(p => (IOpenApiAny) new OpenApiString(p))
                   .ToList());
        }