public string SaveFile(IFormFile file, string path, string organizationId, string apiComponent, string binaryObjectId)
        {
            //save file to OpenBots.Server.Web/BinaryObjects/{organizationId}/{apiComponent}/{binaryObjectId}
            apiComponent = apiComponent ?? string.Empty;
            var target = Path.Combine(path, organizationId, apiComponent);

            if (!directoryManager.Exists(target))
            {
                directoryManager.CreateDirectory(target);
            }

            var filePath = Path.Combine(target, binaryObjectId);

            if (file.Length <= 0 || file.Equals(null))
            {
                return("No file exists.");
            }
            if (file.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                ConvertToBinaryObject(filePath);
            }
            return(binaryObjectId);
        }
Exemple #2
0
        public async Task Initialize(string workingDirectory, Version cdkVersion)
        {
            var packageJsonFileContent = _packageJsonGenerator.Generate(cdkVersion);
            var packageJsonFilePath    = Path.Combine(workingDirectory, _packageJsonFileName);

            try
            {
                if (!_directoryManager.Exists(workingDirectory))
                {
                    _directoryManager.CreateDirectory(workingDirectory);
                }

                await _fileManager.WriteAllTextAsync(packageJsonFilePath, packageJsonFileContent);
            }
            catch (Exception exception)
            {
                throw new PackageJsonFileException($"Failed to write {_packageJsonFileName} at {packageJsonFilePath}", exception);
            }

            try
            {
                // Install node packages specified in package.json file
                await _commandLineWrapper.Run("npm install", workingDirectory, false);
            }
            catch (Exception exception)
            {
                throw new NPMCommandFailedException($"Failed to install npm packages at {workingDirectory}", exception);
            }
        }
        public string CreateCdkProject(Recommendation recommendation, OrchestratorSession session, string?saveCdkDirectoryPath = null)
        {
            string?assemblyName;

            if (string.IsNullOrEmpty(saveCdkDirectoryPath))
            {
                saveCdkDirectoryPath =
                    Path.Combine(
                        Constants.CDK.ProjectsDirectory,
                        Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                assemblyName = recommendation.ProjectDefinition.AssemblyName;
            }
            else
            {
                assemblyName = _directoryManager.GetDirectoryInfo(saveCdkDirectoryPath).Name;
            }

            if (string.IsNullOrEmpty(assemblyName))
            {
                throw new ArgumentNullException("The assembly name for the CDK deployment project cannot be null");
            }

            _directoryManager.CreateDirectory(saveCdkDirectoryPath);

            var templateEngine = new TemplateEngine();

            templateEngine.GenerateCDKProjectFromTemplate(recommendation, session, saveCdkDirectoryPath, assemblyName);

            _interactiveService.LogDebugLine($"The CDK Project is saved at: {saveCdkDirectoryPath}");
            return(saveCdkDirectoryPath);
        }
Exemple #4
0
        public void CreateDirectory(string name, string path)
        {
            var directoryPath = CreateDirectoryPath(name, path);

            if (!_directoryManager.Exists(directoryPath))
            {
                _directoryManager.CreateDirectory(directoryPath);
            }
        }
Exemple #5
0
        public Test CreateTest(string author, string title, List <Question> questions)
        {
            Test test = new Test(title, author, questions);

            if (!dirMan.CreateDirectory(rootPath, author))
            {
                Console.WriteLine("Such user directory already exists!");
            }

            if (!dirMan.CreateDirectory(string.Concat(rootPath, @"\", author, @"\"), "madeTests"))
            {
                Console.WriteLine("Could Not Create a test file directory");
            }

            string testPath = string.Concat(rootPath, @"\", author, @"\", "madeTests", @"\", title);

            writeToFile(testPath, title, questions, true);
            return(new Test(title, author, questions));
        }
Exemple #6
0
        /// <summary>
        /// This method takes a path and creates a new directory at this path if one does not already exist.
        /// </summary>
        /// <param name="saveCdkDirectoryPath">Relative or absolute path of the directory at which the CDK deployment project will be saved.</param>
        /// <returns>A boolean to indicate if a new directory was created.</returns>
        private bool CreateSaveCdkDirectory(string saveCdkDirectoryPath)
        {
            var newDirectoryCreated = false;

            if (!_directoryManager.Exists(saveCdkDirectoryPath))
            {
                _directoryManager.CreateDirectory(saveCdkDirectoryPath);
                newDirectoryCreated = true;
            }
            return(newDirectoryCreated);
        }
Exemple #7
0
        public async Task <IActionResult> CreateDirectory(DirectoryFormViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(viewModel.DirectoryId == null ?
                       (IActionResult)View(!viewModel.IsPrivate ? "Public" : "Private", storageViewModel) : View("Directory", directoryViewModel.SetPrivate(viewModel.IsPrivate)));
            }

            return(await directoryManager.CreateDirectory(viewModel.DirectoryName, viewModel.DirectoryPath, isPrivate : viewModel.IsPrivate, parentDirectoryId : viewModel.DirectoryId) != null
                    ? (viewModel.DirectoryId == null ? (IActionResult)RedirectToAction(!viewModel.IsPrivate ? "Public" : "Private")
                        : RedirectToAction("Directory", new { id = viewModel.DirectoryId, isPrivate = viewModel.IsPrivate })).PushAlert("Directory has been created")
                    : (viewModel.DirectoryId == null ? (IActionResult)RedirectToAction(!viewModel.IsPrivate ? "Public" : "Private", storageViewModel)
                        : RedirectToAction("Directory", new { id = viewModel.DirectoryId, isPrivate = viewModel.IsPrivate })));
        }
Exemple #8
0
        private string CreateRepoRootDir(string usrRootDir, string reponame)
        {
            // by project convention, the root of all user repos is called "Repositories"

            string repoRootDir = Path.Combine(usrRootDir, "Repositories");

            // user do not have a repo root yet, create one first
            if (!_directoryManager.Exists(repoRootDir))
            {
                try
                {
                    _directoryManager.CreateDirectory(repoRootDir);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Failed creating root repo directory \"{usrRootDir}\". Exception: \"{ex.Message}\"");
                    return(null);
                }
            }

            string repoDir = Path.Combine(repoRootDir, reponame);

            if (!_directoryManager.Exists(repoDir))
            {
                try
                {
                    _directoryManager.CreateDirectory(repoDir);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Failed creating repo directory \"{repoDir}\". Exception: \"{ex.Message}\"");
                    return(null);
                }
            }

            return(repoDir);
        }
Exemple #9
0
        public async Task <string> CreateDotnetPublishZip(Recommendation recommendation)
        {
            _interactiveService.LogMessageLine(string.Empty);
            _interactiveService.LogMessageLine("Creating Dotnet Publish Zip file...");

            var publishDirectoryInfo = _directoryManager.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));
            var additionalArguments  = recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments;
            var runtimeArg           =
                recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild &&
                !additionalArguments.Contains("--runtime ") &&
                !additionalArguments.Contains("-r ")
                     ? "--runtime linux-x64"
                     : "";
            var publishCommand =
                $"dotnet publish \"{recommendation.ProjectPath}\"" +
                $" -o \"{publishDirectoryInfo}\"" +
                $" -c {recommendation.DeploymentBundle.DotnetPublishBuildConfiguration}" +
                $" {runtimeArg}" +
                $" {additionalArguments}";

            // Blazor applications do not build with the default of setting self-contained to false.
            // So only add the --self-contained true if the user explicitly sets it to true.
            if (recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild)
            {
                publishCommand += " --self-contained true";
            }

            var result = await _commandLineWrapper.TryRunWithResult(publishCommand, redirectIO : false);

            if (result.ExitCode != 0)
            {
                throw new DotnetPublishFailedException(result.StandardError);
            }

            var zipFilePath = $"{publishDirectoryInfo.FullName}.zip";
            await _zipFileManager.CreateFromDirectory(publishDirectoryInfo.FullName, zipFilePath);

            recommendation.DeploymentBundle.DotnetPublishZipPath         = zipFilePath;
            recommendation.DeploymentBundle.DotnetPublishOutputDirectory = publishDirectoryInfo.FullName;

            return(zipFilePath);
        }
Exemple #10
0
        private string CreateUserRootDir(string username)
        {
            string[] paths       = { _fileDirectoryOptions.Value.AppRootDirectory, username };
            string   userRootDir = Path.Combine(paths);

            if (_directoryManager.Exists(userRootDir))
            {
                _logger.LogError($"Failed creating directory for user \"{username}\", directory \"{userRootDir}\" already exists.");
                return(null);
            }

            try
            {
                _directoryManager.CreateDirectory(userRootDir);
            }
            catch (Exception ex)
            {
                _logger.LogError($"\nFailed creating directory for user \"{username}\", exception message: \"{ex.Message}\"");
                return(null);
            }

            return(userRootDir);
        }
Exemple #11
0
        public async Task UpdateDeploymentManifestFile()
        {
            // Arrange
            var saveCdkDirectoryFullPath  = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp");
            var saveCdkDirectoryFullPath2 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp2");
            var saveCdkDirectoryFullPath3 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp3");

            _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath);
            _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath2);
            _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath3);

            var saveCdkDirectoryRelativePath  = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath);
            var saveCdkDirectoryRelativePath2 = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath2);
            var saveCdkDirectoryRelativePath3 = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath3);

            var deploymentManifestFilePath = Path.Combine(_targetApplicationDirectoryFullPath, "aws-deployments.json");

            // Act
            await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath, _targetApplicationFullPath);

            // Assert
            Assert.True(_fileManager.Exists(deploymentManifestFilePath));
            var deploymentProjectPaths = await GetDeploymentManifestEntries(deploymentManifestFilePath);

            Assert.Single(deploymentProjectPaths);
            deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath);

            // Update deployment-manifest file
            await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath2, _targetApplicationFullPath);

            await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath3, _targetApplicationFullPath);

            // Assert
            Assert.True(_fileManager.Exists(deploymentManifestFilePath));
            deploymentProjectPaths = await GetDeploymentManifestEntries(deploymentManifestFilePath);

            Assert.Equal(3, deploymentProjectPaths.Count);
            deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath);
            deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath2);
            deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath3);

            // cleanup
            File.Delete(deploymentManifestFilePath);
            Assert.False(_fileManager.Exists(deploymentManifestFilePath));
        }
Exemple #12
0
        public async Task<JsonResult> SaveDecesionAsync(DecesionViewModel decesionViewModel)
        {
            try
            {
                ModelState.Remove("Decesion.DecesionStatusType");
                if (!ModelState.IsValid && decesionViewModel.Decesion.DecesionTarget.ID != 0 || decesionViewModel == null)
                {
                    ModelState.AddModelError("", "Дані введені неправильно");
                    return Json(new { success = false, text = ModelState.Values.SelectMany(v => v.Errors), model = decesionViewModel, modelstate = ModelState });
                }

                if (decesionViewModel.File != null && decesionViewModel.File.Length > 10485760)
                {
                    ModelState.AddModelError("", "файл за великий (більше 10 Мб)");
                    return Json(new { success = false, text = "file lenght > 10485760" });
                }

                decesionViewModel.Decesion.HaveFile = decesionViewModel.File != null ? true : false;

                _repoWrapper.Decesion.Attach(decesionViewModel.Decesion);
                _repoWrapper.Decesion.Create(decesionViewModel.Decesion);
                _repoWrapper.Save();

                if (decesionViewModel.Decesion.HaveFile)
                {
                    try
                    {
                        string path = _appEnvironment.WebRootPath + DecesionsDocumentFolder + decesionViewModel.Decesion.ID;
                        _directoryManager.CreateDirectory(path);

                        if (!_directoryManager.Exists(path))
                        {
                            throw new ArgumentException($"directory '{path}' is not exist");
                        }

                        if (decesionViewModel.File != null)
                        {
                            path = Path.Combine(path, decesionViewModel.File.FileName);

                            using (var stream = _fileStreamManager.GenerateFileStreamManager(path, FileMode.Create))
                            {
                                await _fileStreamManager.CopyToAsync(decesionViewModel.File, stream.GetStream());
                                if (!_fileManager.Exists(path))
                                {
                                    throw new ArgumentException($"File was not created it '{path}' directory");
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        return Json(new { success = false, text = e.Message });
                    }
                }
                return Json(new
                {
                    success = true,
                    Text = "Рішення додано!",
                    decesion = decesionViewModel.Decesion,
                    decesionOrganization = _repoWrapper.Organization.FindByCondition(x => x.ID == decesionViewModel.Decesion.Organization.ID).Select(x => x.OrganizationName)
                });
            }
            catch (Exception e)
            {
                return Json(new
                {
                    success = false,
                    text = e.Message
                });
            }
        }