コード例 #1
0
ファイル: NSwagDocumentBase.cs プロジェクト: mssomrgda/NSwag
        /// <summary>Loads an existing NSwagDocument.</summary>
        /// <typeparam name="TDocument">The type.</typeparam>
        /// <param name="filePath">The file path.</param>
        /// <param name="mappings">The mappings.</param>
        /// <returns>The document.</returns>
        protected static Task <TDocument> LoadAsync <TDocument>(string filePath, IDictionary <Type, Type> mappings)
            where TDocument : NSwagDocumentBase, new()
        {
            return(Task.Run(async() =>
            {
                var saveFile = false;
                var data = DynamicApis.FileReadAllText(filePath);
                data = TransformLegacyDocument(data, out saveFile); // TODO: Remove this legacy stuff later

                var settings = GetSerializerSettings();
                settings.ContractResolver = new BaseTypeMappingContractResolver(mappings);

                var document = JsonConvert.DeserializeObject <TDocument>(data, settings);
                document.Path = filePath;
                document.ConvertToAbsolutePaths();
                document._latestData = JsonConvert.SerializeObject(document, Formatting.Indented, GetSerializerSettings());

                if (saveFile)
                {
                    await document.SaveAsync();
                }

                return document;
            }));
        }
コード例 #2
0
        public static Task <bool> TryWriteFileOutputAsync(this IOutputCommand command, string path, IConsoleHost host, NewLineBehavior newLineBehavior, Func <string> generator)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var directory = DynamicApis.PathGetDirectoryName(path);
                if (!string.IsNullOrEmpty(directory) && DynamicApis.DirectoryExists(directory) == false)
                {
                    DynamicApis.DirectoryCreateDirectory(directory);
                }

                var data = generator();

                data = data?.Replace("\r", "") ?? "";
                data = newLineBehavior == NewLineBehavior.Auto ? data.Replace("\n", Environment.NewLine) :
                       newLineBehavior == NewLineBehavior.CRLF ? data.Replace("\n", "\r\n") : data;

                if (!DynamicApis.FileExists(path) || DynamicApis.FileReadAllText(path) != data)
                {
                    DynamicApis.FileWriteAllText(path, data);

                    host?.WriteMessage("Code has been successfully written to file.\n");
                }
                else
                {
                    host?.WriteMessage("Code has been successfully generated but not written to file (no change detected).\n");
                }
                return(Task.FromResult(true));
            }
            return(Task.FromResult(false));
        }
コード例 #3
0
        public async Task <SwaggerDocument> RunAsync()
        {
            return(await Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(DocumentTemplate))
                {
                    if (DynamicApis.FileExists(DocumentTemplate))
                    {
                        Settings.DocumentTemplate = DynamicApis.FileReadAllText(DocumentTemplate);
                    }
                    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 = generator.GenerateForControllers(controllerNames);

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

                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;
            }));
        }
コード例 #4
0
        public async Task LoadSwaggerUrlAsync(string url)
        {
            var json = string.Empty;

            await RunTaskAsync(async() =>
            {
                json = url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ||
                       url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) ?
                       await DynamicApis.HttpGetAsync(url) : DynamicApis.FileReadAllText(url);
                json = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented);
            });

            Command.Json = json;
        }
コード例 #5
0
        public async Task <string> RunAsync()
        {
            return(await Task.Run(() =>
            {
                var additionalCode = ExtensionCode ?? string.Empty;
                if (DynamicApis.FileExists(additionalCode))
                {
                    additionalCode = DynamicApis.FileReadAllText(additionalCode);
                }
                Settings.TypeScriptGeneratorSettings.ExtensionCode = additionalCode;

                var clientGenerator = new SwaggerToTypeScriptClientGenerator(InputSwaggerDocument, Settings);
                return clientGenerator.GenerateFile();
            }));
        }
コード例 #6
0
        public async Task <string> RunAsync()
        {
            var additionalCode = ExtensionCode ?? string.Empty;

            if (DynamicApis.FileExists(additionalCode))
            {
                additionalCode = DynamicApis.FileReadAllText(additionalCode);
            }

            Settings.TypeScriptGeneratorSettings.ExtensionCode = additionalCode;

            var document = await GetInputSwaggerDocument().ConfigureAwait(false);

            var clientGenerator = new TypeScriptClientGenerator(document, Settings);

            return(clientGenerator.GenerateFile());
        }
コード例 #7
0
        /// <summary>Loads an existing NSwagDocument.</summary>
        /// <typeparam name="TDocument">The type.</typeparam>
        /// <param name="filePath">The file path.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="applyTransformations">Specifies whether to expand environment variables and convert variables.</param>
        /// <param name="mappings">The mappings.</param>
        /// <returns>The document.</returns>
        protected static Task <TDocument> LoadAsync <TDocument>(
            string filePath,
            string variables,
            bool applyTransformations,
            IDictionary <Type, Type> mappings)
            where TDocument : NSwagDocumentBase, new()
        {
            return(Task.Run(async() =>
            {
                var data = DynamicApis.FileReadAllText(filePath);
                data = TransformLegacyDocument(data, out var requiredLegacyTransformations);

                if (requiredLegacyTransformations)
                {
                    // Save now to avoid transformations
                    var document = LoadDocument <TDocument>(filePath, mappings, data);
                    await document.SaveAsync();
                }

                if (applyTransformations)
                {
                    data = Regex.Replace(data, "%[A-Za-z0-9_]*?%", p => EscapeJsonString(Environment.ExpandEnvironmentVariables(p.Value)));

                    foreach (var p in ConvertVariables(variables))
                    {
                        data = data.Replace("$(" + p.Key + ")", EscapeJsonString(p.Value));
                    }

                    var obj = JObject.Parse(data);
                    if (obj["defaultVariables"] != null)
                    {
                        var defaultVariables = obj["defaultVariables"].Value <string>();
                        foreach (var p in ConvertVariables(defaultVariables))
                        {
                            data = data.Replace("$(" + p.Key + ")", EscapeJsonString(p.Value));
                        }
                    }
                }

                return LoadDocument <TDocument>(filePath, mappings, data);
            }));
        }
コード例 #8
0
        public static async Task <bool> TryWriteFileOutputAsync(this IOutputCommand command, string path, IConsoleHost host, Func <string> generator)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var directory = DynamicApis.PathGetDirectoryName(path);
                if (!string.IsNullOrEmpty(directory) && DynamicApis.DirectoryExists(directory) == false)
                {
                    DynamicApis.DirectoryCreateDirectory(directory);
                }

                var data = generator();
                if (!DynamicApis.FileExists(path) || DynamicApis.FileReadAllText(path) != data)
                {
                    DynamicApis.FileWriteAllText(path, data);
                    host?.WriteMessage("Code has been successfully written to file.\n");
                }
                else
                {
                    host?.WriteMessage("Code has been successfully generated but not written to file (no change detected).\n");
                }
                return(true);
            }
            return(false);
        }
コード例 #9
0
ファイル: JsonSchema4.cs プロジェクト: nickcox/NJsonSchema
        /// <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="jsonReferenceResolver">The JSON document resolver.</param>
        /// <returns>The JSON Schema.</returns>
        public static JsonSchema4 FromFile(string filePath, JsonReferenceResolver jsonReferenceResolver)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(FromJson(data, filePath, jsonReferenceResolver));
        }
コード例 #10
0
        /// <summary>Creates a JSON Schema from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The <see cref="JsonSchema" />.</returns>
        public static async Task <JsonSchema> FromFileAsync(string filePath, Func <JsonSchema, JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(await FromYamlAsync(data, filePath, referenceResolverFactory, cancellationToken).ConfigureAwait(false));
        }
コード例 #11
0
ファイル: SwaggerDocument.cs プロジェクト: threax/NSwag
        /// <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));
        }
コード例 #12
0
ファイル: JsonSchema.cs プロジェクト: john-larson/NJsonSchema
        /// <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 <JsonSchema> FromFileAsync(string filePath, Func <JsonSchema, JsonReferenceResolver> referenceResolverFactory)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(await FromJsonAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false));
        }
コード例 #13
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 FromJsonAsync(data, filePath).ConfigureAwait(false));
        }
コード例 #14
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 FromYamlAsync(data, filePath, cancellationToken).ConfigureAwait(false));
        }
コード例 #15
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>
        /// <returns>The JSON Schema.</returns>
        public static JsonSchema4 FromFile(string filePath)
        {
            var data = DynamicApis.FileReadAllText(filePath);

            return(FromJson(data, filePath));
        }