/// <summary>
        /// Verify that mutability values are valid in context of Read Only property.
        /// </summary>
        /// <param name="mutable">mutability extension object.</param>
        /// <param name="context">Rule context.</param>
        /// <param name="formatParameters">array of invalid parameters to be returned.</param>
        /// <returns><c>true</c> if all values for x-ms-mutability are valid in context of Read Only property, otherwise <c>false</c>.</returns>
        private bool ValidateMutabilityValuesWithReadOnlyProperty(object mutable, RuleContext context, out object[] formatParameters)
        {
            string[] values        = ((Newtonsoft.Json.Linq.JArray)mutable).ToObject <string[]>();
            string[] invalidValues = null;

            var    resolver = new SchemaResolver(context?.GetServiceDefinition());
            Schema schema   = resolver.Unwrap(context?.GetFirstAncestor <Schema>());

            if (schema.ReadOnly)
            {
                // Property with "readOnly": true must only have "read" value in x-ms-mutability extension.
                invalidValues = values.Except(ValidValuesForReadOnlyProperty, StringComparer.OrdinalIgnoreCase).ToArray();
            }
            else
            {
                // Property with "readOnly": false must have more than "read" value in x-ms-mutability extension.
                if (values.Length == 1)
                {
                    invalidValues = values.Contains(ValidValuesForReadOnlyProperty[0], StringComparer.OrdinalIgnoreCase) ?
                                    ValidValuesForReadOnlyProperty : new string[0];
                }
            }

            bool isValid = invalidValues == null || invalidValues.Length == 0;

            formatParameters = isValid ? new object[0] : new string[] { String.Join(",", invalidValues) };

            return(isValid);
        }
Пример #2
0
        public SwaggerService Generate(Type type, InterfaceMapping map, string excludedMethodName = "Swagger", string controllernameused = null)
        {
            _service     = new SwaggerService();
            _serviceType = type;

            _exceptionType          = new JsonSchema4();
            _exceptionType.TypeName = "SwaggerException";
            _exceptionType.Properties.Add("ExceptionType", new JsonProperty {
                Type = JsonObjectType.String
            });
            _exceptionType.Properties.Add("Message", new JsonProperty {
                Type = JsonObjectType.String
            });
            _exceptionType.Properties.Add("StackTrace", new JsonProperty {
                Type = JsonObjectType.String
            });

            _service.Definitions[_exceptionType.TypeName] = _exceptionType;

            var schemaResolver = new SchemaResolver();
            var methods        = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var method in methods.Where(m => m.Name != excludedMethodName))
            {
                if (Array.IndexOf(map.TargetMethods, method) == -1)
                {
                    continue;
                }

                var parameters = method.GetParameters().ToList();
                var methodName = method.Name;

                var operation = new SwaggerOperation();
                operation.OperationId = methodName;

                var httpPath = GetHttpPath(operation, method, parameters, schemaResolver, controllernameused);

                LoadParameters(operation, parameters, schemaResolver);
                LoadReturnType(operation, method, schemaResolver);
                LoadMetaData(operation, method);

                var httpMethod = GetMethod(method);

                if (!_service.Paths.ContainsKey(httpPath))
                {
                    var path = new SwaggerOperations();
                    _service.Paths[httpPath] = path;
                }

                _service.Paths[httpPath][httpMethod] = operation;
            }

            foreach (var schema in schemaResolver.Schemes)
            {
                _service.Definitions[schema.TypeName] = schema;
            }

            _service.GenerateOperationIds();
            return(_service);
        }
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <returns>The <see cref="SwaggerDocument" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerDocument GenerateForControllers(IEnumerable <Type> controllerTypes)
        {
            var document = CreateDocument(Settings);

            var schemaResolver           = new SchemaResolver();
            var schemaDefinitionAppender = new SwaggerDocumentSchemaDefinitionAppender(document,
                                                                                       Settings.TypeNameGenerator);

            foreach (var controllerType in controllerTypes)
            {
                GenerateForController(document, controllerType,
                                      new SwaggerGenerator(_schemaGenerator, Settings, schemaResolver, schemaDefinitionAppender));
            }


            AppendRequiredSchemasToDefinitions(document, schemaResolver);
            document.GenerateOperationIds();

            foreach (var processor in Settings.DocumentProcessors)
            {
                processor.Process(new DocumentProcessorContext(document, controllerTypes));
            }

            return(document);
        }
        public void TypeLookupAdvancedTest(Type expectedType, AvroSchema schema)
        {
            var assembly   = Assembly.GetExecutingAssembly();
            var actualType = SchemaResolver.GetTypeFromSchema(schema, assembly);

            Assert.AreEqual(expectedType, actualType);
        }
        public void TypeLookupExceptionTest()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var schema   = new TypeLookupSchema();

            Assert.Throws <ArgumentException>(() => SchemaResolver.GetTypeFromSchema(schema, assembly));
        }
Пример #6
0
        /// <summary>
        /// Builds the schema. Main list of activities to perform.
        /// </summary>
        private void BuildSchemaImpl(IEnumerable <Entity> entities, IEnumerable <SchemaFile> schemas)
        {
            _namespaceToSchema = schemas.ToDictionary(schema => schema.Namespace);
            _entities          = entities;
            _aliasResolver     = new EntityStreamAliasResolver(entities);
            _schemaManager     = new SchemaResolver(entities, _aliasResolver);
            _schemaManager.Initialize();
            _namesUsed     = new HashSet <XmlQualifiedName>();
            _namesDeclared = new HashSet <XmlQualifiedName>();

            AddRootElement();
            AddRootChildren();

            FindFieldTypes();
            AddFields();
            AddTypes();
            AddRelationships();

            var errors = _namesUsed.Except(_namesDeclared).ToList( );

            if (errors.Count > 0)
            {
                throw new Exception("Names were used but not declared: " + string.Join(", ", errors.Select(qn => string.Format("{0}:{1}", qn.Namespace, qn.Name))));
            }
        }
            internal string FromAssemblyType(string[] classNames, string settingsData)
            {
                var settings = JsonConvert.DeserializeObject <AssemblyTypeToSwaggerGeneratorSettings>(settingsData);

                RegisterReferencePaths(GetAllReferencePaths(settings));

                var document = new SwaggerDocument();

                var generator                = new JsonSchemaGenerator(settings);
                var schemaResolver           = new SchemaResolver();
                var schemaDefinitionAppender = new SwaggerDocumentSchemaDefinitionAppender(document, settings.TypeNameGenerator);

#if FullNet
                var assembly = Assembly.LoadFrom(settings.AssemblyPath);
#else
                var assembly = Context.LoadFromAssemblyPath(settings.AssemblyPath);
#endif
                foreach (var className in classNames)
                {
                    var type   = assembly.GetType(className);
                    var schema = generator.Generate(type, schemaResolver, schemaDefinitionAppender);
                    document.Definitions[type.Name] = schema;
                }

                return(document.ToJson());
            }
Пример #8
0
        public void Should_build_json_schema_with_resolver()
        {
            var schemaResolver = new SchemaResolver((name, action) => action());

            var jsonSchema = schema.BuildDynamicJsonSchema(schemaResolver);

            CheckFields(jsonSchema);
        }
        public void TypeLookupTest(Type expectedType, Type schema)
        {
            var assembly       = Assembly.GetExecutingAssembly();
            var schemaInstance = Activator.CreateInstance(schema) as AvroSchema;
            var actualType     = SchemaResolver.GetTypeFromSchema(schemaInstance, assembly);

            Assert.AreEqual(expectedType, actualType);
        }
Пример #10
0
        public DatumReader(AvroSchema readerSchema, AvroSchema writerSchema)
        {
            var methods = SchemaResolver.ResolveReader <T>(readerSchema, writerSchema);

            _reader      = methods.Item1;
            _skipper     = methods.Item2;
            ReaderSchema = readerSchema;
            WriterSchema = writerSchema;
        }
Пример #11
0
        /// <summary>Generates a Swagger specification for the given controller type.</summary>
        /// <param name="controllerType">The type of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForController(Type controllerType, string excludedMethodName = "Swagger")
        {
            var service        = new SwaggerService();
            var schemaResolver = new SchemaResolver();

            GenerateForController(service, controllerType, excludedMethodName, schemaResolver);

            service.GenerateOperationIds();
            return(service);
        }
Пример #12
0
        protected static Schema Get200ResponseSchema(RuleContext context)
        {
            OperationResponse response = context?.GetFirstAncestor <Operation>()?.Responses?.GetValueOrNull("200");

            if (response == null)
            {
                return(null);
            }
            var resolver = new SchemaResolver(context?.GetServiceDefinition());

            return(resolver.Unwrap(response.Schema));
        }
Пример #13
0
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForControllers(Type[] controllerTypes, string excludedMethodName = "Swagger")
        {
            var service        = new SwaggerService();
            var schemaResolver = new SchemaResolver();

            foreach (var controllerType in controllerTypes)
            {
                GenerateForController(service, controllerType, excludedMethodName, schemaResolver);
            }

            service.GenerateOperationIds();
            return(service);
        }
Пример #14
0
        public void Should_build_flat_json_schema()
        {
            var languagesConfig = LanguagesConfig.English.Set(Language.DE);

            var schemaResolver = new SchemaResolver((name, action) =>
            {
                return(action());
            });

            var jsonSchema = schema.BuildFlatJsonSchema(schemaResolver);

            CheckFields(jsonSchema);
        }
Пример #15
0
        public static CMapperSchemaTree CreateSchemaTree(TransformBase map)
        {
            var schemaLoader         = new BizTalkMapSchemaArtifactLoader(map);
            var schemaResolveHandler = new SchemaResolver();

            schemaResolveHandler.CustomResolution(schemaLoader);

            var schemaTree = new CMapperSchemaTree();

            schemaTree.SetSchemaResolveHandler(schemaResolveHandler);

            return(schemaTree);
        }
Пример #16
0
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForControllers(IEnumerable <Type> controllerTypes, string excludedMethodName = "Swagger")
        {
            var service = CreateService(Settings);

            var schemaResolver           = new SchemaResolver();
            var schemaDefinitionAppender = new SwaggerServiceSchemaDefinitionAppender(service, Settings.TypeNameGenerator);

            foreach (var controllerType in controllerTypes)
            {
                GenerateForController(service, controllerType, excludedMethodName, schemaResolver, schemaDefinitionAppender);
            }

            service.GenerateOperationIds();
            return(service);
        }
Пример #17
0
        /// <summary>
        /// Finds a property by name in the given
        /// </summary>
        /// <param name="schema">The schema to serve as a starting point</param>
        /// <param name="definition">The service definition that contains all definitions</param>
        /// <param name="propertyName">The name of the property to find</param>
        /// <returns>The schema for the found property or null</returns>
        public static Schema FindPropertyInChain(this Schema schema, ServiceDefinition definition, string propertyName)
        {
            Schema propertyDefinition = null;
            var    resolver           = new SchemaResolver(definition);

            // Try to find the property in this schema or its ancestors
            try
            {
                propertyDefinition = resolver.FindProperty(schema, propertyName);
            }
            catch (InvalidOperationException)
            {
                // There was a problem finding the property (e.g. a circular reference). Return null
            }
            return(propertyDefinition);
        }
Пример #18
0
        /// <summary>
        ///     Load field data.
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <remarks>
        ///     Data sources MUST:
        ///     - ensure that bits are represented as Booleans
        ///     - ensure that XML is transformed so that entityRefs contain Upgrade ids
        ///     - or where XML contains an alias, translate it to uprgadeId|alias   (as the alias may be changed in the target)
        ///     - ensure that aliases export their namespace and direction marker.
        /// </remarks>
        public IEnumerable <DataEntry> GetFieldData(string dataTable, IProcessingContext context)
        {
            if (!FieldData.ContainsKey(dataTable))
            {
                return(Enumerable.Empty <DataEntry>( ));
            }

            Dictionary <Entity, List <FieldData> > typedValues = FieldData[dataTable];

            if (dataTable == "Alias")
            {
                Alias aliasMarkerIdField = Aliases.CoreAlias("aliasMarkerId");

                return(from pair in typedValues
                       from field in pair.Value
                       let alias = SchemaResolver.GetAliasFieldValue(pair.Key, field.Field.Alias)
                                   let intFieldValue = SchemaResolver.GetIntFieldValue(field.Field, aliasMarkerIdField)
                                                       where intFieldValue != null
                                                       where pair.Key.Members != null && pair.Key.Members.Any(m => m.MemberDefinition.Alias.Namespace == "core" && m.MemberDefinition.Alias.Value == "inSolution" && m.Value == ActiveSolution)
                                                       let markerId = intFieldValue.Value
                                                                      select new DataEntry
                {
                    AliasMarkerId = markerId,
                    Data = alias.Value,
                    EntityId = pair.Key.Guid,
                    FieldId = field.Field.Guid,
                    Namespace = alias.Namespace,
                    State = DataState.Added
                });
            }

            /////
            // Non-Alias
            /////
            return(from pair in typedValues
                   from field in pair.Value
                   where pair.Key.Members != null && pair.Key.Members.Any(m => m.MemberDefinition.Alias.Namespace == "core" && m.MemberDefinition.Alias.Value == "inSolution" && m.Value == ActiveSolution)
                   select new DataEntry
            {
                Data = FormatData(field),
                EntityId = pair.Key.Guid,
                FieldId = field.Field.Guid,
                State = DataState.Added
            });
        }
Пример #19
0
        /// <summary>Generates a Swagger specification for the given controller type.</summary>
        /// <param name="controllerType">The type of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForController(Type controllerType, string excludedMethodName = "Swagger")
        {
            var service = new SwaggerService
            {
                Consumes = new List <string> {
                    "application/json"
                },
                Produces = new List <string> {
                    "application/json"
                }
            };
            var schemaResolver = new SchemaResolver();

            GenerateForController(service, controllerType, excludedMethodName, schemaResolver);

            service.GenerateOperationIds();
            return(service);
        }
Пример #20
0
            internal string FromAssemblyType(string[] classNames, string settingsData)
            {
                var settings = JsonConvert.DeserializeObject <AssemblyTypeToSwaggerGeneratorSettings>(settingsData);

                var generator = new JsonSchemaGenerator(settings);
                var resolver  = new SchemaResolver();
                var service   = new SwaggerService();

                var assembly = Assembly.LoadFrom(settings.AssemblyPath);

                foreach (var className in classNames)
                {
                    var type   = assembly.GetType(className);
                    var schema = generator.Generate <JsonSchema4>(type, resolver);
                    service.Definitions[type.Name] = schema;
                }

                return(service.ToJson());
            }
Пример #21
0
        private void AppendRequiredSchemasToDefinitions(SwaggerService service, SchemaResolver schemaResolver)
        {
            foreach (var schema in schemaResolver.Schemes)
            {
                if (!service.Definitions.Values.Contains(schema))
                {
                    var typeName = schema.GetTypeName(Settings.TypeNameGenerator);

                    if (!service.Definitions.ContainsKey(typeName))
                    {
                        service.Definitions[typeName] = schema;
                    }
                    else
                    {
                        service.Definitions["ref_" + Guid.NewGuid().ToString().Replace("-", "_")] = schema;
                    }
                }
            }
        }
Пример #22
0
        public SchemaSwaggerGenerator(
            SwaggerDocument document,
            string appName,
            string appPath,
            Schema schema,
            SchemaResolver schemaResolver,
            PartitionResolver partitionResolver)
        {
            this.document = document;

            this.appName = appName;
            this.appPath = appPath;

            schemaPath = schema.Name;
            schemaName = schema.DisplayName();
            schemaType = schema.TypeName();

            dataSchema = schemaResolver($"{schemaType}Dto", schema.BuildJsonSchema(partitionResolver, schemaResolver));

            contentSchema = schemaResolver($"{schemaType}ContentDto", schemaBuilder.CreateContentSchema(schema, dataSchema));
        }
Пример #23
0
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForControllers(IEnumerable <Type> controllerTypes, string excludedMethodName = "Swagger")
        {
            var service = new SwaggerService
            {
                Consumes = new List <string> {
                    "application/json"
                },
                Produces = new List <string> {
                    "application/json"
                }
            };
            var schemaResolver = new SchemaResolver();

            foreach (var controllerType in controllerTypes)
            {
                GenerateForController(service, controllerType, excludedMethodName, schemaResolver);
            }

            service.GenerateOperationIds();
            return(service);
        }
Пример #24
0
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForControllers(IEnumerable <Type> controllerTypes)
        {
            var service = CreateDocument(Settings);

            var schemaResolver           = new SchemaResolver();
            var schemaDefinitionAppender = new SwaggerServiceSchemaDefinitionAppender(service, Settings.TypeNameGenerator);

            foreach (var controllerType in controllerTypes)
            {
                GenerateForController(service, controllerType, schemaResolver, new SwaggerGenerator(_schemaGenerator, Settings, schemaResolver, schemaDefinitionAppender));
            }

            service.GenerateOperationIds();

            foreach (var processor in Settings.DocumentProcessors)
            {
                processor.Process(service);
            }

            return(service);
        }
Пример #25
0
        public static JsonSchema BuildFlatJsonSchema(this Schema schema, SchemaResolver schemaResolver)
        {
            Guard.NotNull(schemaResolver, nameof(schemaResolver));

            var schemaName = schema.TypeName();

            var jsonSchema = SchemaBuilder.Object();

            foreach (var field in schema.Fields.ForApi())
            {
                var property = JsonTypeVisitor.BuildProperty(field, null, false);

                if (property != null)
                {
                    var propertyReference = schemaResolver($"{schemaName}{field.Name.ToPascalCase()}FlatPropertyDto", () => property);

                    jsonSchema.Properties.Add(field.Name, CreateProperty(field, propertyReference));
                }
            }

            return(jsonSchema);
        }
Пример #26
0
        /// <summary>
        ///     Load entities.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IEnumerable <EntityEntry> GetEntities(IProcessingContext context)
        {
            if (string.IsNullOrEmpty(ActiveSolution))
            {
                throw new InvalidOperationException("No 'ActiveSolution' has been specified.");
            }

            /////
            // Get all entities.
            /////
            IEnumerable <Entity> allEntities = Entities.Concat(SchemaResolver.GetImpliedRelationshipEntites( ));

            /////
            // Get the entities that belong to the active solution.
            /////
            IEnumerable <Entity> activeSolutionEntities = allEntities.Where(e => e.Members.Any(m => m.MemberDefinition.Alias.Namespace == "core" && m.MemberDefinition.Alias.Value == "inSolution" && m.Value == ActiveSolution));

            return(activeSolutionEntities.Select(e => new EntityEntry
            {
                EntityId = e.Guid,
                State = DataState.Added
            }));
        }
Пример #27
0
        /// <summary>
        ///     Gets the fields with defaults.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        private IEnumerable <FieldData> GetFieldsWithDefaults(Entity type)
        {
            List <FieldData> result;

            if (!_defaultsOnType.TryGetValue(type, out result))
            {
                Alias defaultValueAlias = Aliases.CoreAlias("defaultValue");

                result =
                    (from ancType in SchemaResolver.GetAncestors(type)
                     from field in SchemaResolver.GetDeclaredFields(ancType)
                     let defaultValue = SchemaResolver.GetStringFieldValue(field, defaultValueAlias)
                                        where defaultValue != null
                                        select new FieldData
                {
                    Field = field,
                    Value = defaultValue
                }).ToList( );

                _defaultsOnType[type] = result;
            }
            return(result);
        }
Пример #28
0
        public static JsonSchema BuildDynamicJsonSchema(this Schema schema, SchemaResolver schemaResolver, bool withHidden = false)
        {
            Guard.NotNull(schemaResolver, nameof(schemaResolver));

            var jsonSchema = SchemaBuilder.Object();

            foreach (var field in schema.Fields.ForApi(withHidden))
            {
                var propertyItem = JsonTypeVisitor.BuildProperty(field, null, withHidden);

                if (propertyItem != null)
                {
                    var property =
                        SchemaBuilder.ObjectProperty(propertyItem)
                        .SetDescription(field)
                        .SetRequired(field.RawProperties.IsRequired);

                    jsonSchema.Properties.Add(field.Name, property);
                }
            }

            return(jsonSchema);
        }
Пример #29
0
        public void Should_build_flat_json_schema()
        {
            var languagesConfig = LanguagesConfig.English.Set(Language.DE);

            var schemaResolver = new SchemaResolver((name, action) =>
            {
                return(action());
            });

            var jsonSchema     = schema.BuildFlatJsonSchema(schemaResolver);
            var jsonProperties = AllPropertyNames(jsonSchema);

            void CheckField(IField field)
            {
                if (!field.IsForApi())
                {
                    Assert.DoesNotContain(field.Name, jsonProperties);
                }
                else
                {
                    Assert.Contains(field.Name, jsonProperties);
                }

                if (field is IArrayField array)
                {
                    foreach (var nested in array.Fields)
                    {
                        CheckField(nested);
                    }
                }
            }

            foreach (var field in schema.Fields)
            {
                CheckField(field);
            }
        }
Пример #30
0
 public DotNetSchemaURIResolver(SchemaResolver resolver)
 {
     this.resolver = resolver;
 }
Пример #31
0
 public DotNetSchemaURIResolver(SchemaResolver resolver)
 {
     this.resolver = resolver;
 }