Exemplo n.º 1
0
        /// <summary>Loads a JSON Schema from a given file path (only available in .NET 4.x).</summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The JSON Schema.</returns>
        /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception>
        public static async Task <JsonSchema4> FromFileAsync(string filePath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
        {
            var data = await DynamicApis.FileReadAllTextAsync(filePath);

            return(await FromJsonAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false));
        }
Exemplo n.º 2
0
        /// <summary>Creates a Swagger specification from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The <see cref="SwaggerDocument" />.</returns>
        public static async Task <SwaggerDocument> FromFileAsync(string filePath)
        {
            var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false);

            return(await FromJsonAsync(data, filePath).ConfigureAwait(false));
        }
Exemplo n.º 3
0
        /// <summary>Creates a Swagger specification from an URL.</summary>
        /// <param name="url">The URL.</param>
        /// <returns>The <see cref="SwaggerDocument"/>.</returns>
        public static async Task <SwaggerDocument> FromUrlAsync(string url)
        {
            var data = await DynamicApis.HttpGetAsync(url).ConfigureAwait(false);

            return(await FromJsonAsync(data, url).ConfigureAwait(false));
        }
        /// <summary>Resolves file path.</summary>
        /// <param name="documentPath">The document path.</param>
        /// <param name="jsonPath">The JSON path</param>
        public virtual string ResolveFilePath(string documentPath, string jsonPath)
        {
            var arr = Regex.Split(jsonPath, @"(?=#)");

            return(DynamicApis.PathCombine(DynamicApis.PathGetDirectoryName(documentPath), arr[0]));
        }
Exemplo n.º 5
0
 /// <summary>Adds a document reference.</summary>
 /// <param name="documentPath">The document path.</param>
 /// <param name="schema">The referenced schema.</param>
 public void AddDocumentReference(string documentPath, IJsonReference schema)
 {
     _resolvedObjects[documentPath.Contains("://") ? documentPath : DynamicApis.GetFullPath(documentPath)] = schema;
 }
Exemplo n.º 6
0
        /// <summary>Creates a Swagger specification from an URL.</summary>
        /// <param name="url">The URL.</param>
        /// <returns>The <see cref="SwaggerService"/>.</returns>
        public static SwaggerService FromUrl(string url)
        {
            var data = DynamicApis.HttpGet(url);

            return(FromJson(data, url));
        }
Exemplo n.º 7
0
        public async Task <SwaggerDocument> RunAsync()
        {
            return(await Task.Run(async() =>
            {
                if (!string.IsNullOrEmpty(DocumentTemplate))
                {
                    if (await DynamicApis.FileExistsAsync(DocumentTemplate).ConfigureAwait(false))
                    {
                        Settings.DocumentTemplate = await DynamicApis.FileReadAllTextAsync(DocumentTemplate).ConfigureAwait(false);
                    }
                    else
                    {
                        Settings.DocumentTemplate = DocumentTemplate;
                    }
                }
                else
                {
                    Settings.DocumentTemplate = null;
                }

                var generator = CreateGenerator();
                var controllerNames = ControllerNames.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                if (!controllerNames.Any() && Settings.AssemblyPaths?.Length > 0)
                {
                    controllerNames = generator.GetControllerClasses().ToList();
                }

                var document = await generator.GenerateForControllersAsync(controllerNames).ConfigureAwait(false);

                if (ServiceHost == ".")
                {
                    document.Host = string.Empty;
                }
                else if (!string.IsNullOrEmpty(ServiceHost))
                {
                    document.Host = ServiceHost;
                }

                if (!string.IsNullOrEmpty(InfoTitle))
                {
                    document.Info.Title = InfoTitle;
                }
                if (!string.IsNullOrEmpty(InfoVersion))
                {
                    document.Info.Version = InfoVersion;
                }
                if (!string.IsNullOrEmpty(InfoDescription))
                {
                    document.Info.Description = InfoDescription;
                }

                if (ServiceSchemes != null && ServiceSchemes.Any())
                {
                    document.Schemes = ServiceSchemes.Select(s => (SwaggerSchema)Enum.Parse(typeof(SwaggerSchema), s, true)).ToList();
                }

                if (!string.IsNullOrEmpty(ServiceBasePath))
                {
                    document.BasePath = ServiceBasePath;
                }

                return document;
            }));
        }
Exemplo n.º 8
0
        /// <summary>Loads a JSON Schema from a given file path (only available in .NET 4.x).</summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The JSON Schema.</returns>
        /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception>
        public static async Task <JsonSchema> FromFileAsync(string filePath, Func <JsonSchema, JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(await FromJsonAsync(data, filePath, referenceResolverFactory, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 9
0
        /// <summary>Loads a JSON Schema from a given URL (only available in .NET 4.x).</summary>
        /// <param name="url">The URL to the document.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The JSON Schema.</returns>
        /// <exception cref="NotSupportedException">The HttpClient.GetAsync API is not available on this platform.</exception>
        public static async Task <JsonSchema> FromUrlAsync(string url, Func <JsonSchema, JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
        {
            var data = await DynamicApis.HttpGetAsync(url, cancellationToken).ConfigureAwait(false);

            return(await FromJsonAsync(data, url, referenceResolverFactory, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 10
0
        internal static XElement GetXmlDocsElement(this XDocument xml, string name)
        {
            var result = (IEnumerable)DynamicApis.XPathEvaluate(xml, $"/doc/members/member[@name='{name}']");

            return(result.OfType <XElement>().FirstOrDefault());
        }
Exemplo n.º 11
0
        private static string GetXmlDocsPath(dynamic assembly)
        {
            string path;

            try
            {
                if (assembly == null)
                {
                    return(null);
                }

                var assemblyName = assembly.GetName();
                if (string.IsNullOrEmpty(assemblyName.Name))
                {
                    return(null);
                }

                if (Cache.ContainsKey(assemblyName.FullName))
                {
                    return(null);
                }

                if (!string.IsNullOrEmpty(assembly.Location))
                {
                    var assemblyDirectory = DynamicApis.PathGetDirectoryName((string)assembly.Location);
                    path = DynamicApis.PathCombine(assemblyDirectory, (string)assemblyName.Name + ".xml");
                    if (DynamicApis.FileExists(path))
                    {
                        return(path);
                    }
                }

                if (ObjectExtensions.HasProperty(assembly, "CodeBase"))
                {
                    var codeBase = (string)assembly.CodeBase;
                    if (!string.IsNullOrEmpty(codeBase))
                    {
                        path = DynamicApis.PathCombine(DynamicApis.PathGetDirectoryName(codeBase
                                                                                        .Replace("file:///", string.Empty)), assemblyName.Name + ".xml")
                               .Replace("file:\\", string.Empty);

                        if (DynamicApis.FileExists(path))
                        {
                            return(path);
                        }
                    }
                }

                var currentDomain = Type.GetType("System.AppDomain")?.GetRuntimeProperty("CurrentDomain").GetValue(null);
                if (currentDomain?.HasProperty("BaseDirectory") == true)
                {
                    var baseDirectory = currentDomain.TryGetPropertyValue("BaseDirectory", "");
                    if (!string.IsNullOrEmpty(baseDirectory))
                    {
                        path = DynamicApis.PathCombine(baseDirectory, assemblyName.Name + ".xml");
                        if (DynamicApis.FileExists(path))
                        {
                            return(path);
                        }

                        return(DynamicApis.PathCombine(baseDirectory, "bin\\" + assemblyName.Name + ".xml"));
                    }
                }

                var currentDirectory = DynamicApis.DirectoryGetCurrentDirectory();
                path = DynamicApis.PathCombine(currentDirectory, assembly.GetName().Name + ".xml");
                if (DynamicApis.FileExists(path))
                {
                    return(path);
                }

                path = DynamicApis.PathCombine(currentDirectory, "bin\\" + assembly.GetName().Name + ".xml");
                if (DynamicApis.FileExists(path))
                {
                    return(path);
                }

                return(null);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 12
0
        /// <summary>Creates a Swagger specification from an URL.</summary>
        /// <param name="url">The URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="OpenApiDocument"/>.</returns>
        public static async Task <OpenApiDocument> FromUrlAsync(string url, CancellationToken cancellationToken = default)
        {
            var data = await DynamicApis.HttpGetAsync(url, cancellationToken).ConfigureAwait(false);

            return(await FromJsonAsync(data, url, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 13
0
        /// <summary>Creates a Swagger specification from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="OpenApiDocument" />.</returns>
        public static async Task <OpenApiDocument> FromFileAsync(string filePath, CancellationToken cancellationToken = default)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(await FromJsonAsync(data, filePath, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 14
0
        /// <summary>Creates a Swagger specification from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The <see cref="OpenApiDocument" />.</returns>
        public static async Task <OpenApiDocument> FromFileAsync(string filePath)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(await FromYamlAsync(data, filePath).ConfigureAwait(false));
        }
Exemplo n.º 15
0
        /// <summary>Loads a JSON Schema from a given URL (only available in .NET 4.x).</summary>
        /// <param name="url">The URL to the document.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The JSON Schema.</returns>
        /// <exception cref="NotSupportedException">The HttpClient.GetAsync API is not available on this platform.</exception>
        public static async Task <JsonSchema4> FromUrlAsync(string url, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
        {
            var data = await DynamicApis.HttpGetAsync(url);

            return(await FromJsonAsync(data, url, referenceResolverFactory).ConfigureAwait(false));
        }
Exemplo n.º 16
0
        protected void RegisterReferencePaths(IEnumerable <string> referencePaths)
        {
#if FullNet
            var allReferencePaths = new List <string>(GetAllDirectories(AppDomain.CurrentDomain.SetupInformation.ApplicationBase));
#else
            var allReferencePaths = new List <string>();
#endif

            foreach (var path in referencePaths.Where(p => !string.IsNullOrWhiteSpace(p)))
            {
                allReferencePaths.Add(path);
                allReferencePaths.AddRange(GetAllDirectories(path));
            }

            // Add path to executable directory
            allReferencePaths.Add(Path.GetDirectoryName(typeof(AssemblyLoader).GetTypeInfo().Assembly.CodeBase.Replace("file:///", string.Empty)));
            allReferencePaths = allReferencePaths.Distinct().ToList();

#if FullNet
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
#else
            var assembliesLoadedByName = new HashSet <string>(); // used to avoid recursions
            Context.Resolving         += (context, args) =>
#endif
            {
                var separatorIndex = args.Name.IndexOf(",", StringComparison.Ordinal);
                var assemblyName   = separatorIndex > 0 ? args.Name.Substring(0, separatorIndex) : args.Name;

#if FullNet
                var existingAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == assemblyName);
                if (existingAssembly != null)
                {
                    return(existingAssembly);
                }
#endif

                foreach (var path in allReferencePaths)
                {
                    var files = Directory.GetFiles(path, assemblyName + ".dll", SearchOption.TopDirectoryOnly);
                    foreach (var file in files)
                    {
                        try
                        {
#if FullNet
                            return(Assembly.LoadFrom(file));
#else
                            var currentDirectory = DynamicApis.DirectoryGetCurrentDirectoryAsync().GetAwaiter().GetResult();
                            return(Context.LoadFromAssemblyPath(PathUtilities.MakeAbsolutePath(file, currentDirectory)));
#endif
                        }
                        catch (Exception exception)
                        {
                            Debug.WriteLine("NSwag: AssemblyLoader exception when loading assembly by file '" + file + "': \n" + exception.ToString());
                        }
                    }
                }

#if !FullNet
                if (!assembliesLoadedByName.Contains(assemblyName))
                {
                    try
                    {
                        assembliesLoadedByName.Add(assemblyName);
                        return(Context.LoadFromAssemblyName(new AssemblyName(assemblyName)));
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine("NSwag: AssemblyLoader exception when loading assembly by name '" + assemblyName + "': \n" + exception.ToString());
                    }
                }
#endif

                return(null);
            };
        }
Exemplo n.º 17
0
        /// <summary>Creates a Swagger specification from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The <see cref="SwaggerDocument" />.</returns>
        public static SwaggerDocument FromFile(string filePath)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(FromJson(data, filePath));
        }
Exemplo n.º 18
0
        internal static XElement?GetXmlDocsElement(this XDocument xml, string name)
        {
            var result = (IEnumerable)DynamicApis.XPathEvaluate(xml, $"/doc/members/member[@name='{name}']");

            return(CachingXDocument.GetXmlDocsElement(xml, name));
        }