public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            Contract.Assume(swaggerDoc != null);
            Contract.Assume(schemaRegistry != null);
            Contract.Assume(apiExplorer != null);

            var pathItems = swaggerDoc.paths.Values;

            var deletes = pathItems.Select(pathItem => pathItem.delete).Where(operation => operation != null);
            var gets = pathItems.Select(pathItem => pathItem.get).Where(operation => operation != null);
            var heads = pathItems.Select(pathItem => pathItem.head).Where(operation => operation != null);
            var patches = pathItems.Select(pathItem => pathItem.patch).Where(operation => operation != null);
            var puts = pathItems.Select(pathItem => pathItem.put).Where(operation => operation != null);
            var posts = pathItems.Select(pathItem => pathItem.post).Where(operation => operation != null);
            var options = pathItems.Select(pathItem => pathItem.options).Where(operation => operation != null);

            var allOperations = deletes.ConcatEvenIfNull(gets)
                                       .ConcatEvenIfNull(heads)
                                       .ConcatEvenIfNull(patches)
                                       .ConcatEvenIfNull(puts)
                                       .ConcatEvenIfNull(posts)
                                       .ConcatEvenIfNull(options)
                                       .ToList();

            AppendParameterNamesToOperationId(allOperations);

            UniquifyOperationId(allOperations);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="schemaRegistry"></param>
        /// <param name="apiExplorer"></param>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            IList<string> apilist = new List<string>();

            if (swaggerDoc != null && swaggerDoc.paths != null)
            {
                foreach (System.Collections.Generic.KeyValuePair<string, PathItem> pathitem in swaggerDoc.paths)
                {
                    if (pathitem.Key.Contains("OAuth"))
                    {
                        apilist.Add(pathitem.Key);
                    }
                }
            }

            foreach (string pathitem in apilist)
            {
                swaggerDoc.paths.Remove(pathitem);
            }

            if (swaggerDoc != null && swaggerDoc.definitions != null)
            {
                swaggerDoc.definitions.Remove("TokenResult");
                swaggerDoc.definitions.Remove("Object");
            }
        }
        public static void Configure(IApiExplorer apiExplorer, string xmlDocumentationPath, Action<ApiAuthorFactory> configure)
        {
            // Sanity checks
            if (apiExplorer == null) throw new ArgumentNullException("apiExplorer");
            if (xmlDocumentationPath == null) throw new ArgumentNullException("xmlDocumentationPath");
            if (Instance.IsValueCreated) throw new InvalidOperationException("Api Author is already configured. Make sure to not call the configure method twice");

            Instance.Value._apiExplorer = apiExplorer;

            // Try to load xml documentation file
            try
            {
                Instance.Value._xmlDocumentation = XDocument.Load(xmlDocumentationPath);
            }
            catch (Exception exception)
            {
                throw new FileLoadException("Unable to load XML documentation. Make sure to enable XML documentation in the build properties of your API project and specifiy the correct path to the XML file when configuring ApiDiscloser.", xmlDocumentationPath, exception);
            }

            // Execute configuration action specified by consumer of factory if specified.
            if (configure != null)
            {
                configure(Instance.Value);
            }
        }
Exemplo n.º 4
0
 public ApiModel(IApiExplorer explorer)
 {
     if (explorer==null)
     {
         throw new ArgumentException("explorer");
     }
     _explorer = explorer;
 }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            swaggerDoc.basePath = "/" + swaggerDoc.info.version;

            swaggerDoc.paths = swaggerDoc.paths.ToDictionary(
                entry => entry.Key.Replace("/{apiVersion}", ""),
                entry => RemoveVersionParamsFrom(entry.Value));
        }
        public static ApiDiscloserSpecification GetApiSpecification(IApiExplorer apiExplorer)
        {
            if (!Instance.IsValueCreated)
            {
                throw new InvalidOperationException("Api discloser has not been configured. Make sure to configure Api Discloser once during application start.");
            }

            return Instance.Value._apiSpecification ?? (Instance.Value._apiSpecification = new ApiDiscloserSpecification(apiExplorer, Instance.Value.XmlDocumentation));
        }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            //添加Tag
            swaggerDoc.tags = new List<Tag>();
            var controllers = apiExplorer.ApiDescriptions.Select(p => p.ActionDescriptor.ControllerDescriptor).Distinct();
            foreach (var item in controllers)
            {
                var desc = item.GetCustomAttributes<DisplayNameAttribute>();
                if (desc != null && desc.Count > 0)
                {
                    //hack
                    swaggerDoc.tags.Add(new Tag() { name = hackcontrollername(item.ControllerName), description = desc[0].DisplayName });
                }
                else
                {
                    var desc2 = item.GetCustomAttributes<DescriptionAttribute>();
                    if (desc2 != null && desc2.Count > 0)
                    {
                        swaggerDoc.tags.Add(new Tag() { name = hackcontrollername(item.ControllerName), description = desc2[0].Description });
                    }
                }

                
            }


            //优化枚举显示
            foreach (var schemaDictionaryItem in swaggerDoc.definitions)
            {
                var schema = schemaDictionaryItem.Value;
                foreach (var propertyDictionaryItem in schema.properties)
                {
                    var property = propertyDictionaryItem.Value;
                    var propertyEnums = property.@enum;
                    if (propertyEnums != null && propertyEnums.Count > 0)
                    {
                        var enumDescriptions = new List<string>();
                        for (int i = 0; i < propertyEnums.Count; i++)
                        {
                            var enumOption = propertyEnums[i];
                            var desc =(DisplayAttribute) enumOption.GetType().GetField(enumOption.ToString()).GetCustomAttributes(true).Where(p => p is DisplayAttribute).FirstOrDefault();
                            if (desc==null)
                            {
                                enumDescriptions.Add(string.Format("{0} = {1} ", Convert.ToInt32(enumOption), Enum.GetName(enumOption.GetType(), enumOption)));
                            }
                            else
                            {
                                enumDescriptions.Add(string.Format("{0} = {1} ", Convert.ToInt32(enumOption), desc.Name));
                            }
                            
                        }
                        property.description += string.Format(" ({0})", string.Join(", ", enumDescriptions.ToArray()));
                    }
                }
            }
        }
        public ApiDiscloserSpecification(IApiExplorer apiExplorer, XDocument xmlDocumentation)
        {
            // Group by controller name. Each controller will be a different API
            var apiDescriptionGroups = apiExplorer.ApiDescriptions.GroupBy(x=>x.ActionDescriptor.ControllerDescriptor.ControllerName);

            foreach (var apiDescriptionGroup in apiDescriptionGroups)
            {
                Apis.Add(new Api(apiDescriptionGroup, xmlDocumentation));
            }
        }
Exemplo n.º 9
0
        public MappingRule(MethodCallExpression methodExpression, IApiExplorer apiExplorer)
        {
            _methodExpression = methodExpression;
            _parametersDelegates = ParametersDelegateBuilder.Build(methodExpression);

            if (apiExplorer != null)
                MapApiDesctiption(apiExplorer);

            AddRelsFromAttribute(methodExpression);
        }
Exemplo n.º 10
0
 public SwaggerGenerator(
     IApiExplorer apiExplorer,
     IContractResolver jsonContractResolver,
     IDictionary<string, Info> apiVersions,
     SwaggerGeneratorOptions options = null)
 {
     _apiExplorer = apiExplorer;
     _jsonContractResolver = jsonContractResolver;
     _apiVersions = apiVersions;
     _options = options ?? new SwaggerGeneratorOptions();
 }
Exemplo n.º 11
0
 public SwaggerGenerator(
     IApiExplorer apiExplorer,
     JsonSerializerSettings jsonSerializerSettings,
     IDictionary<string, Info> apiVersions,
     SwaggerGeneratorOptions options = null)
 {
     _apiExplorer = apiExplorer;
     _jsonSerializerSettings = jsonSerializerSettings;
     _apiVersions = apiVersions;
     _options = options ?? new SwaggerGeneratorOptions();
 }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.tags = new List<Tag>
     {
         new Tag { name = "Clients", description = "an ApiController resource" },
         new Tag { name = "Customers", description = "an ODataController resource" },
         new Tag { name = "Orders", description = "an ODataController resource" },
         new Tag { name = "CustomersV1", description = "a versioned ODataController resource" },
         new Tag { name = "Users", description = "a RESTier resource" },
         new Tag { name = "Products", description = "demonstrates OData functions and actions" }
     };
 }
Exemplo n.º 13
0
        public SwaggerSpec From(IApiExplorer apiExplorer)
        {
            var apiDescriptionGroups = apiExplorer.ApiDescriptions
                .GroupBy(apiDesc => "/" + _declarationKeySelector(apiDesc))
                .ToArray();

            return new SwaggerSpec
                {
                    Listing = CreateListing(apiDescriptionGroups),
                    Declarations = CreateDeclarations(apiDescriptionGroups)
                };
        }
Exemplo n.º 14
0
 /// <summary>
 /// Apply function
 /// </summary>
 /// <param name="swaggerDoc"></param>
 /// <param name="schemaRegistry"></param>
 /// <param name="apiExplorer"></param>
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     try
     {
         swaggerDoc.paths.Remove("/{url}");
         swaggerDoc.paths.Remove("/Error");
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Exemplo n.º 15
0
        public SwaggerSpec Generate(IApiExplorer apiExplorer)
        {
            var apiDescriptionGroups = apiExplorer.ApiDescriptions
                .Where(apiDesc => apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName != "ApiDocs") // Exclude the Swagger controller
                .GroupBy(apiDesc => "/" + _declarationKeySelector(apiDesc))
                .ToArray();

            return new SwaggerSpec
                {
                    Listing = GenerateListing(apiDescriptionGroups),
                    Declarations = GenerateDeclarations(apiDescriptionGroups)
                };
        }
        public static SwaggerSpec CreateFrom(IApiExplorer apiExplorer)
        {
            var swaggerGenerator = new SwaggerGenerator(
                SwaggerSpecConfig.Instance.DeclarationKeySelector,
                SwaggerSpecConfig.Instance.BasePathResolver,
                SwaggerSpecConfig.Instance.CustomTypeMappings,
                SwaggerSpecConfig.Instance.OperationFilters,
                SwaggerSpecConfig.Instance.OperationSpecFilters);

            // TODO: Implement as Singleton - there is only one spec and it should only be generated once

            return swaggerGenerator.From(apiExplorer);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataSwaggerProvider" /> class.
        /// Use this constructor to customize all <see cref="ODataSwaggerProvider" /> dependencies.
        /// </summary>
        /// <param name="defaultProvider">The default provider.</param>
        /// <param name="options">The options.</param>
        /// <param name="apiVersions">The version information.</param>
        /// <param name="odataApiExplorer">The API explorer.</param>
        /// <param name="httpConfig">The HttpConfiguration that contains the OData Edm Model.</param>
        internal ODataSwaggerProvider(ISwaggerProvider defaultProvider, SwaggerProviderOptions options, IDictionary<string, Info> apiVersions, IApiExplorer odataApiExplorer, HttpConfiguration httpConfig)
        {
            Contract.Requires(defaultProvider != null);
            Contract.Requires(odataApiExplorer != null);
            Contract.Requires(httpConfig != null);
            Contract.Requires(options != null);

            _defaultProvider = defaultProvider;
            _httpConfig = httpConfig;
            _options = new ODataSwaggerProviderOptions(options);
            _apiVersions = apiVersions;
            _odataApiExplorer = odataApiExplorer;
        }
Exemplo n.º 18
0
        public ApiExplorerAdapter(
            IApiExplorer apiExplorer,
            Func<string> basePathAccessor,
            IEnumerable<IOperationSpecFilter> postFilters)
        {
            // Group ApiDescriptions by controller name - each group corresponds to an ApiDeclaration
            _controllerGroups = apiExplorer.ApiDescriptions
                .GroupBy(ad => "/swagger/api-docs/" + ad.ActionDescriptor.ControllerDescriptor.ControllerName);

            _basePathAccessor = basePathAccessor;
            _postFilters = postFilters;
            _resourceListing = new Lazy<ResourceListing>(GenerateResourceListing);
            _apiDeclarations = new Lazy<Dictionary<string, ApiDeclaration>>(GenerateApiDeclarations);
        }
Exemplo n.º 19
0
        public SwaggerSpec ApiExplorerToSwaggerSpec(IApiExplorer apiExplorer)
        {
            var apiDescriptionGroups = apiExplorer.ApiDescriptions
                .Where(apiDesc => !_config.IgnoreObsoleteActions || !apiDesc.IsMarkedObsolete())
                .GroupBy(apiDesc => "/" + _config.DeclarationKeySelector(apiDesc))
                .OrderBy(group => group.Key)
                .ToArray();

            return new SwaggerSpec
                {
                    Listing = CreateListing(apiDescriptionGroups),
                    Declarations = CreateDeclarations(apiDescriptionGroups)
                };
        }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.tags = new List<Tag>
     {
         new Tag { name = "Clients", description = "an ApiController resource" },
         new Tag { name = "Customers", description = "an ODataController resource" },
         new Tag { name = "Orders", description = "an ODataController resource" },
         new Tag { name = "CustomersV1", description = "a versioned ODataController resource" },
         new Tag { name = "Users", description = "a RESTier resource" },
         new Tag { name = "Products", description = "demonstrates OData functions and actions" },
         new Tag { name = "ProductWithCompositeEnumIntKeys", description = "demonstrates composite keys with an enum as a key" },
         new Tag { name = "ProductWithEnumKeys", description = "demonstrates use of enum as a key" },
     };
 }
Exemplo n.º 21
0
        public HelpApi(IRootPathProvider pathProvider):base("/help")
        {
            var xmlDocPath = Path.Combine(pathProvider.GetRootPath(), ConfigurationManager.AppSettings["xmlDocumentationFile"]);
            _apiExplorer =  new DefaultApiExplorer(ModulePath, xmlDocPath);

            Get["/"] = q => View["RouteCatelog.cshtml", _apiExplorer.ModuleRouteCatelog];

            Get["/{api*}"] = context =>
            {
                var model = _apiExplorer.GetRouteDetail(Request.Path);
                return View["RouteDetail.cshtml", model];
            };

            Get["/resourceModel/{modelName}"] = context => View["ResourceModel.cshtml", _apiExplorer.GetResourceDetail(Request.Path)];
        }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (var apiDescription in apiExplorer.ApiDescriptions)
            {
                if (
                    !apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<SwHideInDocsAttribute>()
                        .Any() && !apiDescription.ActionDescriptor.GetCustomAttributes<SwHideInDocsAttribute>().Any())
                {
                    continue;
                }
                var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/');
                swaggerDoc.paths.Remove(route);

            }
        }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList();
     var controllers = Assembly.GetExecutingAssembly().GetTypes().Where(type => typeof(ApiController).IsAssignableFrom(type));
     var odataRoutes = GlobalConfiguration.Configuration.Routes.Where(a => a.GetType() == typeof(ODataRoute)).ToList();
     var route = odataRoutes.FirstOrDefault() as ODataRoute;
     foreach (Type controller in controllers)
     {
         string name = controller.Name.Replace("Controller", "");
         if (swaggerDoc.paths.Keys.Contains("/Api/" + name))
         {
             swaggerDoc.paths["/Api/" + name].get = null;
         }
     }
 }
Exemplo n.º 24
0
 public ApiExplorerAdapter(
     IApiExplorer apiExplorer,
     bool ignoreObsoleteActions,
     Func<ApiDescription, string, bool> resoveVersionSupport,
     Func<ApiDescription, string> resolveResourceName,
     Dictionary<Type, Func<DataType>> customTypeMappings,
     IEnumerable<PolymorphicType> polymorphicTypes,
     IEnumerable<IModelFilter> modelFilters,
     IEnumerable<IOperationFilter> operationFilters)
 {
     _apiExplorer = apiExplorer;
     _ignoreObsoleteActions = ignoreObsoleteActions;
     _resoveVersionSupport = resoveVersionSupport;
     _resolveResourceName = resolveResourceName;
     _customTypeMappings = customTypeMappings;
     _polymorphicTypes = polymorphicTypes;
     _modelFilters = modelFilters;
     _operationFilters = operationFilters;
 }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (var definition in swaggerDoc.definitions)
            {
                if (IsEntityType(definition))
                {
                    var schema = definition.Value;
                    Contract.Assume(schema != null);

                    var properties = schema.properties.ToList();
                    foreach (var property in schema.properties)
                    {
                        RemoveCollectionTypeProperty(property, properties);
                        RemoveReferenceTypeProperty(property, properties);
                    }
                    schema.properties = properties.ToDictionary(property => property.Key, property => property.Value);
                }
            }
        }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            var setting = Its.Configuration.Settings.Get<SwaggerToolSettings>();
            foreach (var apiDescription in apiExplorer.ApiDescriptions)
            {
                //hide attr
                
                //remove from docs autogenerated services
                if (setting.HideAbpAutogeneratedApi)
                {
                    Regex r = new Regex(AbpPath);
                    if (r.IsMatch(apiDescription.ID))
                    {
                        swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]);
                        continue;
                    }
                    
                }
                if (setting.HideDocPaths!=null&&setting.HideDocPaths.Length>0)
                {
                    if (setting.HideDocPaths.Where(p=>apiDescription.ID.Contains(p)).Count()>0)
                    {
                        swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]);
                        continue;
                    }
                }
                if (!string.IsNullOrEmpty(setting.HideDocPathAttributeName))
                {
                    var attr = apiDescription.GetControllerAndActionAttributes<object>();
                    if (attr!=null&& attr.Where(p=>p.ToString()==setting.HideDocPathAttributeName).Count()>0)
                    {
                        swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]);
                        continue;
                    }
                }
               

            }
        }
Exemplo n.º 27
0
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            var defaultApiKey = _settingManager.GetValue("Swashbuckle.DefaultApiKey", string.Empty);

            swaggerDoc.info.description = string.Format(CultureInfo.InvariantCulture, "For this sample, you can use the `{0}` key to satisfy the authorization filters.", defaultApiKey);
            swaggerDoc.info.termsOfService = "";

            swaggerDoc.info.contact = new Contact
            {
                email = "*****@*****.**",
                name = "Virto Commerce",
                url = "http://virtocommerce.com"
            };

            swaggerDoc.info.license = new License
            {
                name = "Virto Commerce Open Software License 3.0",
                url = "http://virtocommerce.com/opensourcelicense"
            };

            var tags = _moduleCatalog.Modules
                .OfType<ManifestModuleInfo>()
                .Select(x => new Tag
                {
                    name = x.Title,
                    description = x.Description
                })
                .ToList();

            tags.Add(new Tag
            {
                name = "VirtoCommerce platform",
                description = "Platform functionality represent common resources and operations"
            });

            swaggerDoc.tags = tags;
        }
Exemplo n.º 28
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     if (swaggerDoc != null)
     {
         foreach (var path in swaggerDoc.paths)
         {
             if (path.Value.post != null && path.Value.post.parameters != null)
             {
                 var parameters = path.Value.post.parameters;
                 if (parameters.Count == 3 && parameters[0].name.StartsWith("emp"))
                 {
                     path.Value.post.parameters = EmployeeBodyParam;
                 }
             }
         }
     }
 }
	    public ApiExplorerService(IApiExplorer apiExplorer, string baseUri)
		{
			this.apiExplorer = apiExplorer;
			this.baseUri = baseUri;
		}
Exemplo n.º 30
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     // Include the given data type in the final SwaggerDocument
     //
     //schemaRegistry.GetOrRegister(typeof(ExtraType));
 }
Exemplo n.º 31
0
        /// <summary></summary>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList();

            var odatacontrollers = thisAssemblyTypes.Where(t => t.IsSubclassOf(typeof(ODataController))).ToList();
            var odataRoutes      = GlobalConfiguration.Configuration.Routes.Where(a => a.GetType() == typeof(ODataRoute)).ToList();

            if (!odataRoutes.Any() || !odatacontrollers.Any())
            {
                return;
            }
            var odatamethods = new[] { "Get", "Put", "Post", "Delete" };

            var route = odataRoutes.FirstOrDefault() as ODataRoute;

            foreach (var odataContoller in odatacontrollers)  // this is all of the OData controllers in your API
            {
                var methods = odataContoller.GetMethods().Where(a => odatamethods.Contains(a.Name)).ToList();
                if (!methods.Any())
                {
                    continue;                   // next controller -- this one doesn't have any applicable methods
                }
                foreach (var method in methods) // this is all of the methods for a SINGLE controller (e.g. GET, POST, PUT, etc)
                {
                    var path = "/" + route.RoutePrefix + "/" + odataContoller.Name.Replace("Controller", "");

                    if (swaggerDoc.paths.ContainsKey(path))
                    {
                        Debug.WriteLine("Path " + path + " already exists");
                        Console.WriteLine("Path " + path + " already exists");
                        continue;
                    }

                    var odataPathItem = new PathItem();
                    var op            = new Operation();

                    // This is assuming that all of the odata methods will be listed under a heading called OData in the swagger doc
                    op.tags = new List <string> {
                        "OData"
                    };
                    op.operationId = "OData_" + odataContoller.Name.Replace("Controller", "");

                    // This should probably be retrieved from XML code comments....
                    op.summary     = "Summary for your method / data";
                    op.description = "Here is where we go deep into the description and options for the call.";

                    op.consumes = new List <string>();
                    op.produces = new List <string> {
                        "application/atom+xml", "application/json", "text/json", "application/xml", "text/xml"
                    };
                    op.deprecated = false;

                    var response = new Response()
                    {
                        description = "OK"
                    };
                    response.schema = new Schema {
                        type = "array", items = schemaRegistry.GetOrRegister(method.ReturnType)
                    };
                    op.responses = new Dictionary <string, Response> {
                        { "200", response }
                    };

                    var security = GetSecurityForOperation(odataContoller);
                    if (security != null)
                    {
                        op.security = new List <IDictionary <string, IEnumerable <string> > > {
                            security
                        }
                    }
                    ;

                    odataPathItem.get = op;   // this needs to be a switch based on the method name
                    if (swaggerDoc.paths.ContainsKey(path))
                    {
                        Debug.WriteLine("Path " + path + " already exists");
                        Console.WriteLine("Path " + path + " already exists");
                    }
                    else
                    {
                        swaggerDoc.paths.Add(path, odataPathItem);
                    }
                }
            }
        }
Exemplo n.º 32
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     var usertTokenSecurity = new Dictionary<string, IEnumerable<string>>();
     usertTokenSecurity[SwaggerConfig.UserTokenSecurityDefinitionName] = new List<string>();
     swaggerDoc.security = new List<IDictionary<string, IEnumerable<string>>>() {usertTokenSecurity};
 }
Exemplo n.º 33
0
        /// <summary>
        /// Register the Mappings endpoint, OWIN middleware and options
        /// </summary>
        /// <param name="container">Autofac DI <see cref="ContainerBuilder"/></param>
        /// <param name="config">Your application's <see cref="IConfiguration"/></param>
        /// <param name="apiExplorer"><see cref="ApiExplorer"/> for iterating registered routes</param>
        public static void RegisterMappingsActuator(this ContainerBuilder container, IConfiguration config, IApiExplorer apiExplorer)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (apiExplorer == null)
            {
                throw new ArgumentNullException(nameof(apiExplorer));
            }

            container.RegisterInstance(new MappingsOptions(config)).As <IMappingsOptions>();
            container.RegisterInstance(apiExplorer);
            container.RegisterType <MappingsEndpoint>().SingleInstance();
            container.RegisterType <MappingsEndpointOwinMiddleware>().SingleInstance();
        }
Exemplo n.º 34
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                var defaultApiKey = _settingManager.GetValue("Swashbuckle.DefaultApiKey", string.Empty);

                swaggerDoc.info.description = string.Format("For this sample, you can use the `{0}` key to test the authorization filters.", defaultApiKey);
                swaggerDoc.info.contact     = new Contact
                {
                    email = "*****@*****.**",
                    name  = "VirtoCommerce",
                    url   = "http://virtocommerce.com"
                };
                swaggerDoc.info.termsOfService = "";
                swaggerDoc.info.license        = new License
                {
                    name = "Virto Commerce Open Software License 3.0",
                    url  = "http://virtocommerce.com/opensourcelicense"
                };
                var tags = _packageService.GetModules().Select(x => new Tag
                {
                    name        = x.Title,
                    description = x.Description
                }).ToList();

                tags.Add(new Tag
                {
                    name        = "VirtoCommerce platform",
                    description = "Platform functionality represent common resources and operations"
                });
                swaggerDoc.tags = tags;
            }
Exemplo n.º 35
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     for (int i = 0; i < 10; i++)
     {
         swaggerDoc.paths.Add("/Fake/" + i + "/{id}", FakePathItem("Fake", i));
     }
     for (int i = 0; i < 2; i++)
     {
         swaggerDoc.paths.Add("/Space Sample/" + i + "/{id}", FakePathItem("Space Sample", i));
     }
     for (int i = 0; i < 2; i++)
     {
         swaggerDoc.paths.Add("/Hash#Sample/" + i + "/{id}", FakePathItem("Hash#Sample", i));
     }
 }
Exemplo n.º 36
0
 public static void UseAllActuators(IConfiguration configuration, ILoggerProvider dynamicLogger, MediaTypeVersion version, ActuatorContext context, IEnumerable <IHealthContributor> healthContributors = null, IApiExplorer apiExplorer = null, ILoggerFactory loggerFactory = null)
 {
     UseCloudFoundryActuators(configuration, dynamicLogger, version, context, healthContributors, apiExplorer, loggerFactory);
     UseEnvActuator(configuration, null, loggerFactory);
     UseRefreshActuator(configuration, loggerFactory);
     UseMetricsActuator(configuration, loggerFactory);
 }
Exemplo n.º 37
0
 public static void UseAllActuators(IConfiguration configuration, ILoggerProvider dynamicLogger, IEnumerable <IHealthContributor> healthContributors = null, IApiExplorer apiExplorer = null, ILoggerFactory loggerFactory = null)
 {
     UseAllActuators(configuration, dynamicLogger, MediaTypeVersion.V1, ActuatorContext.CloudFoundry, healthContributors, apiExplorer, loggerFactory);
 }
Exemplo n.º 38
0
 void IDocumentFilter.Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.paths.Add("/token", new PathItem
     {
         post = new Operation
         {
             tags = new List <string> {
                 "Auth"
             },
             consumes = new List <string>
             {
                 "application/x-www-form-urlencoded"
             },
             parameters = new List <Parameter>
             {
                 new Parameter
                 {
                     type     = "string",
                     name     = "grant_type",
                     required = true,
                     @in      = "formData",
                     @default = "password"
                 },
                 new Parameter
                 {
                     type     = "string",
                     name     = "username",
                     required = false,
                     @in      = "formData"
                 },
                 new Parameter
                 {
                     type     = "string",
                     name     = "password",
                     required = false,
                     @in      = "formData"
                 }
             }
         }
     });
 }
Exemplo n.º 39
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.info.description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia.";
     foreach (var path in swaggerDoc.paths)
     {
         if (path.Key.Contains("foo") && path.Value.get != null)
         {
             path.Value.put = path.Value.get;
         }
     }
 }
Exemplo n.º 40
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                schemaRegistry.GetOrRegister(typeof(ExtraType));
                //schemaRegistry.GetOrRegister(typeof(BigClass));
                foreach (var type in ContractTypes(typeof(ContractClassAttribute)))
                {
                    schemaRegistry.GetOrRegister(type);
                }

                var paths = new Dictionary <string, PathItem>(swaggerDoc.paths);

                swaggerDoc.paths.Clear();
                foreach (var path in paths)
                {
                    if (path.Key.Contains("foo"))
                    {
                        swaggerDoc.paths.Add(path);
                    }
                }
            }
Exemplo n.º 41
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                string file = AppDomain.CurrentDomain.BaseDirectory + "swagger_yaml.txt";

                if (!File.Exists(file))
                {
                    var serializer = new YamlSerializer();
                    serializer.SerializeToFile(file, swaggerDoc);
                }
            }
Exemplo n.º 42
0
 /// <summary>
 /// Applies the specified swagger document.
 /// </summary>
 /// <param name="swaggerDoc">The swagger document.</param>
 /// <param name="schemaRegistry">The schema registry.</param>
 /// <param name="apiExplorer">The API explorer.</param>
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     // sort the definitions and paths
     swaggerDoc.definitions = swaggerDoc.definitions.OrderBy(a => a.Key).ToDictionary(x => x.Key, x => x.Value);
     swaggerDoc.paths       = swaggerDoc.paths.OrderBy(a => a.Key).ToDictionary(x => x.Key, x => x.Value);
 }
Exemplo n.º 43
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                string actionPath = "/attrib/{payId}";

                if (swaggerDoc.paths != null && swaggerDoc.paths.ContainsKey(actionPath))
                {
                    swaggerDoc.paths[actionPath].get.parameters[0].required = false;
                }
            }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.paths = swaggerDoc.paths
                        .ToDictionary(p => p.Key.Replace("Default.", ""), p => p.Value);
 }
Exemplo n.º 45
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                string model = "ViewModelTest";

                if (swaggerDoc.definitions.ContainsKey(model))
                {
                    var props = swaggerDoc.definitions[model].properties.OrderBy(x => x.Key).ToArray();
                    swaggerDoc.definitions[model].properties.Clear();
                    foreach (var prop in props)
                    {
                        swaggerDoc.definitions[model].properties.Add(prop.Key, prop.Value);
                    }
                }
            }
Exemplo n.º 46
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                var version = swaggerDoc.info.version;
                var result  = new Dictionary <string, PathItem>();

                foreach (var pair in swaggerDoc.paths)
                {
                    // remove duplicate version from the key
                    // it was appeared because of the logic in VersioningControllerSelector
                    var key = pair.Key.Replace(string.Format("/api/{0}/{0}", version), "/api/" + version);
                    result.Add(key, pair.Value);
                }
                swaggerDoc.paths = result;
            }
        public static void AttachPerformanceCounters
        (
            HttpConfiguration httpConfiguration
            , string controllerCategoryNamePrefix = null
            , string actionInstanceNamePrefix     = null
        )
        {
            IApiExplorer apiExplorer = httpConfiguration
                                       .Services
                                       .GetApiExplorer();
            var apiDescriptions = apiExplorer
                                  .ApiDescriptions;
            var groups = apiDescriptions
                         .ToLookup
                         (
                (x) =>
            {
                return
                (x
                 .ActionDescriptor
                 .ControllerDescriptor
                 .ControllerName);
            }
                         );
            var processName = Process
                              .GetCurrentProcess()
                              .ProcessName;

            groups
            .AsParallel()
            .WithDegreeOfParallelism(groups.Count)
            .ForAll
            (
                (x) =>
            {
                bool controllerPerformanceCounterProcessed = false;
                foreach (var xx in x)
                {
                    var performanceCounterCategoryName = string
                                                         .Format
                                                         (
                        "{1}{0}{2}"
                        , "-"
                        , controllerCategoryNamePrefix
                        , x.Key
                                                         );
                    var performanceCounterInstanceName = string.Empty;
                    CommonPerformanceCountersContainer commonPerformanceCountersContainer = null;
                    if (!controllerPerformanceCounterProcessed)
                    {
                        performanceCounterInstanceName = "*";
                        var controllerAttribute        = xx
                                                         .ActionDescriptor
                                                         .ControllerDescriptor
                                                         .GetCustomAttributes <CommonPerformanceCounterAttribute>()
                                                         .FirstOrDefault();
                        if (controllerAttribute != null)
                        {
                            if (!string.IsNullOrEmpty(controllerAttribute.PerformanceCounterCategoryName))
                            {
                                performanceCounterCategoryName = controllerAttribute.PerformanceCounterCategoryName;
                            }
                            if (!string.IsNullOrEmpty(controllerAttribute.PerformanceCounterInstanceName))
                            {
                                performanceCounterInstanceName = controllerAttribute.PerformanceCounterInstanceName;
                            }
                        }
                        EasyPerformanceCountersHelper <CommonPerformanceCountersContainer>
                        .AttachPerformanceCountersCategoryInstance
                        (
                            performanceCounterCategoryName
                            , performanceCounterInstanceName
                            , out commonPerformanceCountersContainer
                        );
                        controllerPerformanceCounterProcessed = true;
                    }
                    performanceCounterCategoryName
                        = string
                          .Format
                          (
                              "{1}{0}{2}"
                              , "-"
                              , controllerCategoryNamePrefix
                              , x.Key
                          );
                    performanceCounterInstanceName
                        = string
                          .Format
                          (
                              "{1}{0}{2}{0}{3}{0}{4}{0}{5}"
                              , "-"
                              , actionInstanceNamePrefix
                              , xx
                              .ActionDescriptor
                              .ControllerDescriptor
                              .ControllerName
                              , xx
                              .ActionDescriptor
                              .ActionName
                              , xx
                              .HttpMethod
                              .Method
                              , processName
                          );
                    var actionAttribute = xx
                                          .ActionDescriptor
                                          .GetCustomAttributes <CommonPerformanceCounterAttribute>()
                                          .FirstOrDefault();
                    if (actionAttribute != null)
                    {
                        if (!string.IsNullOrEmpty(actionAttribute.PerformanceCounterCategoryName))
                        {
                            performanceCounterCategoryName = actionAttribute.PerformanceCounterCategoryName;
                        }
                        if (!string.IsNullOrEmpty(actionAttribute.PerformanceCounterInstanceName))
                        {
                            performanceCounterInstanceName = actionAttribute.PerformanceCounterInstanceName;
                        }
                    }
                    EasyPerformanceCountersHelper <CommonPerformanceCountersContainer>
                    .AttachPerformanceCountersCategoryInstance
                    (
                        performanceCounterCategoryName
                        , performanceCounterInstanceName
                        , out commonPerformanceCountersContainer
                    );
                }
            }
            );
        }
Exemplo n.º 48
0
        public static void ConfigureManagementActuators(IConfiguration configuration, ILoggerProvider dynamicLogger, IApiExplorer apiExplorer, ILoggerFactory loggerFactory = null)
        {
            ActuatorConfigurator.UseCloudFoundryActuators(configuration, dynamicLogger, null, apiExplorer, loggerFactory);

            // You can individually configure actuators as shown below if you don't want all of them
            // ActuatorConfigurator.UseCloudFoundrySecurity(configuration, null, loggerFactory);
            //  ActuatorConfigurator.UseCloudFoundryActuator(configuration, loggerFactory);
            // ActuatorConfigurator.UseHealthActuator(configuration, null, GetHealthContributors(configuration), loggerFactory);
            // ActuatorConfigurator.UseHealthActuator(configuration, null, null, loggerFactory);
            //ActuatorConfigurator.UseHeapDumpActuator(configuration, null, loggerFactory);
            //ActuatorConfigurator.UseThreadDumpActuator(configuration, null, loggerFactory);
            // ActuatorConfigurator.UseInfoActuator(configuration, null, loggerFactory);
            // ActuatorConfigurator.UseLoggerActuator(configuration, dynamicLogger, loggerFactory);
            //  ActuatorConfigurator.UseTraceActuator(configuration, null, loggerFactory);
            //  ActuatorConfigurator.UseMappingsActuator(configuration, apiExplorer, loggerFactory);

            // Uncomment if you want to enable metrics actuator endpoint, it's not enabled by default
            //  ActuatorConfigurator.UseMetricsActuator(configuration, loggerFactory);
        }
Exemplo n.º 49
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.host = "foo";
 }
Exemplo n.º 50
0
        /// <summary>
        /// Add all actuator OWIN Middlewares, configure CORS and Cloud Foundry request security
        /// </summary>
        /// <param name="container">Autofac DI <see cref="ContainerBuilder"/></param>
        /// <param name="config">Your application's <see cref="IConfiguration"/></param>
        /// <param name="apiExplorer">An <see cref="ApiExplorer" /> that has access to your HttpConfiguration.<para />If not provided, mappings actuator will not be registered</param>
        public static void RegisterCloudFoundryActuators(this ContainerBuilder container, IConfiguration config, IApiExplorer apiExplorer = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            container.RegisterDiagnosticSourceMiddleware();
            container.RegisterCloudFoundrySecurityMiddleware(config);
            container.RegisterCloudFoundryActuator(config);
            container.RegisterHealthActuator(config);
            container.RegisterHeapDumpActuator(config);
            container.RegisterInfoActuator(config);
            container.RegisterLoggersActuator(config);
            if (apiExplorer != null)
            {
                container.RegisterMappingsActuator(config, apiExplorer);
            }

            container.RegisterMetricsActuator(config);
            container.RegisterThreadDumpActuator(config);
            container.RegisterTraceActuator(config);
        }
Exemplo n.º 51
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.definitions["Object"].vendorExtensions["additionalProperties"] = true;
 }
Exemplo n.º 52
0
 public ApiExplorerServiceVersion1(IApiExplorer apiExplorer, string baseUri = null)
     : base(apiExplorer, baseUri)
 {
     typeBuilder = new Raml1TypeBuilder(RamlTypes);
 }
Exemplo n.º 53
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                schemaRegistry.GetOrRegister(typeof(GeolocateResponse));
                schemaRegistry.GetOrRegister(typeof(CountingLock1));
                schemaRegistry.GetOrRegister(typeof(CountingLock2));
                schemaRegistry.GetOrRegister(typeof(Coordinate));

                if (swaggerDoc.definitions != null && swaggerDoc.definitions.ContainsKey("Company"))
                {
                    swaggerDoc.definitions.Add("Company123", swaggerDoc.definitions["Company"]);
                }
                if (swaggerDoc.paths != null && swaggerDoc.paths.ContainsKey("/api/Company"))
                {
                    var get      = swaggerDoc.paths["/api/Company"].get;
                    var response = get.responses["200"];
                    response.schema.@ref = "#/definitions/Company123";
                    response.description =
                        "## MARKDOWN DoubleHash \n" +
                        "### MARKDOWN TripleHash \n" +
                        "`MARKDOWN code` \n " + get.description;

                    var post = swaggerDoc.paths["/api/Company"].post;
                    post.description = "foo | bar\r\n----|----\r\nbaz | qux &#x7c; quux";
                }
            }
Exemplo n.º 54
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                swaggerDoc.info.description = "Lorem ipsum dolor sit amet, <b>consectetur adipiscing elit</b>, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <br>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
                                              "<ul>" +
                                              "<li>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</li>" +
                                              "<li>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia.</li>" +
                                              "</ul>" +
                                              "The code for this project is here: https://github.com/heldersepu/Swagger-Net-Test";

                /*foreach (var path in swaggerDoc.paths)
                 * {
                 *  if (path.Key.Contains("foo") && path.Value.get != null)
                 *  {
                 *      path.Value.put = path.Value.get;
                 *  }
                 * }*/
            }
 public ApiExplorerServiceVersion08(IApiExplorer apiExplorer, string baseUri = null) : base(apiExplorer, baseUri)
 {
 }
Exemplo n.º 56
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                if (swaggerDoc.paths != null)
                {
                    if (swaggerDoc.paths.ContainsKey("/api/PngImage"))
                    {
                        var post = swaggerDoc.paths["/api/PngImage"].post;
                        post.produces.Clear();
                        post.produces.Add("image/png");
                    }
                    if (swaggerDoc.paths.ContainsKey("/api/Image"))
                    {
                        var put = swaggerDoc.paths["/api/Image"].put;
                        if (put != null)
                        {
                            put.responses["200"].schema      = new Schema();
                            put.responses["200"].schema.type = "file";
                        }

                        var patch = swaggerDoc.paths["/api/Image"].patch;
                        if (patch != null)
                        {
                            foreach (var param in patch.parameters)
                            {
                                if (param.name == "templateFile")
                                {
                                    param.type = "file";
                                    param.@in  = "formData";
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 57
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     if (swaggerDoc.paths != null)
     {
         foreach (var path in swaggerDoc.paths)
         {
             ProcessOperation(path.Value.get);
             ProcessOperation(path.Value.put);
             ProcessOperation(path.Value.post);
             ProcessOperation(path.Value.delete);
             ProcessOperation(path.Value.options);
             ProcessOperation(path.Value.head);
             ProcessOperation(path.Value.patch);
         }
     }
 }
Exemplo n.º 58
0
        public static void UseCloudFoundryActuators(IConfiguration configuration, ILoggerProvider dynamicLogger, MediaTypeVersion version, ActuatorContext context, IEnumerable <IHealthContributor> healthContributors = null, IApiExplorer apiExplorer = null, ILoggerFactory loggerFactory = null)
        {
            if (context != ActuatorContext.Actuator)
            {
                UseCloudFoundrySecurity(configuration, null, loggerFactory);
                UseCloudFoundryActuator(configuration, loggerFactory);
            }
            else
            {
                UseHypermediaActuator(configuration, loggerFactory);
            }

            UseHealthActuator(configuration, null, healthContributors, loggerFactory);
            UseHeapDumpActuator(configuration, null, loggerFactory);
            UseThreadDumpActuator(configuration, version, null, loggerFactory);
            UseInfoActuator(configuration, null, loggerFactory);
            UseLoggerActuator(configuration, dynamicLogger, loggerFactory);
            UseTraceActuator(configuration, version, null, loggerFactory);
            UseMappingsActuator(configuration, apiExplorer, loggerFactory);
        }
Exemplo n.º 59
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.tags = new List <Tag>
     {
     };
 }
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            // Change host to be UI
            swaggerDoc.host = UrlHelper.TrimProtocol(ApplicationConfiguration.UrlUI);

            // Remove private API calls from live docs
            if (ApplicationConfiguration.IsEnvironmentLive)
            {
                var omitedControllers = new List<string>
                {
                    "Home",
                    "Log",
                    "StaticReports",
                    "PdfReporting",
                    "NonPublicServices"
                };

                foreach (var apiDescription in apiExplorer.ApiDescriptions)
                {
                    if (omitedControllers.Contains(apiDescription.ActionDescriptor.ControllerDescriptor.ControllerName))
                    {
                        var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/');
                        swaggerDoc.paths.Remove(route);
                    }
                }
            }
        }