public DocumentModel(NSwagDocument document) { Document = document; SwaggerGeneratorViews = new ISwaggerGeneratorView[] { new SwaggerInputView(Document.SwaggerGenerators.FromSwaggerCommand), new WebApiToSwaggerGeneratorView((WebApiToSwaggerCommand)Document.SwaggerGenerators.WebApiToSwaggerCommand, document), new JsonSchemaInputView(Document.SwaggerGenerators.JsonSchemaToSwaggerCommand), new AssemblyTypeToSwaggerGeneratorView((AssemblyTypeToSwaggerCommand)Document.SwaggerGenerators.AssemblyTypeToSwaggerCommand, document), }; CodeGenerators = new CodeGeneratorViewBase[] { new SwaggerOutputView(), new SwaggerToTypeScriptClientGeneratorView(Document), new SwaggerToCSharpClientGeneratorView(Document), new SwaggerToCSharpControllerGeneratorView(Document) } .Select(v => new CodeGeneratorModel { View = v }) .ToList(); foreach (var codeGenerator in CodeGenerators) { codeGenerator.View.PropertyChanged += OnCodeGeneratorPropertyChanged; } RaisePropertyChanged(() => SwaggerGeneratorViews); RaisePropertyChanged(() => CodeGenerators); }
//[TestMethod] public async Task RunIntegrationTests() { //// Arrange foreach (var path in Directory.GetDirectories("../../../NSwag.Integration.Tests")) { try { var configPath = Path.GetFullPath(path + "/nswag.json"); var config = await NSwagDocument.LoadAsync(configPath); var outputPath = config.SwaggerGenerators.WebApiToSwaggerCommand.OutputFilePath; //// Act var command = "run \"" + configPath + "\""; var output = RunCommandLine(command, outputPath); var document = await SwaggerDocument.FromJsonAsync(output); //// Assert Assert.IsTrue(document.Paths.Any()); Debug.WriteLine("The integration test '" + Path.GetFileName(path) + "' passed!"); } catch (Exception e) { throw new Exception("The integration test '" + Path.GetFileName(path) + "' failed: " + e); } } }
private async Task ExecuteDocumentAsync(IConsoleHost host, string filePath) { host.WriteMessage("\nExecuting file '" + filePath + "' with variables '" + Variables + "'...\n"); var document = await NSwagDocument.LoadWithTransformationsAsync(filePath, Variables); if (document.Runtime != Runtime.Default) { if (document.Runtime != RuntimeUtilities.CurrentRuntime) { throw new InvalidOperationException("The specified runtime in the document (" + document.Runtime + ") differs " + "from the current process runtime (" + RuntimeUtilities.CurrentRuntime + "). " + "Change the runtime with the '/runtime:" + document.Runtime + "' parameter " + "or run the file with the correct command line binary."); } if (document.SelectedSwaggerGenerator == document.SwaggerGenerators.WebApiToOpenApiCommand && document.SwaggerGenerators.WebApiToOpenApiCommand.IsAspNetCore == false && document.Runtime != Runtime.Debug && document.Runtime != Runtime.WinX86 && document.Runtime != Runtime.WinX64) { throw new InvalidOperationException("The runtime " + document.Runtime + " in the document must be used " + "with ASP.NET Core. Enable /isAspNetCore:true."); } } await document.ExecuteAsync(); host.WriteMessage("Done.\n"); }
private NSwagDocument LoadDocument(string filePath) { var document = NSwagDocument.LoadDocument(filePath); Documents.Add(document); return(document); }
/// <summary>Creates a new document in the given path.</summary> /// <param name="filePath">The file path.</param> /// <returns>The task.</returns> protected override async Task CreateDocumentAsync(string filePath) { var document = new NSwagDocument(); document.Path = filePath; await document.SaveAsync(); }
private bool SaveDocument(NSwagDocument document) { try { if (File.Exists(document.Path)) { document.Save(); MessageBox.Show("The file has been saved.", "File saved"); return(true); } else { if (SaveAsDocument(document)) { return(true); } } } catch (Exception exception) { MessageBox.Show("File save failed: \n" + exception.Message, "Could not save the settings"); } return(false); }
public async Task <bool> CloseDocumentAsync(NSwagDocument document) { if (document.IsDirty) { var result = MessageBox.Show("Do you want to save the file " + document.Name + " ?", "Save file", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) { var success = await SaveDocumentAsync(document); if (!success) { return(false); } } else if (result == DialogResult.Cancel) { return(false); } } Documents.Remove(document); return(true); }
private void CreateDocument() { var document = NSwagDocument.CreateDocument(); Documents.Add(document); SelectedDocument = document; }
private async Task <string> GenerateNswagFileAsync(ConnectedServiceHandlerContext context, Instance instance) { var nameSpace = context.ProjectHierarchy.GetProject().GetNameSpace(); var serviceUrl = instance.ServiceUri; var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder(); var serviceFolder = instance.Name; var document = NSwagDocument.Create(); document.CodeGenerators.SwaggerToCSharpClientCommand = new SwaggerToCSharpClientCommand { OutputFilePath = $"{serviceFolder}Client.Generated.cs", ClassName = "{controller}Client", Namespace = $"{nameSpace}.{serviceFolder}" }; document.SelectedSwaggerGenerator = new FromSwaggerCommand { OutputFilePath = $"{serviceFolder}.nswag.json", Url = serviceUrl }; var json = document.ToJson(); var tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, json); var targetPath = Path.Combine(rootFolder, serviceFolder, $"{serviceFolder}.nswag"); var nswagFilePath = await context.HandlerHelper.AddFileAsync(tempFileName, targetPath); return(nswagFilePath); }
private void CreateDocument() { var document = new DocumentModel(NSwagDocument.Create()); Documents.Add(document); SelectedDocument = document; }
public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { if (!string.IsNullOrEmpty(File)) { var document = await NSwagDocument.LoadWithTransformationsAsync(File, Variables); var command = (TypesToSwaggerCommand)document.SelectedSwaggerGenerator; AssemblyPaths = command.AssemblyPaths; AssemblyConfig = command.AssemblyConfig; ReferencePaths = command.ReferencePaths; } var classNames = await RunIsolatedAsync(!string.IsNullOrEmpty(File)?Path.GetDirectoryName(File) : null); host.WriteMessage("\r\n"); foreach (var className in classNames) { host.WriteMessage(className + "\r\n"); } host.WriteMessage("\r\n"); return(classNames); }
public SwaggerToTypeScriptClientGeneratorView(NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); _document = document; Model.Command = document.CodeGenerators.SwaggerToTypeScriptClientCommand; }
public SwaggerToCSharpControllerGeneratorView(NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); _document = document; Model.Command = document.CodeGenerators.SwaggerToCSharpControllerCommand; }
public AspNetCoreToSwaggerGeneratorView(AspNetCoreToSwaggerCommand command, NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); Model.Command = command; Model.Document = document; }
private async Task CreateDocumentAsync(string filePath) { var document = new NSwagDocument(); document.Path = filePath; document.CodeGenerators.SwaggerToCSharpControllerCommand = new SwaggerToCSharpControllerCommand(); document.CodeGenerators.SwaggerToCSharpClientCommand = new SwaggerToCSharpClientCommand(); document.CodeGenerators.SwaggerToTypeScriptClientCommand = new SwaggerToTypeScriptClientCommand(); await document.SaveAsync(); }
private async Task <string> ReGenerateCSharpFileAsync(ConnectedServiceHandlerContext context, Instance instance) { var serviceFolder = instance.Name; var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder(); var folderPath = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder); var nswagFilePath = Path.Combine(folderPath, $"{serviceFolder}.nswag"); var document = await NSwagDocument.LoadAsync(nswagFilePath); await document.ExecuteAsync(); return(nswagFilePath); }
public AssemblyTypeToSwaggerGeneratorView(TypesToSwaggerCommand command, NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); Model.Command = command; Model.Document = document; ControllersList.SelectedItems.Clear(); foreach (var controller in Model.ClassNames) { ControllersList.SelectedItems.Add(controller); } }
public SwaggerInputView(NSwagDocument document) { InitializeComponent(); var hasInputSwaggerUrl = !string.IsNullOrEmpty(document.InputSwaggerUrl); if (hasInputSwaggerUrl) document.InputSwagger = string.Empty; Model.Document = document; Model.RaiseAllPropertiesChanged(); if (hasInputSwaggerUrl) Model.LoadSwaggerUrlAsync(); }
internal async Task <string> ReGenerateCSharpFileAsync(ConnectedServiceHandlerContext context, Instance instance) { var serviceFolder = instance.Name; var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder(); var folderPath = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder); var nswagFilePath = Path.Combine(folderPath, $"{serviceFolder}.nswag"); var document = await NSwagDocument.LoadWithTransformationsAsync(nswagFilePath, instance.ServiceConfig.Variables); document.Runtime = instance.ServiceConfig.Runtime; await document.ExecuteAsync(); return(document.SelectedSwaggerGenerator.OutputFilePath); }
private bool SaveAsDocument(NSwagDocument document) { var dlg = new SaveFileDialog(); dlg.Filter = "NSwag settings (*.nswag)|*.nswag"; dlg.RestoreDirectory = true; dlg.AddExtension = true; if (dlg.ShowDialog() == DialogResult.OK) { document.Path = dlg.FileName; document.Save(); return(true); } return(false); }
protected override byte[] GenerateCode(string inputFileName, string inputFileContent) { var generationReport = new StringBuilder() .AppendLine($"Code Generation Report - {DateTime.Now}") .Append(Environment.NewLine); try { var document = ThreadHelper.JoinableTaskFactory.Run(() => NSwagDocument.LoadAsync(inputFileName)); ThreadHelper.JoinableTaskFactory.Run(() => document.ExecuteAsync()); generationReport = generationReport.AppendLine( $"- C# client: {document.CodeGenerators.OpenApiToCSharpClientCommand?.OutputFilePath ?? "not selected"}") .AppendLine( $"- TS client: {document.CodeGenerators.OpenApiToTypeScriptClientCommand?.OutputFilePath ?? "not selected"}") .AppendLine( $"- C# controllers: {document.CodeGenerators.OpenApiToCSharpControllerCommand?.OutputFilePath ?? "not selected"}") .Append(Environment.NewLine); } catch (Exception exception) { generationReport = generationReport .AppendLine($"Generation failed: {exception.Message}") .Append(Environment.NewLine) .AppendLine("Error details:") .AppendLine(exception.ToString()) .Append(Environment.NewLine); } generationReport = generationReport .AppendLine("Tips & Tricks:").Append(Environment.NewLine) .AppendLine($"- Use {Constants.NSwagStudioName} - a Windows desktop app for configuring .{Constants.NswagExt} settings visually.") .AppendLine($" {Constants.NSwagStudioLink}") .AppendLine($"- Configure Visual Studio to automatically open .{Constants.NswagExt} files in {Constants.NSwagStudioName}: in right click on .{Constants.NswagExt} file in Solution Explorer -> Open With... -> Add -> extension to {Constants.NSwagStudioName} app.") .AppendLine($"- To regenerate code quickly just select .{Constants.NswagExt} file and press CTRL+S.") .AppendLine($"- If code is not generated check .{Constants.NswagExt} file `Custom Tool` in Property Window. There is should be `{Name}`. You can just add it manually or select `Generate API Client` in context menu.") .AppendLine($" {Constants.NSwagStudioLink}").Append(Environment.NewLine); generationReport = generationReport .AppendLine("Support Development:").Append(Environment.NewLine) .AppendLine($"- Note a lovely `Sponsor` button with available options at the top of this page {Constants.ProductGitHib}. Your support is much appreciated!") .AppendLine($"- Please provide feedback on {Constants.ProductName} extension by raising new issue here {Constants.ProductGitHib}/issues"); // # Support Development // Note a lovely :heart: `Sponsor` button with available options at the top of this page. Your support is much appreciated! return(Encoding.UTF8.GetBytes(generationReport.ToString())); }
public async Task OpenDocumentAsync(string filePath) { await RunTaskAsync(async() => { var currentDocument = Documents.SingleOrDefault(d => d.Document.Path == filePath); if (currentDocument != null) { SelectedDocument = currentDocument; } else { var document = new DocumentModel(await NSwagDocument.LoadAsync(filePath)); Documents.Add(document); SelectedDocument = document; } }); }
private void LoadGeneratoers(NSwagDocument document) { SwaggerGenerators = new ISwaggerGenerator[] { new SwaggerInputGeneratorView(Document), new WebApiSwaggerGeneratorView(Document.WebApiToSwaggerCommand), new JsonSchemaInputGeneratorView(Document), new AssemblySwaggerGeneratorView(Document.AssemblyTypeToSwaggerCommand), }; ClientGenerators = new IClientGenerator[] { new SwaggerGeneratorView(), new TypeScriptCodeGeneratorView(Document.SwaggerToTypeScriptCommand), new CSharpClientGeneratorView(Document.SwaggerToCSharpCommand) }; RaisePropertyChanged(() => SwaggerGenerators); RaisePropertyChanged(() => ClientGenerators); }
public void OpenDocument(string filePath) { try { var currentDocument = Documents.SingleOrDefault(d => d.Path == filePath); if (currentDocument != null) { SelectedDocument = currentDocument; } else { var document = NSwagDocument.LoadDocument(filePath); Documents.Add(document); SelectedDocument = document; } } catch (Exception exception) { MessageBox.Show("File open failed: \n" + exception.Message, "Could not load the settings"); } }
private bool SaveAsDocument(NSwagDocument document) { var dlg = new SaveFileDialog(); dlg.Filter = "NSwag settings (*.nswag)|*.nswag"; dlg.RestoreDirectory = true; dlg.AddExtension = true; if (dlg.ShowDialog() == DialogResult.OK) { document.Path = dlg.FileName; document.Save(); return true; } return false; }
private bool SaveDocument(NSwagDocument document) { try { if (File.Exists(document.Path)) { document.Save(); MessageBox.Show("The file has been saved.", "File saved"); return true; } else { if (SaveAsDocument(document)) return true; } } catch (Exception exception) { MessageBox.Show("File save failed: \n" + exception.Message, "Could not save the settings"); } return false; }
public bool CloseDocument(NSwagDocument document) { if (document.IsDirty) { var result = MessageBox.Show("Do you want to save the file " + document.Name + " ?", "Save file", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) { var success = SaveDocument(document); if (!success) return false; } else if (result == DialogResult.Cancel) return false; } Documents.Remove(document); return true; }
internal async Task <string> GenerateNswagFileAsync(ConnectedServiceHandlerContext context, Instance instance) { var nameSpace = context.ProjectHierarchy.GetProject().GetNameSpace(); var serviceUrl = instance.ServiceConfig.Endpoint; if (string.IsNullOrWhiteSpace(instance.Name)) { instance.Name = Constants.DefaultServiceName; } var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder(); var serviceFolder = instance.Name; var document = NSwagDocument.Create(); if (instance.ServiceConfig.GenerateCSharpClient) { instance.ServiceConfig.OpenApiToCSharpClientCommand.OutputFilePath = $"{serviceFolder}Client.Generated.cs"; if (string.IsNullOrWhiteSpace(instance.ServiceConfig.OpenApiToCSharpClientCommand.Namespace)) { instance.ServiceConfig.OpenApiToCSharpClientCommand.Namespace = $"{nameSpace}.{serviceFolder}"; } document.CodeGenerators.OpenApiToCSharpClientCommand = instance.ServiceConfig.OpenApiToCSharpClientCommand; } if (instance.ServiceConfig.GenerateTypeScriptClient) { instance.ServiceConfig.OpenApiToTypeScriptClientCommand.OutputFilePath = $"{serviceFolder}Client.Generated.ts"; document.CodeGenerators.OpenApiToTypeScriptClientCommand = instance.ServiceConfig.OpenApiToTypeScriptClientCommand; } if (instance.ServiceConfig.GenerateCSharpController) { instance.ServiceConfig.OpenApiToCSharpControllerCommand.OutputFilePath = $"{serviceFolder}Controller.Generated.cs"; if (string.IsNullOrWhiteSpace(instance.ServiceConfig.OpenApiToCSharpControllerCommand.Namespace)) { instance.ServiceConfig.OpenApiToCSharpControllerCommand.Namespace = $"{nameSpace}.{serviceFolder}"; } document.CodeGenerators.OpenApiToCSharpControllerCommand = instance.ServiceConfig.OpenApiToCSharpControllerCommand; } document.SelectedSwaggerGenerator = new FromDocumentCommand { OutputFilePath = $"{serviceFolder}.nswag.json", Url = serviceUrl, Json = instance.ServiceConfig.CopySpecification ? File.ReadAllText(instance.SpecificationTempPath) : null }; var json = document.ToJson(); var tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, json); var targetPath = Path.Combine(rootFolder, serviceFolder, $"{serviceFolder}.nswag"); var nswagFilePath = await context.HandlerHelper.AddFileAsync(tempFileName, targetPath); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } if (File.Exists(instance.SpecificationTempPath)) { File.Delete(instance.SpecificationTempPath); } return(nswagFilePath); }
internal async Task <string> GenerateCodeAsync(ConnectedServiceHandlerContext context, Instance instance) { var serviceFolder = instance.Name; var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder(); var folderPath = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder); var nswagFilePath = Path.Combine(folderPath, $"{serviceFolder}.nswag"); var document = await NSwagDocument.LoadWithTransformationsAsync(nswagFilePath, instance.ServiceConfig.Variables); document.Runtime = instance.ServiceConfig.Runtime; var nswagJsonTempFileName = Path.GetTempFileName(); var csharpClientTempFileName = Path.GetTempFileName(); var typeScriptClientTempFileName = Path.GetTempFileName(); var controllerTempFileName = Path.GetTempFileName(); var nswagJsonOutputPath = document.SelectedSwaggerGenerator.OutputFilePath; try { var csharpClientOutputPath = document.CodeGenerators?.OpenApiToCSharpClientCommand?.OutputFilePath; var typeScriptClientOutputPath = document.CodeGenerators?.OpenApiToTypeScriptClientCommand?.OutputFilePath; var controllerOutputPath = document.CodeGenerators?.OpenApiToCSharpControllerCommand?.OutputFilePath; document.SelectedSwaggerGenerator.OutputFilePath = nswagJsonTempFileName; if (document.CodeGenerators?.OpenApiToCSharpClientCommand != null) { document.CodeGenerators.OpenApiToCSharpClientCommand.OutputFilePath = csharpClientTempFileName; } if (document.CodeGenerators?.OpenApiToTypeScriptClientCommand != null) { document.CodeGenerators.OpenApiToTypeScriptClientCommand.OutputFilePath = typeScriptClientTempFileName; } if (document.CodeGenerators?.OpenApiToCSharpControllerCommand != null) { document.CodeGenerators.OpenApiToCSharpControllerCommand.OutputFilePath = controllerTempFileName; } await document.ExecuteAsync(); nswagJsonOutputPath = await context.HandlerHelper.AddFileAsync(nswagJsonTempFileName, nswagJsonOutputPath, new AddFileOptions { OpenOnComplete = instance.ServiceConfig.OpenGeneratedFilesOnComplete }); if (document.CodeGenerators?.OpenApiToCSharpClientCommand != null) { await context.HandlerHelper.AddFileAsync(csharpClientTempFileName, csharpClientOutputPath, new AddFileOptions { OpenOnComplete = instance.ServiceConfig.OpenGeneratedFilesOnComplete }); } if (document.CodeGenerators?.OpenApiToTypeScriptClientCommand != null) { await context.HandlerHelper.AddFileAsync(typeScriptClientTempFileName, typeScriptClientOutputPath, new AddFileOptions { OpenOnComplete = instance.ServiceConfig.OpenGeneratedFilesOnComplete }); } if (document.CodeGenerators?.OpenApiToCSharpControllerCommand != null) { await context.HandlerHelper.AddFileAsync(controllerTempFileName, controllerOutputPath, new AddFileOptions { OpenOnComplete = instance.ServiceConfig.OpenGeneratedFilesOnComplete }); } } catch (Exception ex) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, $"Error: {ex.Message}."); } finally { if (File.Exists(nswagJsonTempFileName)) { File.Delete(nswagJsonTempFileName); } if (File.Exists(csharpClientTempFileName)) { File.Delete(csharpClientTempFileName); } if (File.Exists(typeScriptClientTempFileName)) { File.Delete(typeScriptClientTempFileName); } if (File.Exists(controllerTempFileName)) { File.Delete(controllerTempFileName); } } return(nswagJsonOutputPath); }
public JsonSchemaInputView(NSwagDocument document) { InitializeComponent(); DataContext = document; }
/// <summary>Loads an existing NSwagDocument.</summary> /// <param name="filePath">The file path.</param> /// <returns>The document.</returns> protected override async Task <NSwagDocumentBase> LoadDocumentAsync(string filePath) { return(await NSwagDocument.LoadAsync(filePath)); }
public JsonSchemaInputGeneratorView(NSwagDocument document) { InitializeComponent(); DataContext = document; }
public SwaggerInputGeneratorView(NSwagDocument document) { InitializeComponent(); DataContext = document; }
public DocumentModel(NSwagDocument document) { Document = document; LoadGenerators(); }