public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) { dte = automationObject as EnvDTE.DTE; defaultDestinationFolder = replacementsDictionary["$destinationdirectory$"]; basePath = Path.GetDirectoryName((string)customParams[0]); safeProjectName = replacementsDictionary["$safeprojectname$"]; var doc = Helpers.LoadWizardXml(replacementsDictionary); var ns = Helpers.WizardNamespace; foreach (var element in doc.Root.Elements(ns + "Projects").Elements(ns + "Project")) { var definition = new ProjectDefinition(element, replacementsDictionary); if (replacementsDictionary.MatchesCondition(definition.Condition)) definitions.Add(definition); } }
public static bool Create(string subscriptionKey, string hostURI, string name, string description, string gender, string locale) { var properties = new Dictionary <string, string>(); properties.Add("Gender", gender.Substring(0, 1).ToUpper() + gender.Substring(1)); var projectDefinition = ProjectDefinition.Create( name, name, description, locale, properties, "TextToSpeech"); var response = APIHelper.Submit <ProjectDefinition>(subscriptionKey, hostURI + API_V3.VoiceProject_Create, projectDefinition); if (response.StatusCode != HttpStatusCode.Accepted && response.StatusCode != HttpStatusCode.Created) { APIHelper.PrintErrorMessage(response); return(false); } return(true); }
public void BasicProjectTest() { var sln = new ProjectDefinition( "HelloWorld", PythonProject, Compile("server", "") ).Generate(); using (var vs = sln.ToMockVs()) { Assert.IsNotNull(vs.WaitForItem("HelloWorld", "Python Environments")); Assert.IsNotNull(vs.WaitForItem("HelloWorld", "References")); Assert.IsNotNull(vs.WaitForItem("HelloWorld", "Search Paths")); Assert.IsNotNull(vs.WaitForItem("HelloWorld", "server.py")); var view = vs.OpenItem("HelloWorld", "server.py"); view.Invoke(() => view.Type("import ")); using (var sh = view.WaitForSession <ICompletionSession>()) { AssertUtil.Contains(sh.Session.Completions(), "sys"); } } }
public async Task CreateDotnetPublishZip_SelfContained() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var projectDefinition = new ProjectDefinition(projectPath); var recipeDefinition = new Mock <RecipeDefinition>(); var recommendation = new Recommendation(recipeDefinition.Object, projectDefinition.ProjectPath, 100, new Dictionary <string, string>()); recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild = true; recommendation.DeploymentBundle.DotnetPublishBuildConfiguration = "Release"; recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = "--nologo"; await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation); var expectedCommand = $"dotnet publish \"{projectDefinition.ProjectPath}\"" + $" -o \"{_directoryManager.CreatedDirectories.First()}\"" + " -c Release" + " --runtime linux-x64" + " --nologo" + " --self-contained true"; Assert.Equal(expectedCommand, _commandLineWrapper.CommandsToExecute.First().Command); }
public DataProjectAssembler CreateWork(ProjectDefinition project, AppSettings settings) { // Grab the temp directory and make sure it exists var tempDir = new DirectoryInfo(settings.TempDir); if (!tempDir.Exists) { logger.LogInformation("Creating temp directory: {Path}.", tempDir.FullName); tempDir.Create(); } // Create the worker that assembles a data project from its components (models, mappings) var root = serviceProvider.GetRequiredService <DataProjectAssembler>(); // Add a worker to create each data model foreach (var model in project.Models) { root.AddWorker(CreateWorker(model, settings)); } // Add a worker to process each mapping foreach (var map in project.Maps) { root.AddWorker(CreateWorker(map)); } // Dump the dependency tree, for debugging using (var writer = new StreamWriter(Path.Combine(tempDir.FullName, "work-plan.txt"))) using (var context = new PlanDumperContext(writer)) { root.Dump(context); } // Return the dependency tree, for subsequent execution return(root); }
private async Task <List <UserDocument> > ResolveUsersAsync(ProjectDefinition projectDefinition, string projectId) { var users = new List <UserDocument>(); if (projectDefinition.Users?.Any() ?? false) { var tasks = projectDefinition.Users.Select(user => ResolveUserAndEnsureMembershipAsync(user, projectId)); users = (await Task.WhenAll(tasks).ConfigureAwait(false)).ToList(); } if (!users.Any(u => u.Id == UserService.CurrentUserId)) { var currentUser = await UserService .CurrentUserAsync() .ConfigureAwait(false); currentUser.EnsureProjectMembership(projectId, ProjectUserRole.Owner); users.Add(currentUser); } return(users); async Task <UserDocument> ResolveUserAndEnsureMembershipAsync(UserDefinition userDefinition, string projectId) { var user = await UserService .ResolveUserAsync(userDefinition) .ConfigureAwait(false); var role = user.Id == UserService.CurrentUserId ? ProjectUserRole.Owner : Enum.Parse <ProjectUserRole>(userDefinition.Role, true); user.EnsureProjectMembership(projectId, role, userDefinition.Properties); return(user); } }
void MargeFn(ProjectDefinition p) { var doNotMarge = new[] { "build.dll", "libcef.dll", "chrome_elf.dll", "d3dcompiler_47.dll", "libEGL.dll", "libGLESv2.dll", "CefSharp.dll", "CefSharp.Core.dll", "CefSharp.BrowserSubprocess.Core.dll" }; var exclude = string.Join(' ', doNotMarge.Select(x => $"--exclude={x}")); var buildOut = TmpBuild / CommonDir.Build / p.Dir; var margeOut = TmpBuild / CommonDir.Merge / p.Dir; EnsureExistingDirectory(margeOut); CopyDirectoryRecursively(buildOut, margeOut, DirectoryExistsPolicy.Merge); using (var process = ProcessTasks.StartProcess( LibzPath, $"inject-dll --assembly {p.Exe} --include *.dll {exclude} --move", margeOut)) { process.AssertWaitForExit(); } }
/// <summary> /// Processes the specified assembly. /// </summary> /// <param name="assemblyPath">The assembly path.</param> /// <param name="projectPath">The project path.</param> /// <param name="solutionPath">The solution path.</param> /// <param name="configuration">The configuration.</param> /// <param name="platform">The platform.</param> /// <param name="buildID">The build identifier.</param> /// <param name="buildTime">The build time.</param> /// <param name="entryAssemblyPath">The entry assembly path.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">Could not find assembly to stitch</exception> /// <exception cref="System.InvalidOperationException">Could not find assembly to stitch</exception> public bool Process(string assemblyPath, string projectPath, string solutionPath, string configuration, string platform, Guid buildID, DateTime buildTime, string entryAssemblyPath) { var globalProperties = new Dictionary <string, string> { { "Configuration", (configuration ?? "Release").Trim() }, { "Platform", (platform ?? "AnyCPU").Trim() } }; var project = new ProjectDefinition(projectPath, Path.GetDirectoryName(assemblyPath), null, CreateAssemblyResolver(), new ProjectCollection(globalProperties)); assemblyPath = assemblyPath ?? project.TargetPath; if (assemblyPath == null || !File.Exists(assemblyPath)) { throw new InvalidOperationException("Could not find assembly to stitch"); } var pdbExtension = ".pdb"; var pdbPath = ChangeExtension(assemblyPath, pdbExtension); bool success = true; var tempAssemblyPath = assemblyPath + ".2"; File.Copy(assemblyPath, tempAssemblyPath, true); try { using (var module = ModuleDefMD.Load(tempAssemblyPath)) { if (File.Exists(pdbPath)) { module.LoadPdb(File.ReadAllBytes(pdbPath)); } bool ok; try { var context = new ProjectStitcherContext { Module = module, AssemblyPath = assemblyPath, BuildTime = buildTime, BuildID = buildID, Project = project, ProjectPath = projectPath, SolutionPath = solutionPath, TaskAssemblyPath = entryAssemblyPath, Configuration = configuration, Platform = platform, }; ok = Process(context); } catch (Exception e) { Logging.WriteError("Uncaught exception: {0}", e.ToString()); ok = false; success = false; } if (ok) { if (module.IsILOnly) { var moduleWriterOptions = new ModuleWriterOptions(module); moduleWriterOptions.WritePdb = true; moduleWriterOptions.PdbFileName = pdbPath; module.Write(assemblyPath, SetWriterOptions(project, module, moduleWriterOptions)); } else { var nativeModuleWriterOptions = new NativeModuleWriterOptions(module, true); nativeModuleWriterOptions.WritePdb = true; nativeModuleWriterOptions.PdbFileName = pdbPath; module.NativeWrite(assemblyPath, SetWriterOptions(project, module, nativeModuleWriterOptions)); } } } } finally { File.Delete(tempAssemblyPath); } return(success); }
// never exclude projects that are passed from the cmd public bool ExludeProject(ProjectDefinition project, Platform platform) => false;
public void GetTypeForAssembliesNullMonoPath() { var projectDefinition = new ProjectDefinition("MyProject", _assemblyLocator.Object, _factory.Object, new List <ITestAssemblyDefinition>(), ""); Assert.Throws <ArgumentNullException>(() => projectDefinition.GetTypeForAssemblies(null, Platform.iOS)); }
private void InitializeProjectModel() { if (ProjectInstance == null) { // load default settings ProjectInstance = ProjectDefinition.LoadDefaultProject(); } ProjectInstance.ProjectName = txtProjectName.Text; ProjectInstance.CodeGenSettings.DefaultNamespace = txtNamespace.Text; ProjectInstance.GenerationPath = txtGenerationPath.Text; ProjectInstance.CodeGenSettings.CodeGenPatternFile = txtPatternfile.Text; ProjectInstance.CodeGenSettings.GenerateTablesForeignKeys = chkGenForeignKey.Checked; ProjectInstance.CodeGenSettings.GenerateColumnsDescription = chkGenDescription.Checked; ProjectInstance.CodeGenSettings.GenerateConstraintKeys = chkTableConstraintKeys.Checked; ProjectInstance.RenamingOptions.UnderlineWordDelimiter = chkRenUnderlineWordDelimiter.Checked; ProjectInstance.RenamingOptions.RemoveUnderline.Enabled = chkRenRemUnderline.Checked; ProjectInstance.RenamingOptions.RemoveUnderline.Tables = chkRenUnderlineTables.Checked; ProjectInstance.RenamingOptions.RemoveUnderline.Properties = chkRenUnderlineProps.Checked; ProjectInstance.RenamingOptions.CaseChange.Enabled = chkRenamingCase.Checked; ProjectInstance.RenamingOptions.CaseChange.Tables = chkRenCaseTables.Checked; ProjectInstance.RenamingOptions.CaseChange.Properties = chkRenCaseProps.Checked; ProjectInstance.RenamingOptions.CaseChangeMode = (ProjectRenaming.CaseChangeType)cmbRenamingCase.SelectedValue; if (pagerDatabaseProvider.SelectedTab == tabSQLServer) { ProjectInstance.DbSettions.ServerName = txtSqlHost.Text; ProjectInstance.DbSettions.DatabaseName = txtSqlDbName.Text; ProjectInstance.DbSettions.SqlUsername = txtSqlUsername.Text; ProjectInstance.DbSettions.SqlPassword = txtSqlPassword.Text; ProjectInstance.DbSettions.UseSqlAuthentication = rbtnSqlAuthentication.Checked; ProjectInstance.DbSettions.ConnectTimeout = Convert.ToInt32(txtSqlConnectTimeout.Text); ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.SQLServer; } else if (pagerDatabaseProvider.SelectedTab == tabSQLite) { ProjectInstance.DbSettions.ServerName = txtSQLiteDatabaseName.Text; try { ProjectInstance.DbSettions.DatabaseName = Path.GetFileNameWithoutExtension(txtSQLiteDatabaseName.Text); } catch { } ProjectInstance.DbSettions.SqlUsername = ""; ProjectInstance.DbSettions.SqlPassword = txtSQLitePassword.Text; ProjectInstance.DbSettions.UseSqlAuthentication = false; ProjectInstance.DbSettions.ConnectTimeout = Convert.ToInt32(txtSQLiteConnectTimeout.Text); ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.SQLite; } else if (pagerDatabaseProvider.SelectedTab == tabSqlCe) { ProjectInstance.DbSettions.ServerName = txtSqlCeDatabaseName.Text; try { ProjectInstance.DbSettions.DatabaseName = Path.GetFileNameWithoutExtension(txtSqlCeDatabaseName.Text); } catch { } ProjectInstance.DbSettions.SqlUsername = ""; ProjectInstance.DbSettions.SqlPassword = txtSqlCePassword.Text; if (string.IsNullOrEmpty(txtSqlCePassword.Text)) { ProjectInstance.DbSettions.UseSqlAuthentication = false; } else { ProjectInstance.DbSettions.UseSqlAuthentication = true; } ProjectInstance.DbSettions.ConnectTimeout = -1; ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.SqlCe4; } else if (pagerDatabaseProvider.SelectedTab == tabOracle) { ProjectInstance.DbSettions.ServerName = txtOrclDataSource.Text; ProjectInstance.DbSettions.ConnectTimeout = Convert.ToInt32(txtOrclConnectTimeout.Text); ProjectInstance.DbSettions.UseSqlAuthentication = rbtnOrclSpecificUsernamePass.Checked; ProjectInstance.DbSettions.DatabaseName = txtOrclDbName.Text; ProjectInstance.DbSettions.SqlUsername = txtOrclUsername.Text; ProjectInstance.DbSettions.SqlPassword = txtOrclPassword.Text; ProjectInstance.DbSettions.OracleUseSysdbaRole = chkOrclUserRoleSYSDBA.Checked; ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.Oracle; } else if (pagerDatabaseProvider.SelectedTab == tabPostgres) { ProjectInstance.DbSettions.ServerName = txtPgHost.Text; ProjectInstance.DbSettions.DatabaseName = txtPgDbName.Text; ProjectInstance.DbSettions.SqlUsername = txtPgUsername.Text; ProjectInstance.DbSettions.SqlPassword = txtPgPassword.Text; ProjectInstance.DbSettions.SchemaName = txtPgSchema.Text; ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.Npgsql; } else if (pagerDatabaseProvider.SelectedTab == tabMySQL) { ProjectInstance.DbSettions.ServerName = txtMysqlHost.Text; ProjectInstance.DbSettions.DatabaseName = txtMysqlDbName.Text; ProjectInstance.DbSettions.SqlUsername = txtMysqlUsername.Text; ProjectInstance.DbSettions.SqlPassword = txtMysqlPassword.Text; ProjectInstance.DbSettions.DatabaseProvider = DatabaseProvider.MySql; } ProjectInstance.DbSettions.SuffixForTables = txtSuffixForTables.Text; ProjectInstance.DbSettions.SuffixForViews = txtSuffixForViews.Text; ProjectInstance.DbSettions.PrefixForTables = txtPrefixForTables.Text; ProjectInstance.DbSettions.PrefixForViews = txtPrefixForViews.Text; ProjectInstance.DbSettions.IgnoredPrefixes.Clear(); foreach (var item in lstIgnoredPrefixes.Items) { ProjectInstance.DbSettions.IgnoredPrefixes.Add(item.ToString()); } ProjectInstance.DbSettions.IgnoredSuffixes.Clear(); foreach (var item in lstIgnoredSuffixes.Items) { ProjectInstance.DbSettions.IgnoredSuffixes.Add(item.ToString()); } }
public SchemaAnalyzer(ProjectDefinition project, PatternProject pattern, DbDatabase database) { _patternProject = pattern; _projectDef = project; _database = database; }
public Proj3DDefWindow(ProjectDefinition projDef) { InitializeComponent(); _projdef = projDef; }
public void LoadProject(string filename, bool noPlugins) { try { _projectFilename = filename; _project.Filenames.Clear(); _model.Clear(); _lookup.Clear(); _watcher.Clear(); _rootItem.Files.Clear(); if (!File.Exists(filename)) { _windowManager.Logger.LogStr("Project file was not found:" + filename); return; } // Load the project file. string s = File.ReadAllText(_projectFilename); Hwd.Serialization.Decoder decoder = new Hwd.Serialization.Decoder(); _project = (ProjectDefinition)decoder.Decode(s); if (_project == null) { _windowManager.Logger.LogStr("Failed to deserialize project file:" + _projectFilename); _project = new ProjectDefinition(); return; } // Check the filename list. List <string> remove = new List <string>(); foreach (string name in _project.Filenames) { if (!File.Exists(name)) { remove.Add(name); } else { MatchFileToModel(name); } } foreach (string name in remove) { _project.Filenames.Remove(name); _windowManager.Logger.LogStr("Warning : Project contains a file that was not found:" + name); } // Load item structure in advance, so we can "goto" items. foreach (KeyValuePair <string, BaseItem> pair in _model.Files) { ReadItem(pair.Value, false); _watcher.AddWatch(pair.Value); } // This must be done before we set current item in the tree. RefreshModel(); SetCaption(); // Load favourites, global ignores, and plugin options as part of the project. _windowManager.Favourites.AddAll(_project.Favourites); _windowManager.SetCaption(_projectFilename); // Load settings for windows. if (!noPlugins) { _windowManager.SetWindowItems(_project.Windows, _project.Items); } // Load the project item. We avoid selecting it here because each // window will load it's own current item anyway, above. BaseItem item = Lookup(_project.ProjectItem); try { _ignoreSelect = true; SetActiveItem(item, this); } finally { _ignoreSelect = false; } // Notify files changed. if (!noPlugins) { if (OnFilesChanged != null) { OnFilesChanged(_rootItem, new EventArgs()); } } _watcher.Start(); } catch (SerializationException exc) { _windowManager.Logger.LogExcStr(exc, "Deserializing project failed"); } catch (IOException exc) { _windowManager.Logger.LogExcStr(exc, "Load project failed"); } }
private List<FileDefinition> LoadFileDefinitions(ProjectDefinition projectDefinition, XElement includeElement) { List<FileDefinition> list = new List<FileDefinition>(); foreach (XElement file in includeElement.Descendants(PROJECT_FILE)) { FileDefinition fileDefinition = new FileDefinition(); fileDefinition.Enabled = bool.Parse(file.Attribute(XName.Get(ENABLED)).Value); // XSD should have validated input... string tmpPath = file.Attribute(XName.Get(PROJECT_PATH)).Value; if (string.IsNullOrEmpty(tmpPath)) { Log.Warning("Empty file defined in project '" + projectDefinition.Name + "'."); continue; } string path = null; if (tmpPath.StartsWith("*")) { tmpPath = tmpPath.TrimStart('*'); path = string.IsNullOrEmpty(tmpPath) ? projectDefinition.RootDirectory.Path : Path.GetFullPath(projectDefinition.RootDirectory.Path + tmpPath); if (!File.Exists(path)) { Log.Warning("Unable to find file '" + path + "' in project '" + projectDefinition.Name + "'."); continue; } } fileDefinition.Path = path; list.Add(fileDefinition); } return list; }
public async Task <IActionResult> Post([FromBody] ProjectDefinition projectDefinition) { if (projectDefinition is null) { throw new ArgumentNullException(nameof(projectDefinition)); } var validation = new ProjectDefinitionValidator().Validate(projectDefinition); if (!validation.IsValid) { return(ErrorResult .BadRequest(validation) .ToActionResult()); } var nameExists = await ProjectRepository .NameExistsAsync(projectDefinition.Name) .ConfigureAwait(false); if (nameExists) { return(ErrorResult .Conflict($"A Project with name '{projectDefinition.Name}' already exists. Project names must be unique. Please try your request again with a unique name.") .ToActionResult()); } var projectId = Guid.NewGuid().ToString(); var users = await ResolveUsersAsync(projectDefinition, projectId) .ConfigureAwait(false); var project = new ProjectDocument { Id = projectId, Users = users, Name = projectDefinition.Name, Tags = projectDefinition.Tags, Properties = projectDefinition.Properties }; if (!string.IsNullOrEmpty(projectDefinition.ProjectType)) { project.Type = await projectTypeRepository .GetAsync(projectDefinition.ProjectType) .ConfigureAwait(false); if (project.Type is null) { return(ErrorResult .BadRequest(new ValidationError { Field = "projectType", Message = $"A Project Type with the ID '{projectDefinition.ProjectType}' could not be found in this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'." }) .ToActionResult()); } } else { project.Type = await projectTypeRepository .GetDefaultAsync() .ConfigureAwait(false); if (project.Type is null) { return(ErrorResult .BadRequest(new ValidationError { Field = "projectType", Message = $"No value was provided for 'projectType' and there is no a default Project Type set for this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'." }) .ToActionResult()); } } var currentUser = users.FirstOrDefault(u => u.Id == UserService.CurrentUserId); var command = new OrchestratorProjectCreateCommand(currentUser, project); return(await Orchestrator .InvokeAndReturnActionResultAsync <ProjectDocument, Project>(command, Request) .ConfigureAwait(false)); }
public async Task ExecuteAsync(bool saveCdkProject) { // Ensure a .NET project can be found. ProjectDefinition project = null; try { project = new ProjectDefinition(_session.ProjectPath); } catch (ProjectFileNotFoundException ex) { var files = Directory.GetFiles(_session.ProjectPath, "*.sln"); if (files.Any()) { _toolInteractiveService.WriteErrorLine($"This directory contains a solution file, but the tool requires a project file. Please run the tool from the directory that contains a .csproj/.fsproj or provide a path to the .csproj/.fsproj via --project-path flag."); } else { _toolInteractiveService.WriteErrorLine($"A project was not found at the path {_session.ProjectPath}"); } throw new FailedToFindDeployableTargetException(ex); } var orchestrator = new Orchestrator.Orchestrator( _session, _orchestratorInteractiveService, _cdkProjectHandler, _awsResourceQueryer, _deploymentBundleHandler, new[] { RecipeLocator.FindRecipeDefinitionsPath() }); // Determine what recommendations are possible for the project. var recommendations = await orchestrator.GenerateDeploymentRecommendations(); if (recommendations.Count == 0) { _toolInteractiveService.WriteLine(string.Empty); _toolInteractiveService.WriteErrorLine($"The project you are trying to deploy is currently not supported."); throw new FailedToGenerateAnyRecommendations(); } // Look to see if there are any existing deployed applications using any of the compatible recommendations. var existingApplications = await orchestrator.GetExistingDeployedApplications(recommendations); _toolInteractiveService.WriteLine(string.Empty); string cloudApplicationName; if (existingApplications.Count == 0) { var title = "Name the AWS stack to deploy your application to" + Environment.NewLine + "(A stack is a collection of AWS resources that you can manage as a single unit.)" + Environment.NewLine + "--------------------------------------------------------------------------------"; cloudApplicationName = _consoleUtilities.AskUserForValue( title, GetDefaultApplicationName(project.ProjectPath), allowEmpty: false); } else { var title = "Select the AWS stack to deploy your application to" + Environment.NewLine + "(A stack is a collection of AWS resources that you can manage as a single unit.)"; var userResponse = _consoleUtilities.AskUserToChooseOrCreateNew(existingApplications.Select(x => x.Name).ToList(), title, askNewName: true, defaultNewName: GetDefaultApplicationName(project.ProjectPath)); cloudApplicationName = userResponse.SelectedOption ?? userResponse.NewName; } var existingCloudApplication = existingApplications.FirstOrDefault(x => string.Equals(x.Name, cloudApplicationName)); Recommendation selectedRecommendation = null; _toolInteractiveService.WriteLine(string.Empty); // If using a previous deployment preset settings for deployment based on last deployment. if (existingCloudApplication != null) { var existingCloudApplicationMetadata = await orchestrator.LoadCloudApplicationMetadata(existingCloudApplication.Name); selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, existingCloudApplication.RecipeId, StringComparison.InvariantCultureIgnoreCase)); selectedRecommendation.ApplyPreviousSettings(existingCloudApplicationMetadata.Settings); var header = $"Loading {existingCloudApplication.Name} settings:"; _toolInteractiveService.WriteLine(header); _toolInteractiveService.WriteLine(new string('-', header.Length)); var optionSettings = selectedRecommendation .Recipe .OptionSettings .Where(x => { if (!selectedRecommendation.IsOptionSettingDisplayable(x)) { return(false); } var value = selectedRecommendation.GetOptionSettingValue(x); if (value == null || value.ToString() == string.Empty || object.Equals(value, x.DefaultValue)) { return(false); } return(true); }) .ToArray(); foreach (var setting in optionSettings) { DisplayOptionSetting(selectedRecommendation, setting, -1, optionSettings.Length, DisplayOptionSettingsMode.Readonly); } } else { selectedRecommendation = _consoleUtilities.AskToChooseRecommendation(recommendations); } // Apply the user enter project name to the recommendation so that any default settings based on project name are applied. selectedRecommendation.OverrideProjectName(cloudApplicationName); var systemCapabilities = await _session.SystemCapabilities; if (selectedRecommendation.Recipe.DeploymentType == DeploymentTypes.CdkProject && !systemCapabilities.NodeJsMinVersionInstalled) { _toolInteractiveService.WriteErrorLine("The selected deployment option requires Node.js 10.3 or later, which was not detected. Please install Node.js: https://nodejs.org/en/download/"); throw new MissingNodeJsException(); } if (selectedRecommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.Container) { if (!systemCapabilities.DockerInfo.DockerInstalled) { _toolInteractiveService.WriteErrorLine("The selected deployment option requires Docker, which was not detected. Please install and start the appropriate version of Docker for you OS: https://docs.docker.com/engine/install/"); throw new MissingDockerException(); } if (!systemCapabilities.DockerInfo.DockerContainerType.Equals("linux", StringComparison.OrdinalIgnoreCase)) { _toolInteractiveService.WriteErrorLine("The deployment tool requires Docker to be running in linux mode. Please switch Docker to linux mode to continue."); throw new DockerContainerTypeException(); } } var deploymentBundleDefinition = orchestrator.GetDeploymentBundleDefinition(selectedRecommendation); var configurableOptionSettings = selectedRecommendation.Recipe.OptionSettings.Union(deploymentBundleDefinition.Parameters); await ConfigureDeployment(selectedRecommendation, configurableOptionSettings, false); var cloudApplication = new CloudApplication { Name = cloudApplicationName }; if (!ConfirmDeployment(selectedRecommendation)) { return; } await CreateDeploymentBundle(orchestrator, selectedRecommendation, cloudApplication); await orchestrator.DeployRecommendation(cloudApplication, selectedRecommendation); }
public SolutionFile Generate(ProjectDefinition project) { return(new ProjectDefinition(PythonProject, project).Generate()); }
public Task <IActionResult> Post([FromBody] ProjectDefinition projectDefinition) => WithContextAsync <Organization>(async(contextUser, organization) =>
public OrchestratorSession(ProjectDefinition projectDefinition) { ProjectDefinition = projectDefinition; }
private void LoadProjectDefinitions(XDocument doc) { lock (_lockConfigurationFile) { // Validate input... if (doc == null) throw new ArgumentNullException("doc"); List<IProjectDefinition> projectDefinitions = new List<IProjectDefinition>(); foreach (XElement projDefinition in doc.Descendants(PROJECT_DEFINITION)) { ProjectDefinition projectDefinition = new ProjectDefinition(); // Load the attributes: "Enabled" and "Name"... projectDefinition.Id = int.Parse(projDefinition.Attribute(XName.Get(ID)).Value); projectDefinition.Enabled = bool.Parse(projDefinition.Attribute(XName.Get(ENABLED)).Value); // XSD should have validated input... projectDefinition.Name = projDefinition.Attribute(XName.Get(NAME)).Value; // Load the directories to "Include" and the directories to "Exclude"... XElement includeDirs = projDefinition.Descendants(PROJECT_DIRECTORIES).Descendants(PROJECT_INCLUDE).First(); XElement excludeDirs = projDefinition.Descendants(PROJECT_DIRECTORIES).Descendants(PROJECT_EXCLUDE).First(); projectDefinition.Directories.AddRange(LoadDirectoryDefinitions(includeDirs)); projectDefinition.ExcludedDirectories.AddRange(LoadDirectoryDefinitions(excludeDirs)); // Load the directories to "Include" and the directories to "Exclude"... XElement includeFiles = projDefinition.Descendants(PROJECT_FILES).Descendants(PROJECT_INCLUDE).First(); XElement excludeFiles = projDefinition.Descendants(PROJECT_FILES).Descendants(PROJECT_EXCLUDE).First(); projectDefinition.Files.AddRange(LoadFileDefinitions(includeFiles)); projectDefinition.ExcludedFiles.AddRange(LoadFileDefinitions(excludeFiles)); // Load the category definitions... foreach (XElement category in projDefinition.Descendants(PROJECT_CATEGORY)) { CategoryDefinition categoryDefinition = LoadCategoryDefinition(category); categoryDefinition.ParentDefinition = projectDefinition; projectDefinition.Categories.Add(categoryDefinition.CategoryDeclarationReferenceId, categoryDefinition); // Update 'Category Definition' statistics counters... ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalCategoryDefinitions); if (categoryDefinition.Enabled) ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.ActiveCategoryDefinitions); } Manager.Definitions.Projects.Add(projectDefinition.Id, projectDefinition); // Update 'Project Definition' statistics counters... ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalProjectDefinitions); if (projectDefinition.Enabled) ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.ActiveProjectDefinitions); } } }
// TODO Add token public CreateProjectMessage(ProjectDefinition projectDefinition) { ProjectDefinition = projectDefinition; }
private void LoadProjectDefinitions(XDocument doc) { lock (_lockConfigurationFile) { // Validate input... if (doc == null) { throw new ArgumentNullException("doc"); } List <IProjectDefinition> projectDefinitions = new List <IProjectDefinition>(); foreach (XElement projDefinition in doc.Descendants(PROJECT_DEFINITION)) { ProjectDefinition projectDefinition = new ProjectDefinition(); // Load the attributes: "Enabled" and "Name"... projectDefinition.Id = int.Parse(projDefinition.Attribute(XName.Get(ID)).Value); projectDefinition.Enabled = bool.Parse(projDefinition.Attribute(XName.Get(ENABLED)).Value); // XSD should have validated input... projectDefinition.Name = projDefinition.Attribute(XName.Get(NAME)).Value; // Load the directories to "Include" and the directories to "Exclude"... XElement includeDirs = projDefinition.Descendants(PROJECT_DIRECTORIES).Descendants(PROJECT_INCLUDE).First(); XElement excludeDirs = projDefinition.Descendants(PROJECT_DIRECTORIES).Descendants(PROJECT_EXCLUDE).First(); projectDefinition.Directories.AddRange(LoadDirectoryDefinitions(includeDirs)); projectDefinition.ExcludedDirectories.AddRange(LoadDirectoryDefinitions(excludeDirs)); // Load the directories to "Include" and the directories to "Exclude"... XElement includeFiles = projDefinition.Descendants(PROJECT_FILES).Descendants(PROJECT_INCLUDE).First(); XElement excludeFiles = projDefinition.Descendants(PROJECT_FILES).Descendants(PROJECT_EXCLUDE).First(); projectDefinition.Files.AddRange(LoadFileDefinitions(includeFiles)); projectDefinition.ExcludedFiles.AddRange(LoadFileDefinitions(excludeFiles)); // Load the category definitions... foreach (XElement category in projDefinition.Descendants(PROJECT_CATEGORY)) { CategoryDefinition categoryDefinition = LoadCategoryDefinition(category); categoryDefinition.ParentDefinition = projectDefinition; projectDefinition.Categories.Add(categoryDefinition.CategoryDeclarationReferenceId, categoryDefinition); // Update 'Category Definition' statistics counters... ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalCategoryDefinitions); if (categoryDefinition.Enabled) { ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.ActiveCategoryDefinitions); } } Manager.Definitions.Projects.Add(projectDefinition.Id, projectDefinition); // Update 'Project Definition' statistics counters... ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalProjectDefinitions); if (projectDefinition.Enabled) { ProxyHome.Instance.RetrieveStatisticsProxy(ConfigKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.ActiveProjectDefinitions); } } } }
bool StartConfig() { bool?success; // Preparation Step 1 - Config path to iS3 and data directory // ConfPathWindow mainWnd = new ConfPathWindow(); mainWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = mainWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } iS3Path = mainWnd.ExePath; dataPath = mainWnd.DataPath; // Preparation Step 2 - Config projects // string projListFile = dataPath + "\\ProjectList.xml"; ProjectList projList = ConfigCore.LoadProjectList(projListFile); ProjectsWindow projsWnd = new ProjectsWindow(projList); projsWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = projsWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } projID = projsWnd.ProjID; projLocX = projsWnd.ProjLocX; projLocY = projsWnd.ProjLocY; // Step 1 - Config project general definition // ProjectDefinition projDef = ConfigCore.LoadProjectDefinition(dataPath, projID); if (projDef == null) { projDef = ConfigCore.CreateProjectDefinition(dataPath, projID); } ProjGnrDefWindow projGnrDefWnd = new ProjGnrDefWindow(projDef); projGnrDefWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = projGnrDefWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } // Step 2 - Config engineering maps definition of the project // ProjEMapDefWindow projEMapsDefWnd = new ProjEMapDefWindow(projDef); projEMapsDefWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = projEMapsDefWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } //Step 3.3 -Config 3d map // Proj3DDefWindow proj3DDefWindow = new Proj3DDefWindow(projDef); success = proj3DDefWindow.ShowDialog(); if (success == null || success.Value == false) { return(false); } // Config 3D map // Note: Because there is nothing to configure for 3D, add "preview 3D model" in DomainDefWindow // //Proj3DViewDefWindow proj3DViewDefWnd = new Proj3DViewDefWindow(dataPath, projID); //proj3DViewDefWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; //success = proj3DViewDefWnd.ShowDialog(); //if (success == null || success.Value == false) //{ // return false; //} // Step 3 - Config domains of the project // List <EMapLayers> eMapLayersList = projEMapsDefWnd.EMapLayersList; UnityLayer unitylayer = proj3DDefWindow.unityLayer; Project prj = ConfigCore.LoadProject(dataPath, projID); DomainDefWindow domainDefWnd = new DomainDefWindow(projDef, prj, eMapLayersList, unitylayer); domainDefWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = domainDefWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } // Step 4 - Config project tree // ProjTreeDefWindow prjTreeDefWnd = new ProjTreeDefWindow(prj); prjTreeDefWnd.WindowStartupLocation = WindowStartupLocation.CenterScreen; success = prjTreeDefWnd.ShowDialog(); if (success == null || success.Value == false) { return(false); } // Write ProjectList.xml // ConfigCore.WriteProjectList(projListFile, projsWnd.ProjectList); // Write <projectID>.xml // ConfigCore.WriteProject(dataPath, projID, projDef, prj); // Write <projectID>.py // ConfigCore.WriteViewsDef(iS3Path, projID, projDef); string format = "Congratulations!\r\n" + "The following files has been generated successfully.\r\n" + " {0}\\ProjectList.xml\r\n" + " {1}\\{2}.xml\r\n" + " {3}\\IS3Py\\{4}.py\r\n" + "The {5} project is ready to use in iS3."; string str = string.Format(format, dataPath, dataPath, projID, iS3Path, projID, projID); MessageBox.Show(str, "Success", MessageBoxButton.OK); return(true); }
public async Task <IActionResult> Post([FromBody] ProjectDefinition projectDefinition) { if (projectDefinition is null) { throw new ArgumentNullException(nameof(projectDefinition)); } var validation = new ProjectDefinitionValidator().Validate(projectDefinition); if (!validation.IsValid) { return(ErrorResult .BadRequest(validation) .ActionResult()); } var users = await ResolveUsersAsync(projectDefinition) .ConfigureAwait(false); var nameExists = await projectsRepository .NameExistsAsync(projectDefinition.Name) .ConfigureAwait(false); if (nameExists) { return(ErrorResult .Conflict($"A Project with name '{projectDefinition.Name}' already exists. Project names must be unique. Please try your request again with a unique name.") .ActionResult()); } var project = new Project { Id = Guid.NewGuid(), Users = users, Name = projectDefinition.Name, Tags = projectDefinition.Tags }; if (!string.IsNullOrEmpty(projectDefinition.ProjectType)) { project.Type = await projectTypesRepository .GetAsync(projectDefinition.ProjectType) .ConfigureAwait(false); if (project.Type is null) { return(ErrorResult .BadRequest(new ValidationError { Field = "projectType", Message = $"A Project Type with the ID '{projectDefinition.ProjectType}' could not be found in this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'." }) .ActionResult()); } } else { project.Type = await projectTypesRepository .GetDefaultAsync() .ConfigureAwait(false); if (project.Type is null) { return(ErrorResult .BadRequest(new ValidationError { Field = "projectType", Message = $"No value was provided for 'projectType' and there is no a default Project Type set for this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'." }) .ActionResult()); } } var command = new OrchestratorProjectCreateCommand(CurrentUser, project); var commandResult = await orchestrator .InvokeAsync(command) .ConfigureAwait(false); if (commandResult.Links.TryGetValue("status", out var statusUrl)) { return(StatusResult .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus) .ActionResult()); } throw new Exception("This shouldn't happen, but we need to decide to do when it does."); }