Example #1
0
        public async Task Generate(
            ProgressMonitor monitor,
            ProjectFile file,
            SingleFileCustomToolResult result)
        {
            Bootstrapper.Initialize();

            using var traceListener = new DisposableTraceListener(
                      new LoggingServiceTraceListener(
                          new ProgressMonitorLoggingService(monitor, "Generating code...")));

            var swaggerFile = file.FilePath;
            var outputFile  = swaggerFile.ChangeExtension(".cs");

            result.GeneratedFilePath = outputFile;

            var customToolNamespace = file.CustomToolNamespace;

            if (string.IsNullOrWhiteSpace(customToolNamespace))
            {
                customToolNamespace = CustomToolService.GetFileNamespace(file, outputFile);
            }

            var generator        = GetCodeGenerator(swaggerFile, customToolNamespace);
            var progressReporter = new ProgressReporter(monitor);
            var contents         = await Task.Run(() => generator.GenerateCode(progressReporter));

            await Task.Run(() => File.WriteAllText(outputFile, contents));
        }
        protected async override void Run()
        {
            var wob = IdeApp.ProjectOperations.CurrentSelectedItem;

            if (wob is ProjectFile pf)
            {
                await CustomToolService.UpdateAsync(pf, pf.Project, true);

                return;
            }

            IEnumerable <ProjectFile> files;

            if (wob is Solution solution)
            {
                files = solution.GetAllProjects().SelectMany(GetFilesToUpdate);
            }
            else if (wob is Project proj)
            {
                files = GetFilesToUpdate(proj);
            }
            else
            {
                return;
            }

            await CustomToolService.Update(files, true);
        }
        protected async override void Run()
        {
            var wob = IdeApp.ProjectOperations.CurrentSelectedItem;

            var pf = wob as ProjectFile;

            if (pf != null)
            {
                CustomToolService.Update(pf, pf.Project, true);
                return;
            }

            IEnumerable <ProjectFile> files;

            var solution = wob as Solution;

            if (solution != null)
            {
                files = solution.GetAllProjects().SelectMany(GetFilesToUpdate);
            }
            else if (wob is Project)
            {
                files = GetFilesToUpdate((Project)wob);
            }
            else
            {
                return;
            }

            await CustomToolService.Update(files, true);
        }
Example #4
0
        static void GenerateInternal(IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result)
        {
            if (file.Project.SupportedLanguages.All(l => l != "C#"))
            {
                const string msg = "Razor templates are only supported in C# projects";
                result.Errors.Add(new CompilerError(file.Name, -1, -1, null, msg));
                monitor.Log.WriteLine(msg);
                return;
            }

            var host = new PreprocessedRazorHost(file.FilePath);

            var defaultOutputName = file.FilePath.ChangeExtension(".cs");

            var ns = CustomToolService.GetFileNamespace(file, defaultOutputName);

            host.DefaultNamespace = ns;

            CompilerErrorCollection errors;
            var code = host.GenerateCode(out errors);

            result.Errors.AddRange(errors);

            var writer = new MonoDevelop.DesignerSupport.CodeBehindWriter();

            writer.WriteFile(defaultOutputName, code);
            writer.WriteOpenFiles();

            result.GeneratedFilePath = defaultOutputName;

            foreach (var err in result.Errors)
            {
                monitor.Log.WriteLine(err);
            }
        }
        static void Generate(TemplateGenerator host, ProjectFile file, out string outputFile)
        {
            outputFile = null;

            string content;

            try {
                content = File.ReadAllText(file.FilePath);
            }
            catch (IOException ex) {
                host.Errors.Add(new CompilerError {
                    ErrorText = GettextCatalog.GetString("Could not read input file '{0}':\n{1}", file.FilePath, ex)
                });
                return;
            }

            var pt = ParsedTemplate.FromText(content, host);

            if (pt.Errors.HasErrors)
            {
                host.Errors.AddRange(pt.Errors);
                return;
            }

            var settings = TemplatingEngine.GetSettings(host, pt);

            if (pt.Errors.HasErrors)
            {
                host.Errors.AddRange(pt.Errors);
                return;
            }

            outputFile         = file.FilePath.ChangeExtension(settings.Provider.FileExtension);
            settings.Name      = settings.Provider.CreateValidIdentifier(file.FilePath.FileNameWithoutExtension);
            settings.Namespace = CustomToolService.GetFileNamespace(file, outputFile);
            settings.IncludePreprocessingHelpers = string.IsNullOrEmpty(settings.Inherits);
            settings.IsPreprocessed = true;

            var ccu = TemplatingEngine.GenerateCompileUnit(host, content, pt, settings);

            host.Errors.AddRange(pt.Errors);
            if (pt.Errors.HasErrors)
            {
                return;
            }

            try {
                using (var writer = new StreamWriter(outputFile, false, System.Text.Encoding.UTF8)) {
                    settings.Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
                }
            }
            catch (IOException ex) {
                host.Errors.Add(new CompilerError {
                    ErrorText = GettextCatalog.GetString("Could not write output file '{0}':\n{1}", outputFile, ex)
                });
            }
        }
        protected override void Run()
        {
            var file = IdeApp.ProjectOperations.CurrentSelectedItem as ProjectFile;

            if (CustomToolServiceExtensions.ShouldRunCustomTool(file))
            {
                CustomToolService.Update(file, file.Project, true);
            }
        }
        public async Task Generate(
            ProgressMonitor monitor,
            ProjectFile file,
            SingleFileCustomToolResult result)
        {
            string generatorName;

            if (GetType() == typeof(OpenApiSingleFileCustomTool))
            {
                generatorName = "OpenAPI Generator";
            }
            else if (GetType() == typeof(SwaggerSingleFileCustomTool))
            {
                generatorName = "Swagger Codegen CLI";
            }
            else
            {
                generatorName = GetType().Name.Replace("SingleFileCustomTool", string.Empty);
            }

            Logger.Instance.TrackFeatureUsage(generatorName, "VSMac");

            Bootstrapper.Initialize();

            var swaggerFile = file.FilePath;
            var outputFile  = swaggerFile.ChangeExtension(".cs");

            result.GeneratedFilePath = outputFile;

            using var traceListener = new DisposableTraceListener(
                      new LoggingServiceTraceListener(
                          new ProgressMonitorLoggingService(monitor, "Generating code...")));

            var customToolNamespace = file.CustomToolNamespace;

            if (string.IsNullOrWhiteSpace(customToolNamespace))
            {
                customToolNamespace = CustomToolService.GetFileNamespace(file, outputFile);
            }

            var generator        = GetCodeGenerator(swaggerFile, customToolNamespace);
            var progressReporter = new ProgressReporter(monitor);
            var contents         = await Task.Run(() => generator.GenerateCode(progressReporter));

            await Task.Run(() => File.WriteAllText(outputFile, contents));
        }
        public IAsyncOperation Generate(IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result)
        {
            return(new ThreadAsyncOperation(delegate {
                var host = new ProjectFileTemplatingHost(file);

                var dnp = file.Project as DotNetProject;
                if (dnp == null)
                {
                    var msg = "Precompiled T4 templates are only supported in .NET projects";
                    result.Errors.Add(new CompilerError(file.Name, -1, -1, null, msg));
                    monitor.Log.WriteLine(msg);
                    return;
                }

                var provider = dnp.LanguageBinding.GetCodeDomProvider();
                if (provider == null)
                {
                    var msg = "Precompiled T4 templates are only supported for .NET languages with CodeDOM providers";
                    result.Errors.Add(new CompilerError(file.Name, -1, -1, null, msg));
                    monitor.Log.WriteLine(msg);
                    return;
                }
                ;

                var outputFile = file.FilePath.ChangeExtension(provider.FileExtension);
                var encoding = System.Text.Encoding.UTF8;
                string langauge;
                string[] references;
                string className = provider.CreateValidIdentifier(file.FilePath.FileNameWithoutExtension);

                string classNamespace = CustomToolService.GetFileNamespace(file, outputFile);
                LogicalSetData("NamespaceHint", classNamespace, result.Errors);

                host.PreprocessTemplate(file.FilePath, className, classNamespace, outputFile, encoding, out langauge, out references);

                result.GeneratedFilePath = outputFile;
                result.Errors.AddRange(host.Errors);
                foreach (var err in host.Errors)
                {
                    monitor.Log.WriteLine(err.ToString());
                }
            }, result));
        }
Example #9
0
        public Task Generate(ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result)
        {
            return(Task.Run(delegate {
                using (var host = new ProjectFileTemplatingHost(file, IdeApp.Workspace.ActiveConfiguration)) {
                    host.AddMonoDevelopHostImport();
                    var defaultOutputName = file.FilePath.ChangeExtension(".cs");                      //cs extension for VS compat

                    string ns = CustomToolService.GetFileNamespace(file, defaultOutputName);
                    LogicalSetData("NamespaceHint", ns);

                    host.ProcessTemplate(file.FilePath, defaultOutputName);
                    result.GeneratedFilePath = host.OutputFile;
                    result.Errors.AddRange(host.Errors);

                    foreach (var err in host.Errors)
                    {
                        monitor.Log.WriteLine(err);
                    }
                }
            }));
        }
Example #10
0
        public IAsyncOperation Generate(IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result)
        {
            return(new ThreadAsyncOperation(delegate {
                using (var host = new ProjectFileTemplatingHost(file)) {
                    host.AddMonoDevelopHostImport();
                    var defaultOutputName = file.FilePath.ChangeExtension(".cs");                      //cs extension for VS compat

                    string ns = CustomToolService.GetFileNamespace(file, defaultOutputName);
                    TextTemplatingFilePreprocessor.LogicalSetData("NamespaceHint", ns, result.Errors);

                    host.ProcessTemplate(file.FilePath, defaultOutputName);
                    result.GeneratedFilePath = host.OutputFile;
                    result.Errors.AddRange(host.Errors);

                    foreach (var err in host.Errors)
                    {
                        monitor.Log.WriteLine(err);
                    }
                }
            }, result));
        }
        public static async Task Update(IEnumerable <ProjectFile> files, bool force = true)
        {
            if (updateMethod == null)
            {
                await CustomToolService.Update(files, force);

                return;
            }

            IEnumerator <ProjectFile> fileEnumerator;

            var progressMonitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor(false, null);

            if (files == null || !(fileEnumerator = files.GetEnumerator()).MoveNext())
            {
                progressMonitor.ReportSuccess(GettextCatalog.GetString("No custom tools found"));
                progressMonitor.Dispose();
            }
            else
            {
                progressMonitor.BeginTask(GettextCatalog.GetString("Running custom tools"), 1);
                await Update(progressMonitor, fileEnumerator, force);
            }
        }
Example #12
0
        public static void Initialize(IProgressMonitor monitor)
        {
            Counters.Initialization.Trace("Creating Workbench");
            workbench = new Workbench();
            Counters.Initialization.Trace("Creating Root Workspace");
            workspace = new RootWorkspace();
            Counters.Initialization.Trace("Creating Services");
            projectOperations = new ProjectOperations();
            helpOperations    = new HelpOperations();
            commandService    = new CommandManager();
            ideServices       = new IdeServices();
            CustomToolService.Init();
            AutoTestService.Start(commandService, Preferences.EnableAutomatedTesting);

            commandService.CommandTargetScanStarted  += CommandServiceCommandTargetScanStarted;
            commandService.CommandTargetScanFinished += CommandServiceCommandTargetScanFinished;
            commandService.KeyBindingFailed          += KeyBindingFailed;

            KeyBindingService.LoadBindingsFromExtensionPath("/MonoDevelop/Ide/KeyBindingSchemes");
            KeyBindingService.LoadCurrentBindings("MD2");

            commandService.CommandError += delegate(object sender, CommandErrorArgs args) {
                LoggingService.LogInternalError(args.ErrorMessage, args.Exception);
            };

            FileService.ErrorHandler = FileServiceErrorHandler;

            monitor.BeginTask(GettextCatalog.GetString("Loading Workbench"), 5);
            Counters.Initialization.Trace("Loading Commands");

            commandService.LoadCommands("/MonoDevelop/Ide/Commands");
            monitor.Step(1);

            Counters.Initialization.Trace("Initializing Workbench");
            workbench.Initialize(monitor);
            monitor.Step(1);

            InternalLog.EnableErrorNotification();

            MonoDevelop.Ide.WelcomePage.WelcomePageService.Initialize();
            MonoDevelop.Ide.WelcomePage.WelcomePageService.ShowWelcomePage();

            monitor.Step(1);

            Counters.Initialization.Trace("Restoring Workbench State");
            workbench.Show("SharpDevelop.Workbench.WorkbenchMemento");
            monitor.Step(1);

            Counters.Initialization.Trace("Flushing GUI events");
            DispatchService.RunPendingEvents();
            Counters.Initialization.Trace("Flushed GUI events");

            MessageService.RootWindow = workbench.RootWindow;

            commandService.EnableIdleUpdate = true;

            // Perser service initialization
            TypeSystemService.TrackFileChanges            = true;
            TypeSystemService.ParseProgressMonitorFactory = new ParseProgressMonitorFactory();

            Customizer.OnIdeInitialized();

            // Startup commands
            Counters.Initialization.Trace("Running Startup Commands");
            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/StartupHandlers", OnExtensionChanged);
            monitor.Step(1);
            monitor.EndTask();

            // Set initial run flags
            Counters.Initialization.Trace("Upgrading Settings");

            if (PropertyService.Get("MonoDevelop.Core.FirstRun", false))
            {
                isInitialRun = true;
                PropertyService.Set("MonoDevelop.Core.FirstRun", false);
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", BuildInfo.Version);
                PropertyService.Set("MonoDevelop.Core.LastRunRevision", CurrentRevision);
                PropertyService.SaveProperties();
            }

            string lastVersion  = PropertyService.Get("MonoDevelop.Core.LastRunVersion", "1.9.1");
            int    lastRevision = PropertyService.Get("MonoDevelop.Core.LastRunRevision", 0);

            if (lastRevision != CurrentRevision && !isInitialRun)
            {
                isInitialRunAfterUpgrade = true;
                if (lastRevision == 0)
                {
                    switch (lastVersion)
                    {
                    case "1.0": lastRevision = 1; break;

                    case "2.0": lastRevision = 2; break;

                    case "2.2": lastRevision = 3; break;

                    case "2.2.1": lastRevision = 4; break;
                    }
                }
                upgradedFromRevision = lastRevision;
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", BuildInfo.Version);
                PropertyService.Set("MonoDevelop.Core.LastRunRevision", CurrentRevision);
                PropertyService.SaveProperties();
            }

            // The ide is now initialized

            isInitialized = true;

            if (isInitialRun)
            {
                try {
                    OnInitialRun();
                } catch (Exception e) {
                    LoggingService.LogError("Error found while initializing the IDE", e);
                }
            }

            if (isInitialRunAfterUpgrade)
            {
                try {
                    OnUpgraded(upgradedFromRevision);
                } catch (Exception e) {
                    LoggingService.LogError("Error found while initializing the IDE", e);
                }
            }

            if (initializedEvent != null)
            {
                initializedEvent(null, EventArgs.Empty);
                initializedEvent = null;
            }

            //FIXME: we should really make this on-demand. consumers can display a "loading help cache" message like VS
            MonoDevelop.Projects.HelpService.AsyncInitialize();

            UpdateInstrumentationIcon();
            IdeApp.Preferences.EnableInstrumentationChanged += delegate {
                UpdateInstrumentationIcon();
            };
            AutoTestService.NotifyEvent("MonoDevelop.Ide.IdeStart");
        }
Example #13
0
        public static async Task Initialize(ProgressMonitor monitor)
        {
            // Already done in IdeSetup, but called again since unit tests don't use IdeSetup.
            DispatchService.Initialize();

            // Set initial run flags
            Counters.Initialization.Trace("Upgrading Settings");

            if (PropertyService.Get("MonoDevelop.Core.FirstRun", true))
            {
                isInitialRun = true;
                PropertyService.Set("MonoDevelop.Core.FirstRun", false);
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", Runtime.Version.ToString());
                PropertyService.SaveProperties();
            }

            string lastVersionString = PropertyService.Get("MonoDevelop.Core.LastRunVersion", "1.0");

            Version.TryParse(lastVersionString, out var lastVersion);

            if (Runtime.Version > lastVersion && !isInitialRun)
            {
                isInitialRunAfterUpgrade = true;
                upgradedFromVersion      = lastVersion;
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", Runtime.Version.ToString());
                PropertyService.SaveProperties();
            }

            Counters.Initialization.Trace("Initializing WelcomePage service");
            WelcomePage.WelcomePageService.Initialize().Ignore();

            Counters.Initialization.Trace("Creating Services");

            var serviceInitialization = Task.WhenAll(
                Runtime.GetService <DesktopService> (),
                Runtime.GetService <FontService> (),
                Runtime.GetService <TaskService> (),
                Runtime.GetService <ProjectOperations> (),
                Runtime.GetService <TextEditorService> (),
                Runtime.GetService <NavigationHistoryService> (),
                Runtime.GetService <DisplayBindingService> (),
                Runtime.GetService <RootWorkspace> (),
                Runtime.GetService <HelpOperations> (),
                Runtime.GetService <HelpService> ()
                );

            commandService = await Runtime.GetService <CommandManager> ();

            await serviceInitialization;

            Counters.Initialization.Trace("Creating Workbench");
            workbench = new Workbench();

            Counters.Initialization.Trace("Creating Root Workspace");

            CustomToolService.Init();

            FileService.ErrorHandler = FileServiceErrorHandler;

            monitor.BeginTask(GettextCatalog.GetString("Loading Workbench"), 3);

            // Before startup commands.
            Counters.Initialization.Trace("Running Pre-Startup Commands");
            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/PreStartupHandlers", OnExtensionChanged);
            monitor.Step(1);

            Counters.Initialization.Trace("Initializing Workbench");
            await workbench.Initialize(monitor);

            monitor.Step(1);

            Counters.Initialization.Trace("Realizing Workbench Window");
            workbench.Realize();
            monitor.Step(1);

            MessageService.RootWindow    = workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(workbench.RootWindow);

            commandService.EnableIdleUpdate = true;

            if (Customizer != null)
            {
                Customizer.OnIdeInitialized();
            }

            monitor.EndTask();

            UpdateInstrumentationIcon();
            IdeApp.Preferences.EnableInstrumentation.Changed += delegate {
                UpdateInstrumentationIcon();
            };
            AutoTestService.Start(commandService, Preferences.EnableAutomatedTesting);
            AutoTestService.NotifyEvent("MonoDevelop.Ide.IdeStart");

            Gtk.LinkButton.SetUriHook((button, uri) => Xwt.Desktop.OpenUrl(uri));

            // Start initializing the type system service in the background
            Runtime.GetService <TypeSystemService> ().Ignore();

            // The ide is now initialized
            OnInitialized();
        }
Example #14
0
        internal static void Initialize(ProgressMonitor monitor, bool hideWelcomePage)
        {
            // Already done in IdeSetup, but called again since unit tests don't use IdeSetup.
            DispatchService.Initialize();

            Counters.Initialization.Trace("Creating Workbench");
            workbench = new Workbench();

            Counters.Initialization.Trace("Creating Root Workspace");
            workspace = new RootWorkspace();
            Counters.Initialization.Trace("Creating Services");
            projectOperations = new ProjectOperations();
            helpOperations    = new HelpOperations();
            commandService    = new CommandManager();
            ideServices       = new IdeServices();
            CustomToolService.Init();

            commandService.CommandTargetScanStarted  += CommandServiceCommandTargetScanStarted;
            commandService.CommandTargetScanFinished += CommandServiceCommandTargetScanFinished;
            commandService.KeyBindingFailed          += KeyBindingFailed;

            KeyBindingService.LoadBindingsFromExtensionPath("/MonoDevelop/Ide/KeyBindingSchemes");
            KeyBindingService.LoadCurrentBindings("MD2");

            commandService.CommandError += delegate(object sender, CommandErrorArgs args) {
                LoggingService.LogInternalError(args.ErrorMessage, args.Exception);
            };

            FileService.ErrorHandler = FileServiceErrorHandler;

            monitor.BeginTask(GettextCatalog.GetString("Loading Workbench"), 5);
            Counters.Initialization.Trace("Loading Commands");

            commandService.LoadCommands("/MonoDevelop/Ide/Commands");
            monitor.Step(1);

            // Before startup commands.
            Counters.Initialization.Trace("Running Pre-Startup Commands");
            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/PreStartupHandlers", OnExtensionChanged);
            monitor.Step(1);

            Counters.Initialization.Trace("Initializing Workbench");
            workbench.Initialize(monitor);
            monitor.Step(1);

            Counters.Initialization.Trace("Initializing WelcomePage service");
            MonoDevelop.Ide.WelcomePage.WelcomePageService.Initialize();
            monitor.Step(1);

            Counters.Initialization.Trace("Realizing Workbench Window");
            workbench.Realize("SharpDevelop.Workbench.WorkbenchMemento");
            monitor.Step(1);

            MessageService.RootWindow    = workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(workbench.RootWindow);

            commandService.EnableIdleUpdate = true;

            if (Customizer != null)
            {
                Customizer.OnIdeInitialized(hideWelcomePage);
            }

            // Startup commands
            Counters.Initialization.Trace("Running Startup Commands");
            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/StartupHandlers", OnExtensionChanged);
            monitor.Step(1);
            monitor.EndTask();

            // Set initial run flags
            Counters.Initialization.Trace("Upgrading Settings");

            if (PropertyService.Get("MonoDevelop.Core.FirstRun", true))
            {
                isInitialRun = true;
                PropertyService.Set("MonoDevelop.Core.FirstRun", false);
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", Runtime.Version.ToString());
                PropertyService.SaveProperties();
            }

            string lastVersionString = PropertyService.Get("MonoDevelop.Core.LastRunVersion", "1.0");

            Version.TryParse(lastVersionString, out var lastVersion);

            if (Runtime.Version > lastVersion && !isInitialRun)
            {
                isInitialRunAfterUpgrade = true;
                upgradedFromVersion      = lastVersion;
                PropertyService.Set("MonoDevelop.Core.LastRunVersion", Runtime.Version.ToString());
                PropertyService.SaveProperties();
            }

            // The ide is now initialized

            isInitialized = true;

            if (initializedEvent != null)
            {
                initializedEvent(null, EventArgs.Empty);
                initializedEvent = null;
            }

            //FIXME: we should really make this on-demand. consumers can display a "loading help cache" message like VS
            MonoDevelop.Projects.HelpService.AsyncInitialize();

            UpdateInstrumentationIcon();
            IdeApp.Preferences.EnableInstrumentation.Changed += delegate {
                UpdateInstrumentationIcon();
            };
            AutoTestService.Start(commandService, Preferences.EnableAutomatedTesting);
            AutoTestService.NotifyEvent("MonoDevelop.Ide.IdeStart");

            Gtk.LinkButton.SetUriHook((button, uri) => Xwt.Desktop.OpenUrl(uri));
        }