public static HttpResponseMessage ShowSwaggerHtmlResponse(IRocketScienceRequest req, ILogger logger)
        {
            try
            {
                if (_docs == null)
                {
                    try
                    {
                        _docs = GenerateSwagger(req, logger, GetCallingAzureFunction().DeclaringType.Assembly);
                    }
                    catch (Exception e)
                    {
                        var errorResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                        errorResponse.Content = new StringContent($"Docs Error: {e.Message}");
                        errorResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                        return(errorResponse);
                    }
                }

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(GetSwaggerHtml(_docs));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(response);
            }
            catch (Exception e)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent($"<pre>Whoops: \r\n{e.ToString()}</pre>");
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(response);
            }
        }
        private void CreateTypeOrTable(string itemType, string keyspace, SwaggerRoot swaggerRoot, string itemName)
        {
            var itemNameCassandrified = Utils.Utils.CassandrifyName(itemName);
            var columnDefinitions     = GetColumnDefinitions(itemType, swaggerRoot.Definitions[itemName].Properties);
            var cql = $"create {itemType} if not exists {keyspace}.{itemNameCassandrified} {columnDefinitions} ;";

            this.cqlStatements.Add(cql);
        }
예제 #3
0
        private void SaveSplitterSwagger(SwaggerRoot swagger, string entityName)
        {
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.swaggerJsonFile);
            var extension   = Path.GetExtension(this.swaggerJsonFile);
            var newFileName = fileNameWithoutExtension + entityName + extension;

            newFileName = Path.Combine(this.outputFolder, newFileName);
            File.WriteAllText(newFileName, swagger.ToJson());
        }
        //--------------------------------------------------------------------------------
        /// <summary>
        /// Turn swagger documentation into html
        /// </summary>
        //--------------------------------------------------------------------------------
        private static string GetSwaggerHtml(SwaggerRoot docs)
        {
            var content = new StringBuilder();

            content.AppendLine("<pre>");
            content.AppendLine($"{docs.Info.Title} Version {docs.Info.Version}");
            content.AppendLine($"\r\nPaths: ");

            void DoOperation(string path, Operation operation)
            {
                if (operation == null)
                {
                    return;
                }
                content.AppendLine($"    {docs.BasePath}{path}");
                content.AppendLine($"        Parameters:");
                foreach (var parameter in operation.Parameters)
                {
                    var requiredText = parameter.Required.Value ? " * " : "   ";
                    content.AppendLine($"            {requiredText}{parameter.Type} {parameter.Name} in {parameter.In}   {parameter.Description}");
                }

                content.AppendLine($"        Responses:");
                foreach (var response in operation.Responses)
                {
                    content.AppendLine($"               {response.Key} {response.Value.Schema.Type} {response.Value.Description}");
                    foreach (var item in response.Value.Schema.Properties)
                    {
                        content.AppendLine($"                   {item.Value.Type} {item.Key} {item.Value.Description}");
                    }
                }
            }

            foreach (var pathEntry in docs.Paths)
            {
                DoOperation(pathEntry.Key, pathEntry.Value.Get);
                DoOperation(pathEntry.Key, pathEntry.Value.Delete);
                DoOperation(pathEntry.Key, pathEntry.Value.Head);
                DoOperation(pathEntry.Key, pathEntry.Value.Options);
                DoOperation(pathEntry.Key, pathEntry.Value.Patch);
                DoOperation(pathEntry.Key, pathEntry.Value.Post);
                DoOperation(pathEntry.Key, pathEntry.Value.Put);
            }

            content.AppendLine($"Security:");

            foreach (var securityEntry in docs.SecurityDefinitions)
            {
                content.AppendLine($"     {securityEntry.Key}:{securityEntry.Value.Name}");
            }
            content.AppendLine("</pre>");
            return(content.ToString());
        }
 /// <summary>
 /// Allows other root level swagger values to be set.
 /// </summary>
 public static void SetSwaggerRoot(string host = null, string basePath = null, IEnumerable <Schemes> schemes = null,
                                   IEnumerable <string> consumes = null, IEnumerable <string> produces = null, ExternalDocumentation externalDocumentation = null)
 {
     _swaggerRoot = new SwaggerRoot
     {
         Host     = host,
         BasePath = basePath,
         Schemes  = schemes,
         Consumes = consumes,
         Produces = produces,
         ExternalDocumentation = externalDocumentation
     };
 }
예제 #6
0
 private static void ReinjectSecurity(SwaggerRoot swaggerRoot, JsonArray security)
 {
     swaggerRoot.Security = new Dictionary <SecuritySchemes, IEnumerable <string> >();
     foreach (JsonObject sec in security)
     {
         foreach (var securitySchemeName in sec.Keys)
         {
             var securityScheme  = (SecuritySchemes)Enum.Parse(typeof(SecuritySchemes), securitySchemeName);
             var permissions     = (JsonArray)sec[securitySchemeName];
             var permissionsList = new List <string>();
             permissions.ForEach(p => permissionsList.Add((string)p));
             swaggerRoot.Security.Add(securityScheme, permissionsList);
         }
     }
 }
예제 #7
0
        private SwaggerRoot DeleteAllPathsNotRelatedTo(SwaggerRoot swaggerRoot, string entityName)
        {
            var entityNamePlural = pluralizer.Pluralize(entityName);
            var prefix           = $"/{entityNamePlural.ToLowerInvariant()}/";
            var swaggerCopy      = Utils.Utils.Clone(swaggerRoot);

            swaggerRoot
            .Paths
            .Keys
            .Where(p => !Utils.Utils.InvariantStartsWith(p, prefix))
            .ToList()
            .ForEach(p => swaggerCopy.Paths.Remove(p));

            return(swaggerCopy.Paths.Any() ? swaggerCopy : null);
        }
        private void CreateTags(SwaggerRoot swaggerRoot)
        {
            if (swaggerRoot.Tags == null)
            {
                swaggerRoot.Tags = new List <Tag>();
            }
            var tags = swaggerRoot.Tags.ToList();

            if (tags.All(t => t.Name != "Namespace"))
            {
                tags.Add(new Tag {
                    Name = "Namespace", Description = Utils.Utils.CSharpifyName(this.keyNameSpace)
                });
            }
            swaggerRoot.Tags = tags;
        }
 private void CreateUserDefinedTypesIfNeeded(string keyspace, SwaggerRoot swaggerRoot)
 {
     foreach (var entity in swaggerRoot.Definitions)
     {
         var entityName = entity.Key;
         foreach (var propertyName in entity.Value.Properties.Keys)
         {
             var property = entity.Value.Properties[propertyName];
             var udtName  = property?.Ref ?? property?.Items?.Ref;
             if (udtName != null)
             {
                 udtName = GetRefname(udtName);
                 userDefinedTypes.Add(udtName);
                 CreateTypeOrTable("type", keyspace, swaggerRoot, udtName);
             }
         }
     }
 }
예제 #10
0
        internal string GenerateForControllers(IEnumerable <Type> types)
        {
            var swagger = new SwaggerRoot
            {
                Info    = _scope.Settings.Info,
                Host    = _scope.Settings.Host,
                Schemes = _scope.Settings.Schemes,
                Paths   = types
                          .SelectMany(GeneratePaths)
                          .ToDictionary(t => t.Item1, t => t.Item2),
                Definitions = _scope.SwaggerSchemas
            };

            swagger.Security            = _scope.Settings.Security;
            swagger.SecurityDefinitions = _scope.Settings.SecurityDefinitions;
            //Add default error model
            swagger.Definitions.Add(ErrorModel.Name, ErrorModel.Schema);
            return(swagger.ToJson());
        }
예제 #11
0
        internal string GenerateForControllers(IEnumerable <Type> types)
        {
            var swagger = new SwaggerRoot
            {
                Info    = _scope.Settings.Info,
                Host    = _scope.Settings.Host,
                Schemes = _scope.Settings.Schemes,
                Paths   = types
                          .SelectMany(GeneratePaths)
                          .ToLookup(t => t.Item1, t => t.Item2) // for when methods for same route where in different classes
                          .ToDictionary(g => g.Key, t => PathItem.Merge(t.ToArray())),
                Definitions         = _scope.SwaggerSchemas,
                Security            = _scope.Settings.Security,
                SecurityDefinitions = _scope.Settings.SecurityDefinitions,
                Produces            = _scope.Settings.Produces
            };

            swagger.Definitions.Add(ErrorModel.Name, ErrorModel.Schema);
            return(swagger.ToJson());
        }
        //--------------------------------------------------------------------------------
        /// <summary>
        /// Get the swagger documentation for this assembly
        /// </summary>
        //--------------------------------------------------------------------------------
        public static HttpResponseMessage ShowSwaggerHtmlResponse(HttpRequestMessage req, IServiceLogger logger)
        {
            try
            {
                if (_docs == null)
                {
                    _docs = GenerateSwagger(req, logger, Assembly.GetCallingAssembly());
                }

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(GetSwaggerHtml(_docs));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(response);
            }
            catch (Exception e)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent($"<pre>Whoops: \r\n{e.ToString()}</pre>");
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(response);
            }
        }
        //--------------------------------------------------------------------------------
        /// <summary>
        /// Auto-generate swagger doc tree from the calling assembly
        /// </summary>
        //--------------------------------------------------------------------------------
        private static SwaggerRoot GenerateSwagger(IRocketScienceRequest req, ILogger logger, Assembly functionAssembly)
        {
            var caller = GetCallingAzureFunction();
            var paths  = new Dictionary <string, PathItem>();


            string GetKeyFromTrigger(object httpTriggerAttribute)
            {
                return(GetPropertyValue <string>(httpTriggerAttribute, "Route")
                       + " ("
                       + string.Join(",", GetPropertyValue <string[]>(httpTriggerAttribute, "Methods")) + ")");
            }

            // Go through all the types in the calling assembly
            foreach (var type in functionAssembly.GetTypes())
            {
                // Azure functions are public and static
                foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
                {
                    // Must have a function name attribute
                    var functionAtttribute = method.CustomAttributes.Where(a => a.AttributeType.Name == "FunctionNameAttribute").FirstOrDefault();
                    if (functionAtttribute == null)
                    {
                        continue;
                    }

                    // Must have http trigger attribute on the first parameter
                    var parameters = method.GetParameters();
                    if (parameters.Length < 2)
                    {
                        continue;
                    }
                    var httpTriggerAttribute = GetCustomAttribute(parameters[0], "HttpTriggerAttribute");
                    if (httpTriggerAttribute == null)
                    {
                        continue;
                    }

                    // By convention, we'll exclude the azure function calling us
                    if (method.Name == caller.Name && method.DeclaringType.Name == caller.DeclaringType.Name)
                    {
                        continue;
                    }

                    paths.Add(GetKeyFromTrigger(httpTriggerAttribute), CreatePathItemFromMethod(method));
                }
            }

            var security = new Dictionary <string, SecurityScheme>();

            security.Add("apikeyQuery", new SecurityScheme()
            {
                Name = "code",
                Type = SecuritySchemes.ApiKey,
                In   = ApiKeyLocations.Query
            });

            var callerTriggerInfo = GetCustomAttribute(caller.GetParameters()[0], "HttpTriggerAttribute");
            var callerPath        = GetPropertyValue <string>(callerTriggerInfo, "Route");

            var root = new SwaggerRoot()
            {
                Info = new Info()
                {
                    Title = req.Host, Version = functionAssembly.GetName().Version.ToString()
                },
                Host                = req.Host,
                BasePath            = req.LocalPath.Substring(0, req.LocalPath.Length - callerPath.Length),
                Schemes             = new[] { Schemes.Https },
                Paths               = paths,
                Definitions         = new Dictionary <string, Schema>(),
                SecurityDefinitions = security
            };

            return(root);
        }
예제 #14
0
 internal static string ToJson(this SwaggerRoot value)
 {
     return(JsonConvert.SerializeObject(value, _settings));
 }