private void GenerateProject(GeneratorOptions generatorOptions)
 {
     generatorOptions.CreatedFor    = $"{FeatureContext.FeatureInfo.Title}_{ScenarioContext.ScenarioInfo.Title}";
     generatorOptions._TargetFolder = Path.Combine(TestFolders.TempFolder, @"DeveroomTest\DS_{options}");
     generatorOptions.FallbackNuGetPackageSource = TestFolders.GetInputFilePath("ExternalPackages");
     _projectGenerator = generatorOptions.CreateProjectGenerator(s => _outputHelper.WriteLine(s));
     _projectGenerator.Generate();
 }
Example #2
0
 private void OnGenerate(object sender, EventArgs e)
 {
     using (GenCodeDialog dialog = new GenCodeDialog(Model))
     {
         if (dialog.ShowDialog(Workspace.ActiveWindow) == DialogResult.OK)
         {
             IProjectGenerator gen = ServiceRegistry.Instance[typeof(IProjectGenerator)] as IProjectGenerator;
             gen.Generate(Model.CurrentProject);
         }
     }
 }
Example #3
0
        public ActionResult Get([FromServices] IProjectGenerator generator, [FromBody] ProjectMetadata metadata)
        {
            if (metadata.Tags != null)
            {
                foreach (var kvp in metadata.Tags.Where(x => x.Value is JsonElement).ToList())
                {
                    var jsonElem = (JsonElement)kvp.Value;
                    if (jsonElem.ValueKind == JsonValueKind.True)
                    {
                        metadata.Tags[kvp.Key] = true;
                    }
                    else if (jsonElem.ValueKind == JsonValueKind.False)
                    {
                        metadata.Tags[kvp.Key] = false;
                    }
                    else
                    {
                        metadata.Tags[kvp.Key] = jsonElem.ToString();
                    }
                }
            }

            try
            {
                byte[] templateBytes = generator.Generate(metadata);
                return(new FileContentResult(templateBytes, "application/zip")
                {
                    FileDownloadName = $"{metadata.ProjectName}.zip"
                });
            }
            catch (TemplateException ex)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Content(ex.Message));
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Content(ex.Message));
            }
        }
Example #4
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            bool standalone = _configService.AppSettings.GetValue <bool>("Standalone");

            if (standalone)
            {
                // Standalone
                try
                {
                    await _configService.LoadFromConfigFile();

                    await _projectGenerator.Generate();

                    await _projectRunner.Run();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);
                    throw;
                }
            }
            else
            {
                // API
                while (!cancellationToken.IsCancellationRequested && (this._realtimeConnection == null || this._realtimeConnection.State == HubConnectionState.Disconnected))
                {
                    // Setup a connection to the realtime hub
                    _realtimeConnection = new HubConnectionBuilder()
                                          .WithUrl($"{_configService.AppSettings.GetValue<string>("API:URL")}/realtime-hub?isCodeGenerator=true&Template={_configService.AppSettings.GetValue<string>("Template:Name")}")
                                          .WithAutomaticReconnect()
                                          .Build();

                    // When the connection is closed
                    _realtimeConnection.Closed += async(ex) =>
                    {
                        _logger.LogError("Lost realtime connection");
                        if (ex != null)
                        {
                            _logger.LogError(ex.ToString());
                        }

                        await Task.CompletedTask;
                    };

                    _realtimeConnection.On("Generate", async(CodeGenConfig config) =>
                    {
                        await _configService.UpdateConfig(config);
                    });

                    // Start initial realtime connection
                    await Connect();

                    try
                    {
                        await _configService.LoadFromConfigFile();

                        await _projectGenerator.Generate();

                        _projectRunner.Run();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, ex.Message);
                        throw;
                    }
                }
            }
        }
        public override bool Execute()
        {
            if (string.Compare(Platform, "Web", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                // Trigger JSIL provider download if needed.
                string jsilDirectory, jsilCompilerFile;
                if (!m_JSILProvider.GetJSIL(out jsilDirectory, out jsilCompilerFile))
                {
                    return(false);
                }
            }

            var module = ModuleInfo.Load(Path.Combine(RootPath, "Build", "Module.xml"));

            LogMessage(
                "Starting generation of projects for " + Platform);

            var definitions    = module.GetDefinitionsRecursively(Platform).ToArray();
            var loadedProjects = new List <LoadedDefinitionInfo>();

            if (_hostPlatformDetector.DetectPlatform() == "Windows")
            {
                var concurrentProjects = new ConcurrentBag <LoadedDefinitionInfo>();

                Parallel.ForEach(definitions, definition =>
                {
                    LogMessage("Loading: " + definition.Name);
                    concurrentProjects.Add(
                        m_ProjectLoader.Load(
                            Platform,
                            module,
                            definition));
                });

                // Do this so we maintain order with the original definitions list.
                foreach (var definition in definitions)
                {
                    var loadedProject = concurrentProjects.FirstOrDefault(x => x.Definition == definition);
                    if (loadedProject != null)
                    {
                        loadedProjects.Add(loadedProject);
                    }
                }
            }
            else
            {
                foreach (var definition in definitions)
                {
                    LogMessage("Loading: " + definition.Name);
                    loadedProjects.Add(
                        m_ProjectLoader.Load(
                            Platform,
                            module,
                            definition));
                }
            }

            var                  serviceManager = new ServiceManager(Platform);
            List <Service>       services;
            TemporaryServiceSpec serviceSpecPath;

            if (ServiceSpecPath == null)
            {
                serviceManager.SetRootDefinitions(module.GetDefinitions());

                if (EnableServices == null)
                {
                    EnableServices = new string[0];
                }

                if (DisableServices == null)
                {
                    DisableServices = new string[0];
                }

                foreach (var service in EnableServices)
                {
                    serviceManager.EnableService(service);
                }

                foreach (var service in DisableServices)
                {
                    serviceManager.DisableService(service);
                }

                if (DebugServiceResolution)
                {
                    serviceManager.EnableDebugInformation();
                }

                try
                {
                    services = serviceManager.CalculateDependencyGraph(loadedProjects.Select(x => x.Project).ToList());
                }
                catch (InvalidOperationException ex)
                {
                    RedirectableConsole.WriteLine("Error during service resolution: " + ex.Message);
                    return(false);
                }

                serviceSpecPath = serviceManager.SaveServiceSpec(services);

                foreach (var service in services)
                {
                    if (service.ServiceName != null)
                    {
                        LogMessage("Enabled service: " + service.FullName);
                    }
                }
            }
            else
            {
                services        = serviceManager.LoadServiceSpec(ServiceSpecPath);
                serviceSpecPath = new TemporaryServiceSpec(ServiceSpecPath, true);
            }

            using (serviceSpecPath)
            {
                var submodulesToProcess = new List <ModuleInfo>();
                var allSubmodules       = module.GetSubmodules(Platform);

                if (_hostPlatformDetector.DetectPlatform() == "Windows")
                {
                    var concurrentSubmodulesToProcess = new ConcurrentBag <ModuleInfo>();

                    Parallel.ForEach(allSubmodules, submodule =>
                    {
                        if (_featureManager.IsFeatureEnabledInSubmodule(module, submodule,
                                                                        Feature.OptimizationSkipInvocationOnNoStandardProjects))
                        {
                            if (submodule.GetDefinitionsRecursively(Platform).All(x => !x.IsStandardProject))
                            {
                                // Do not invoke this submodule.
                                LogMessage(
                                    "Skipping submodule generation for " + submodule.Name +
                                    " (there are no projects to generate)");
                            }
                            else
                            {
                                concurrentSubmodulesToProcess.Add(submodule);
                            }
                        }
                    });

                    // Do this so we maintain order with the original GetSubmodules list.
                    foreach (var submodule in allSubmodules)
                    {
                        if (concurrentSubmodulesToProcess.Contains(submodule))
                        {
                            submodulesToProcess.Add(submodule);
                        }
                    }
                }
                else
                {
                    foreach (var submodule in module.GetSubmodules(Platform))
                    {
                        if (_featureManager.IsFeatureEnabledInSubmodule(module, submodule,
                                                                        Feature.OptimizationSkipInvocationOnNoStandardProjects))
                        {
                            if (submodule.GetDefinitionsRecursively(Platform).All(x => !x.IsStandardProject))
                            {
                                // Do not invoke this submodule.
                                LogMessage(
                                    "Skipping submodule generation for " + submodule.Name +
                                    " (there are no projects to generate)");
                            }
                            else
                            {
                                submodulesToProcess.Add(submodule);
                            }
                        }
                    }
                }

                // Run Protobuild in batch mode in each of the submodules
                // where it is present.
                foreach (var submodule in submodulesToProcess)
                {
                    LogMessage(
                        "Invoking submodule generation for " + submodule.Name);
                    var noResolve = _featureManager.IsFeatureEnabledInSubmodule(module, submodule,
                                                                                Feature.PackageManagementNoResolve)
                        ? " -no-resolve"
                        : string.Empty;
                    var noHostPlatform = DisableHostPlatformGeneration &&
                                         _featureManager.IsFeatureEnabledInSubmodule(module, submodule,
                                                                                     Feature.NoHostGenerate)
                        ? " -no-host-generate"
                        : string.Empty;
                    _moduleExecution.RunProtobuild(
                        submodule,
                        _featureManager.GetFeatureArgumentToPassToSubmodule(module, submodule) +
                        "-generate " + Platform +
                        " -spec " + serviceSpecPath +
                        " " + m_PackageRedirector.GetRedirectionArguments() +
                        noResolve + noHostPlatform);
                    LogMessage(
                        "Finished submodule generation for " + submodule.Name);
                }

                var repositoryPaths = new List <string>();

                if (_hostPlatformDetector.DetectPlatform() == "Windows")
                {
                    var concurrentRepositoryPaths = new ConcurrentBag <string>();

                    Parallel.ForEach(definitions.Where(x => x.ModulePath == module.Path), definition =>
                    {
                        if (definition.PostBuildHook && RequiresHostPlatform != null)
                        {
                            // We require the host platform projects at this point.
                            RequiresHostPlatform();
                        }

                        string repositoryPath;
                        var definitionCopy = definition;
                        m_ProjectGenerator.Generate(
                            definition,
                            loadedProjects,
                            WorkingDirectory,
                            RootPath,
                            definition.Name,
                            Platform,
                            services,
                            out repositoryPath,
                            () => LogMessage("Generating: " + definitionCopy.Name),
                            DebugProjectGeneration);

                        // Only add repository paths if they should be generated.
                        if (module.GenerateNuGetRepositories && !string.IsNullOrEmpty(repositoryPath))
                        {
                            concurrentRepositoryPaths.Add(repositoryPath);
                        }
                    });

                    repositoryPaths = concurrentRepositoryPaths.ToList();
                }
                else
                {
                    foreach (var definition in definitions.Where(x => x.ModulePath == module.Path))
                    {
                        if (definition.PostBuildHook && RequiresHostPlatform != null)
                        {
                            // We require the host platform projects at this point.
                            RequiresHostPlatform();
                        }

                        string repositoryPath;
                        var    definitionCopy = definition;
                        m_ProjectGenerator.Generate(
                            definition,
                            loadedProjects,
                            WorkingDirectory,
                            RootPath,
                            definition.Name,
                            Platform,
                            services,
                            out repositoryPath,
                            () => LogMessage("Generating: " + definitionCopy.Name),
                            DebugProjectGeneration);

                        // Only add repository paths if they should be generated.
                        if (module.GenerateNuGetRepositories && !string.IsNullOrEmpty(repositoryPath))
                        {
                            repositoryPaths.Add(repositoryPath);
                        }
                    }
                }

                var solution = Path.Combine(
                    RootPath,
                    ModuleName + "." + Platform + ".sln");
                LogMessage("Generating: (solution)");
                m_SolutionGenerator.Generate(
                    WorkingDirectory,
                    module,
                    loadedProjects.Select(x => x.Project).ToList(),
                    Platform,
                    solution,
                    services,
                    repositoryPaths,
                    DebugProjectGeneration);

                // Only save the specification cache if we allow synchronisation
                if (module.DisableSynchronisation == null || !module.DisableSynchronisation.Value)
                {
                    var serviceCache = Path.Combine(RootPath, ModuleName + "." + Platform + ".speccache");
                    LogMessage("Saving service specification");
                    File.Copy(serviceSpecPath.Path, serviceCache, true);
                }

                LogMessage(
                    "Generation complete.");
            }

            return(true);
        }
Example #6
0
        public void Generate(int projectCount, IProjectGenerator generator, IEnumerable <IProjectModifier> modifiers, string solutionPath)
        {
            var projects = new List <IProject>();

            for (var i = 0; i < projectCount; i++)
            {
                var project = generator.Generate(i);

                Directory.CreateDirectory(Path.Combine(solutionPath, project.RelativeProjectPath));

                foreach (var modifier in modifiers)
                {
                    modifier.Modify(project, projects, solutionPath);
                }

                using var stream = new FileStream(Path.Combine(solutionPath, project.RelativeProjectFilePath), FileMode.Create);
                using var writer = XmlWriter.Create(stream, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, IndentChars = "  " });
                project.ProjectXml.Save(writer);

                projects.Add(project);
            }

            using (var stream = File.OpenWrite(Path.Combine(solutionPath, $"{Path.GetFileName(solutionPath)}.sln")))
                using (var writer = new StreamWriter(stream, Encoding.ASCII))
                {
                    writer.WriteLine();
                    writer.WriteLine(@"Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2019
MinimumVisualStudioVersion = 10.0.40219.1");

                    foreach (IProject project in projects)
                    {
                        writer.WriteLine(
                            $@"Project(""{project.ProjectType:B}"") = ""{project.ProjectName}"", ""{project.RelativeProjectFilePath}"", ""{project.ProjectGuid:B}""
EndProject");
                    }

                    writer.WriteLine(
                        @"Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution");
                    foreach (var project in projects)
                    {
                        writer.WriteLine(
                            $@"        {project.ProjectGuid:B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {project.ProjectGuid:B}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {project.ProjectGuid:B}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {project.ProjectGuid:B}.Release|Any CPU.Build.0 = Release|Any CPU");
                    }

                    writer.WriteLine(
                        $@"    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(ExtensibilityGlobals) = postSolution
        SolutionGuid = {Guid.NewGuid():B}
    EndGlobalSection
EndGlobal");
                }
        }