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);
        }
Esempio n. 2
0
        /// <summary>
        /// This method takes the path to the target deployment project and creates
        /// a default save directory inside the parent folder of the current directory.
        /// For example:
        /// Target project directory - C:\Codebase\MyWebApp
        /// Generated default save directory - C:\Codebase\MyWebAppCDK If the save directory already exists, then a suffix number is attached.
        /// </summary>
        /// <returns>The defaukt save directory path.</returns>
        private string GenerateDefaultSaveDirectoryPath()
        {
            var applicatonDirectoryFullPath = _directoryManager.GetDirectoryInfo(_targetApplicationFullPath).Parent.FullName;
            var saveCdkDirectoryFullPath    = applicatonDirectoryFullPath + "CDK";

            var suffixNumber = 0;

            while (_directoryManager.Exists(saveCdkDirectoryFullPath))
            {
                saveCdkDirectoryFullPath = applicatonDirectoryFullPath + $"CDK{++suffixNumber}";
            }

            return(saveCdkDirectoryFullPath);
        }
Esempio n. 3
0
        private string DetermineCloudFormationTemplatePath(string projectRootDirectory)
        {
            if (!_directoryManager.Exists(projectRootDirectory))
            {
                throw new DirectoryNotFoundException("Failed to find the project root directory");
            }

            var templateAbsolutePath = string.Empty;

            var defaultConfigFile = _directoryManager.GetFiles(projectRootDirectory, "aws-lambda-tools-defaults.json", SearchOption.AllDirectories)
                                    .FirstOrDefault();

            if (_fileManager.Exists(defaultConfigFile))
            {
                // the templateAbsolutePath will be empty if the template property is not found in the default config file
                templateAbsolutePath = GetTemplatePathFromDefaultConfigFile(defaultConfigFile);
            }

            // if the default config file does not exist or if the template property is not found in the default config file
            // set the template path inside the project root directory.
            if (string.IsNullOrEmpty(templateAbsolutePath))
            {
                templateAbsolutePath = Path.Combine(projectRootDirectory, "serverless.template");
            }

            return(templateAbsolutePath);
        }
Esempio n. 4
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);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// This method updates the deployment manifest json file by adding the directory path at which the CDK deployment project is saved.
        /// If the manifest file does not exists then a new file is generated.
        /// <param name="saveCdkDirectoryFullPath">The absolute path to the directory at which the CDK deployment project is saved</param>
        /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file.</param>
        /// <exception cref="FailedToUpdateDeploymentManifestFileException">Thrown if an error occured while trying to update the deployment manifest file.</exception>
        /// </summary>
        /// <returns></returns>
        public async Task UpdateDeploymentManifestFile(string saveCdkDirectoryFullPath, string targetApplicationFullPath)
        {
            try
            {
                if (!_directoryManager.Exists(saveCdkDirectoryFullPath))
                {
                    return;
                }

                var deploymentManifestFilePath     = GetDeploymentManifestFilePath(targetApplicationFullPath);
                var targetApplicationDirectoryPath = _directoryManager.GetDirectoryInfo(targetApplicationFullPath).Parent.FullName;
                var saveCdkDirectoryRelativePath   = _directoryManager.GetRelativePath(targetApplicationDirectoryPath, saveCdkDirectoryFullPath);

                DeploymentManifestModel deploymentManifestModel;

                if (_fileManager.Exists(deploymentManifestFilePath))
                {
                    deploymentManifestModel = await ReadManifestFile(deploymentManifestFilePath);

                    if (deploymentManifestModel.DeploymentProjects == null)
                    {
                        deploymentManifestModel.DeploymentProjects = new List <DeploymentManifestEntry> {
                            new DeploymentManifestEntry(saveCdkDirectoryRelativePath)
                        };
                    }
                    else
                    {
                        deploymentManifestModel.DeploymentProjects.Add(new DeploymentManifestEntry(saveCdkDirectoryRelativePath));
                    }
                }
                else
                {
                    var deploymentManifestEntries = new List <DeploymentManifestEntry> {
                        new DeploymentManifestEntry(saveCdkDirectoryRelativePath)
                    };
                    deploymentManifestModel = new DeploymentManifestModel(deploymentManifestEntries);
                }

                var manifestFileJsonString = SerializeManifestModel(deploymentManifestModel);
                await _fileManager.WriteAllTextAsync(deploymentManifestFilePath, manifestFileJsonString);
            }
            catch (Exception ex)
            {
                throw new FailedToUpdateDeploymentManifestFileException($"Failed to update the deployment manifest file " +
                                                                        $"for the deployment project stored at '{saveCdkDirectoryFullPath}'", ex);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// This method parses the target application project and sets the
        /// appropriate metadata as part of the <see cref="ProjectDefinition"/>
        /// </summary>
        /// <param name="projectPath">The project path can be an absolute or a relative path to the
        /// target application project directory or the application project file.</param>
        /// <returns><see cref="ProjectDefinition"/></returns>
        public async Task <ProjectDefinition> Parse(string projectPath)
        {
            if (_directoryManager.Exists(projectPath))
            {
                projectPath = _directoryManager.GetDirectoryInfo(projectPath).FullName;
                var files = _directoryManager.GetFiles(projectPath, "*.csproj");
                if (files.Length == 1)
                {
                    projectPath = Path.Combine(projectPath, files[0]);
                }
                else if (files.Length == 0)
                {
                    files = _directoryManager.GetFiles(projectPath, "*.fsproj");
                    if (files.Length == 1)
                    {
                        projectPath = Path.Combine(projectPath, files[0]);
                    }
                }
            }

            if (!_fileManager.Exists(projectPath))
            {
                throw new ProjectFileNotFoundException(projectPath);
            }

            var xmlProjectFile = new XmlDocument();

            xmlProjectFile.LoadXml(await _fileManager.ReadAllTextAsync(projectPath));

            var projectDefinition = new ProjectDefinition(
                xmlProjectFile,
                projectPath,
                await GetProjectSolutionFile(projectPath),
                xmlProjectFile.DocumentElement?.Attributes["Sdk"]?.Value ??
                throw new InvalidProjectDefinitionException(
                    "The project file that is being referenced does not contain and 'Sdk' attribute.")
                );

            var targetFramework = xmlProjectFile.GetElementsByTagName("TargetFramework");

            if (targetFramework.Count > 0)
            {
                projectDefinition.TargetFramework = targetFramework[0]?.InnerText;
            }

            var assemblyName = xmlProjectFile.GetElementsByTagName("AssemblyName");

            if (assemblyName.Count > 0)
            {
                projectDefinition.AssemblyName = (string.IsNullOrWhiteSpace(assemblyName[0]?.InnerText) ? Path.GetFileNameWithoutExtension(projectPath) : assemblyName[0]?.InnerText);
            }
            else
            {
                projectDefinition.AssemblyName = Path.GetFileNameWithoutExtension(projectPath);
            }

            return(projectDefinition);
        }
Esempio n. 7
0
        public void CreateDirectory(string name, string path)
        {
            var directoryPath = CreateDirectoryPath(name, path);

            if (!_directoryManager.Exists(directoryPath))
            {
                _directoryManager.CreateDirectory(directoryPath);
            }
        }
 private string ValidateExecutionDirectory(string executionDirectory)
 {
     if (!string.IsNullOrEmpty(executionDirectory) && !_directoryManager.Exists(executionDirectory))
     {
         return("The directory specified for Docker execution does not exist.");
     }
     else
     {
         return("");
     }
 }
Esempio n. 9
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);
        }
Esempio n. 10
0
        private async Task CreateDeploymentBundle(Orchestrator orchestrator, Recommendation selectedRecommendation, CloudApplication cloudApplication)
        {
            if (selectedRecommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.Container)
            {
                while (!await orchestrator.CreateContainerDeploymentBundle(cloudApplication, selectedRecommendation))
                {
                    if (_toolInteractiveService.DisableInteractive)
                    {
                        var errorMessage = "Failed to build Docker Image." + Environment.NewLine;
                        errorMessage += "Docker builds usually fail due to executing them from a working directory that is incompatible with the Dockerfile." + Environment.NewLine;
                        errorMessage += "Specify a valid Docker execution directory as part of the deployment settings file and try again.";
                        throw new DockerBuildFailedException(errorMessage);
                    }

                    _toolInteractiveService.WriteLine(string.Empty);
                    var answer = _consoleUtilities.AskYesNoQuestion("Do you want to go back and modify the current configuration?", "false");
                    if (answer == YesNo.Yes)
                    {
                        var dockerExecutionDirectory =
                            _consoleUtilities.AskUserForValue(
                                "Enter the docker execution directory where the docker build command will be executed from:",
                                selectedRecommendation.DeploymentBundle.DockerExecutionDirectory,
                                allowEmpty: true);

                        if (!_directoryManager.Exists(dockerExecutionDirectory))
                        {
                            continue;
                        }

                        selectedRecommendation.DeploymentBundle.DockerExecutionDirectory = dockerExecutionDirectory;
                    }
                    else
                    {
                        throw new FailedToCreateDeploymentBundleException("Failed to create a deployment bundle");
                    }
                }
            }
            else if (selectedRecommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.DotnetPublishZipFile)
            {
                var dotnetPublishDeploymentBundleResult = await orchestrator.CreateDotnetPublishDeploymentBundle(selectedRecommendation);

                if (!dotnetPublishDeploymentBundleResult)
                {
                    throw new FailedToCreateDeploymentBundleException("Failed to create a deployment bundle");
                }
            }
        }
        /// <summary>
        /// This method takes a root directory path and recursively searches all its sub-directories for custom recipe paths.
        /// However, it ignores any recipe file located inside a "bin" folder.
        /// </summary>
        /// <param name="rootDirectoryPath">The absolute path of the root directory.</param>
        /// <returns>A list of recipe definition paths.</returns>
        private List <string> GetRecipePathsFromRootDirectory(string?rootDirectoryPath)
        {
            var recipePaths = new List <string>();

            if (!string.IsNullOrEmpty(rootDirectoryPath) && _directoryManager.Exists(rootDirectoryPath))
            {
                foreach (var recipeFilePath in _directoryManager.GetFiles(rootDirectoryPath, "*.recipe", SearchOption.AllDirectories))
                {
                    if (recipeFilePath.Contains(_ignorePathSubstring))
                    {
                        continue;
                    }
                    recipePaths.Add(_directoryManager.GetDirectoryInfo(recipeFilePath).Parent.FullName);
                }
            }
            return(recipePaths);
        }
Esempio n. 12
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);
        }
Esempio n. 13
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
                });
            }
        }