示例#1
0
        public async Task <IActionResult> Delete(string id)
        {
            var query = new Loader <VisibleFile> {
                Id = id
            };
            await DataHandler.Execute(query);

            if (query.Result != null && AuthoriseWrite(query.Result))
            {
                var delete = new FileDelete {
                    CloudHandler = CloudHandler, File = query.Result
                };
                await LogicHandler.Execute(delete);

                if (delete.Result.Success)
                {
                    await DataHandler.Commit();

                    return(Ok(ConfirmViewModel.CreateSuccess(id)));
                }

                return(Ok(ConfirmViewModel.CreateFailure("Failed to delete file")));
            }

            return(Unauthorized());
        }
示例#2
0
        public async Task FileDeleteLogicDoc()
        {
            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new FakeApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var model = VisibleData.GetFirst();

            model.IsImage    = false;
            model.IsDocument = true;

            data.Result.Setup(m => m.Execute(It.IsAny <Delete <VisibleFile> >())).Returns(true);
            cloud.Result.Setup(m => m.Execute(It.IsAny <DeleteCmd>()))
            .Returns(ActionConfirm.CreateSuccess("File Loaded"));

            var command = new FileDelete
            {
                DataHandler  = data,
                File         = model,
                CloudHandler = cloud,
                LogicHandler = logic
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeTrue();

            data.HasExecuted.Should().BeTrue();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <Delete <VisibleFile> >()), Times.Once());
        }
示例#3
0
        public async Task FileDeleteLogicFail()
        {
            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new FakeApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var model = VisibleData.GetFirst();

            cloud.Result.Setup(m => m.Execute(It.IsAny <DeleteCmd>()))
            .Returns(ActionConfirm.CreateFailure(("Delete Failed")));

            var command = new FileDelete
            {
                DataHandler  = data,
                File         = model,
                CloudHandler = cloud,
                LogicHandler = logic
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeTrue();

            data.HasExecuted.Should().BeFalse();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <Delete <VisibleFile> >()), Times.Never());
        }
示例#4
0
        /*
         * Type:
         * 1 = Directory
         * 2 = File
         */
        private static String UpdateDeleteFilesBackup(UpdateGA update, FileDelete filedelete, String path, String pathFolder, int folderId, int type)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            String pathBackup          = context.Parameter.First().PathBackup;
            String pathBackupDirectory = "";
            String log     = "";
            String pathZip = "";

            try
            {
                if (!pathBackup.EndsWith("\\"))
                {
                    pathBackup += "\\";
                }
                pathZip     = pathBackup + update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\" + filedelete.Id + "\\";
                pathBackup += update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\Arquivos apagados - " + filedelete.Id + "\\Pasta - " + folderId + "\\";

                pathBackupDirectory = pathBackup.Substring(0, pathBackup.LastIndexOf("\\"));
                if (!pathBackupDirectory.EndsWith("\\"))
                {
                    pathBackupDirectory += "\\";
                }

                if (!System.IO.Directory.Exists(pathBackupDirectory))
                {
                    System.IO.Directory.CreateDirectory(pathBackupDirectory);
                }

                //Delete folder
                if (type == 1)
                {
                    String pathDestination = pathBackupDirectory + path.Replace(pathFolder, "");
                    CopyFolder(new System.IO.DirectoryInfo(path), new System.IO.DirectoryInfo(pathDestination));
                }
                //Delete file
                if (type == 2)
                {
                    String fileName        = path.Substring(path.LastIndexOf("\\") + 1);
                    String fileDestination = pathBackupDirectory + path.Replace(pathFolder, "");
                    String directory       = fileDestination.Substring(0, fileDestination.LastIndexOf("\\"));
                    if (!System.IO.Directory.Exists(directory))
                    {
                        System.IO.Directory.CreateDirectory(directory);
                    }
                    System.IO.File.Copy(path, fileDestination, true);
                }

                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Backup do arquivo " + path + " para " + pathBackup + " realizado.", 2, parameter);
            }
            catch (Exception error)
            {
                log = error.ToString();
                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Backup do arquivo " + path + " para " + pathBackup + " não realizado. Erro: " + log, 1, parameter);
            }

            return(log);
        }
示例#5
0
        public static String UpdateRemoveFiles(UpdateGA update, int fileDeleteId)
        {
            Models.GAContext context = new Models.GAContext();

            Parameter  parameter  = context.Parameter.FirstOrDefault();
            FileDelete filedelete = context.FileDelete.First(x => x.Id == fileDeleteId);
            List <FileDeleteFolder> fileDeleteFolders = context.FileDeleteFolder.Where(x => x.FileDeleteId == fileDeleteId).ToList();
            var    pathToDelete = filedelete.FilesDirectory.Replace("\n", "").Split('\r');
            String log          = "";

            try
            {
                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Procedimento - " + filedelete.Name, 2, parameter);

                foreach (FileDeleteFolder fileDeleteFolder in fileDeleteFolders)
                {
                    String pathDestination = context.Folder.First(x => x.Id == fileDeleteFolder.FolderId).Path;
                    if (!pathDestination.EndsWith("\\"))
                    {
                        pathDestination += "\\";
                    }
                    for (int i = 0; i < pathToDelete.Length; i++)
                    {
                        if (pathToDelete[i].Trim() == "")
                        {
                            continue;
                        }
                        String path = pathDestination + pathToDelete[i];
                        try
                        {
                            //1 = Directory
                            //2 = File
                            if (System.IO.File.GetAttributes(path).HasFlag(System.IO.FileAttributes.Directory))
                            {
                                UpdateDeleteFilesBackup(update, filedelete, path, pathDestination, fileDeleteFolder.FolderId, 1);
                                System.IO.Directory.Delete(path, true);
                            }
                            else
                            {
                                UpdateDeleteFilesBackup(update, filedelete, path, pathDestination, fileDeleteFolder.FolderId, 2);
                                System.IO.File.Delete(path);
                            }
                        }
                        catch
                        {
                            GALibrary.GALogs.SaveLogUpdate(update, "FileDelete", "Arquivo/Pasta - " + path + " não foi encontrado.", 1, parameter);
                            log += path + " não foi encontrado" + System.Environment.NewLine;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                log = error.ToString();
                GALibrary.GALogs.SaveLogUpdate(update, "FileDelete", "Arquivo/Pasta - " + filedelete.Id + " - " + log, 1, parameter);
            }

            return(log);
        }
        public void FileDelete_DoesNotExist_Succeeds()
        {
            var mockReader = Helper.GetMockReader(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1);
            var delFile    = new FileDelete();

            delFile.ReadXml(mockReader.Object);

            Assert.IsTrue(delFile.Run());
        }
示例#7
0
        public void GetStrings()
        {
            if (File.Exists(FileName))
            {
                FileDelete.DestroyFile(FileName);
            }

            var hashSet = new HashSet <string>(20_000_000);

            for (int i = 0; i < 256; i++)
            {
                hashSet.Add(i.ToString("D2"));
                hashSet.Add(i.ToString());
            }

            hashSet.UnionWith(new BuildPartsList().GetAllParts());

            hashSet.UnionWith(new BuildAcidEffects().GetAllAcidEffects());
            hashSet.UnionWith(new BuildAcidEmitters().GetAllAcidEmitters());
            hashSet.UnionWith(new BuildBrands().GetAllBrands());
            hashSet.UnionWith(new BuildCarsPartGroups().GetAllCarsPartGroups());
            hashSet.UnionWith(new BuildCarsSlotTypes().GetAllCarsSlotTypes());
            hashSet.UnionWith(new BuildCars().GetAllCars());
            hashSet.UnionWith(new BuildCarsPositionMarkers().GetAllCarsPositionMarkers());
            hashSet.UnionWith(new BuildFng().GetAllFng());
            hashSet.UnionWith(new BuildGCareers().GetAllGCarrers());
            hashSet.UnionWith(new BuildGlobal().GetAllGlobal());
            hashSet.UnionWith(new BuildLanguageLabels().GetAllLabels());
            hashSet.UnionWith(new BuildMaterials().GetAllMaterials());
            hashSet.UnionWith(new BuildPresetSkins().GetAllPresetSkins());
            hashSet.UnionWith(new BuildPresets().GetAllPresets());
            hashSet.UnionWith(new BuildStreamFiles().GetAllStreamFiles());
            hashSet.UnionWith(new BuildSunInfos().GetSunInfos());
            hashSet.UnionWith(new BuildTextures().GetAllTextures());
            hashSet.UnionWith(new BuildVlt().GetAllVlt());

            hashSet.UnionWith(new BuildFiles().GetAllFiles());

            //hashSet.UnionWith(new BuildPartsListOld().GetAllParts());

            try
            {
                using (var writer = new StreamWriter(FileName))
                {
                    foreach (var hashString in hashSet)
                    {
                        writer.Write($"{hashString}{Environment.NewLine}");
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show($"Failed to write to Hashes.txt. Error:{Environment.NewLine}{exp.Message}");
            }
        }
示例#8
0
        private String GetUpdateStepsString(List <UpdateSteps> steps)
        {
            String stepResult = "";

            foreach (UpdateSteps step in steps)
            {
                int order = step.Order + 1;
                try
                {
                    switch (step.Type)
                    {
                    case 1:
                        FileDelete fileDelete = _context.FileDelete.Find(step.ProcessId);
                        stepResult += order + " - Arquivos para apagar - " + "<a href = \"/filesDelete/Details/" + fileDelete.Id + "\" >" + fileDelete.Name + "</a>" + "<br />";
                        break;

                    case 2:
                        GALibrary.Models.File file = _context.File.Find(step.ProcessId);
                        stepResult += order + " - Arquivos para copiar - " + "<a href = \"/files/Details/" + file.Id + "\" >" + file.Name + "</a>" + "<br />";
                        break;

                    case 3:
                        Command command = _context.Command.Find(step.ProcessId);
                        stepResult += order + " - Comandos - " + "<a href = \"/commands/Details/" + command.Id + "\" >" + command.Name + "</a>" + "<br />";
                        break;

                    case 4:
                        Service serviceStart = _context.Service.Find(step.ProcessId);
                        stepResult += order + " - Serviço iniciar - " + "<a href = \"/services/Details/" + serviceStart.Id + "\" >" + serviceStart.Name + "</a>" + "<br />";
                        break;

                    case 5:
                        Service serviceStop = _context.Service.Find(step.ProcessId);
                        stepResult += order + " - Serviço parar - " + "<a href = \"/services/Details/" + serviceStop.Id + "\" >" + serviceStop.Name + "</a>" + "<br />";
                        break;

                    case 6:
                        SQL sql = _context.SQL.Find(step.ProcessId);
                        stepResult += order + " - SQL - " + "<a href = \"/sqls/Details/" + sql.Id + "\" >" + sql.Name + "</a>" + "<br />";
                        break;
                    }
                }
                catch
                {
                    stepResult += order + " - Processo apagado do banco" + "<br />";
                }
            }

            if (stepResult.Length > 6)
            {
                return(stepResult.Substring(0, stepResult.Length - 6));
            }

            return(stepResult);
        }
示例#9
0
        /// <summary>
        /// Delete multiple events in the same project.
        /// </summary>
        /// <param name="query">The list of events to delete.</param>
        /// <param name="token">Optional cancellation token.</param>
        /// <returns>Empty response.</returns>
        public async Task <EmptyResponse> DeleteAsync(FileDelete query, CancellationToken token = default)
        {
            if (query is null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var req = Oryx.Cognite.Files.delete <EmptyResponse>(query);

            return(await RunAsync(req, token).ConfigureAwait(false));
        }
示例#10
0
        public async Task AtualizaSteps(String[] updateProcessSelected, int updateGAId)
        {
            int i = 0;

            List <UpdateSteps> updateStepsList = new List <UpdateSteps>();

            foreach (String process in updateProcessSelected)
            {
                String[] option = process.Split('-');

                int type      = Convert.ToInt32(option[0].Trim());
                int processId = Convert.ToInt32(option[1].Trim());

                UpdateSteps updateSteps = new UpdateSteps();
                updateSteps.Order     = i;
                updateSteps.ProcessId = processId;
                updateSteps.Type      = type;
                updateSteps.UpdateId  = updateGAId;

                i++;

                //Caso seja anexado um arquivo para apagar, copiar ou um SQL desativa o mesmo para não aparecer mais na seleção.
                if (type == 1)
                {
                    FileDelete fileDelete = _context.FileDelete.Find(processId);
                    fileDelete.Enable = false;
                    _context.Update(fileDelete);
                    await _context.SaveChangesAsync();
                }
                if (type == 2)
                {
                    GALibrary.Models.File file = _context.File.Find(processId);
                    file.Enable = false;
                    _context.Update(file);
                    await _context.SaveChangesAsync();
                }

                if (type == 6)
                {
                    SQL sql = _context.SQL.Find(processId);
                    sql.Enable = false;
                    _context.Update(sql);
                    await _context.SaveChangesAsync();
                }

                updateStepsList.Add(updateSteps);
            }

            await _context.UpdateSteps.AddRangeAsync(updateStepsList);

            await _context.SaveChangesAsync();
        }
示例#11
0
        /// <summary>
        /// Delete multiple events in the same project.
        /// </summary>
        /// <param name="externalIds">The list of event externalids to delete.</param>
        /// <param name="token">Optional cancellation token.</param>
        public async Task <EmptyResponse> DeleteAsync(IEnumerable <string> externalIds, CancellationToken token = default)
        {
            if (externalIds is null)
            {
                throw new ArgumentNullException(nameof(externalIds));
            }

            var query = new FileDelete {
                Items = externalIds.Select(Identity.Create)
            };

            return(await DeleteAsync(query, token).ConfigureAwait(false));
        }
示例#12
0
        /// <summary>
        /// Delete multiple events in the same project.
        /// </summary>
        /// <param name="identities">The list of event ids to delete.</param>
        /// <param name="token">Optional cancellation token.</param>
        public async Task <EmptyResponse> DeleteAsync(IEnumerable <Identity> identities, CancellationToken token = default)
        {
            if (identities is null)
            {
                throw new ArgumentNullException(nameof(identities));
            }

            var query = new FileDelete {
                Items = identities
            };

            return(await DeleteAsync(query, token).ConfigureAwait(false));
        }
        public void FileDelete_Exists_Succeeds()
        {
            var cwd          = Environment.CurrentDirectory;
            var tempFileName = Guid.NewGuid().ToString();
            var tempFilePath = Path.Combine(cwd, tempFileName);
            var mockReader   = Helper.GetMockReader(tempFilePath, Guid.NewGuid().ToString(), 1);
            var delFile      = new FileDelete();

            delFile.ReadXml(mockReader.Object);
            File.WriteAllText(tempFilePath, "to be deleted");

            Assert.True(delFile.Run());
            Assert.True(!Directory.Exists(tempFilePath));
        }
示例#14
0
        public async Task <ActionResult> SalvaDados()
        {
            String status = "1";

            try
            {
                FileDelete fileDelete = new FileDelete();

                String name           = Request.Form["fileDeleteName"];
                String applicationId  = Request.Form["fileDeleteApplicationId"];
                String filesDirectory = Request.Form["filesDeleteDirectory"];
                String folders        = Request.Form["fileDeleteFolders"];

                fileDelete.Name           = name;
                fileDelete.ApplicationId  = Convert.ToInt32(applicationId);
                fileDelete.Date           = DateTime.Now;
                fileDelete.User           = User.Identity.Name;
                fileDelete.Enable         = true;
                fileDelete.FilesDirectory = Regex.Replace(filesDirectory, "(?<!\r)\n", "\r\n");

                if (ModelState.IsValid)
                {
                    _context.Add(fileDelete);
                    await _context.SaveChangesAsync();

                    _context.Entry(fileDelete).GetDatabaseValues();

                    List <FileDeleteFolder> fileDeleteFolderList = new List <FileDeleteFolder>();
                    foreach (String folder in folders.Trim().Split(" "))
                    {
                        FileDeleteFolder fileDeleteFolder = new FileDeleteFolder();
                        fileDeleteFolder.ApplicationId = fileDelete.ApplicationId;
                        fileDeleteFolder.FolderId      = Convert.ToInt32(folder);
                        fileDeleteFolder.FileDeleteId  = fileDelete.Id;
                        fileDeleteFolderList.Add(fileDeleteFolder);
                    }
                    _context.FileDeleteFolder.AddRange(fileDeleteFolderList);
                    await _context.SaveChangesAsync();

                    GALibrary.GALogs.SaveLog("FileDelete", "Fim do cadastro de arquivos para remover" + fileDelete.Name + " pelo usuario " + User.Identity.Name, 2, _context.Parameter.FirstOrDefault());
                }
            }
            catch (Exception erro) {
                GALibrary.GALogs.SaveLog("FileDelete", "Erro ao cadastrar arquivo para remover pelo usuario " + User.Identity.Name + ": " + erro.ToString(), 1, _context.Parameter.FirstOrDefault());
                status = erro.ToString();
            }

            return(Json(new { status = status }));
        }
示例#15
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,ApplicationId,FilesDirectory,User,Date,Enable")] FileDelete fileDelete, int[] FileDeleteFolderRight)
        {
            Boolean valida = true;

            if (id != fileDelete.Id)
            {
                return(NotFound());
            }

            try
            {
                fileDelete.Date = DateTime.Now;
                fileDelete.User = User.Identity.Name;

                if (FileDeleteFolderRight.Length == 0)
                {
                    valida             = false;
                    ViewBag.ErroPastas = "É necessário selecionar ao menos uma pasta, o status original foi restaurado";
                }

                if (ModelState.IsValid && valida)
                {
                    fileDelete.FilesDirectory = Regex.Replace(fileDelete.FilesDirectory, "(?<!\r)\n", "\r\n");
                    _context.Update(fileDelete);
                    await _context.SaveChangesAsync();

                    List <FileDeleteFolder> folderSavedList = _context.FileDeleteFolder.Where(x => x.FileDeleteId == fileDelete.Id).ToList();

                    if (FileDeleteFolderRight != null)
                    {
                        List <FileDeleteFolder> lista = new List <FileDeleteFolder>();
                        _context.FileDelete.Attach(fileDelete);
                        _context.Entry(fileDelete).Collection(x => x.FileDeleteFolder).Load();


                        foreach (int idFolder in FileDeleteFolderRight)
                        {
                            FileDeleteFolder fileDeletefolders = folderSavedList.Where(x => x.FolderId == idFolder).FirstOrDefault();
                            if (fileDeletefolders == null)
                            {
                                fileDeletefolders = new FileDeleteFolder();
                                fileDeletefolders.ApplicationId = fileDelete.ApplicationId;
                                fileDeletefolders.FileDeleteId  = fileDelete.Id;
                                fileDeletefolders.FolderId      = idFolder;
                            }
                            lista.Add(fileDeletefolders);
                        }

                        var apagar = fileDelete.FileDeleteFolder.Except(lista).ToList();
                        var novos  = lista.Except(fileDelete.FileDeleteFolder).ToList();

                        if (novos.Count != 0)
                        {
                            foreach (FileDeleteFolder fileDeleteFolders in novos)
                            {
                                _context.FileDeleteFolder.Add(fileDeleteFolders);
                            }
                        }

                        if (apagar.Count != 0)
                        {
                            foreach (FileDeleteFolder fileDeleteFolders in apagar)
                            {
                                _context.FileDeleteFolder.Remove(fileDeleteFolders);
                            }
                        }
                        _context.SaveChanges();
                    }

                    GALibrary.GALogs.SaveLog("FileDelete", "Fim da edicao do arquivo para apagar " + fileDelete.Name + " realizada pelo usuario " + User.Identity.Name, 2, _context.Parameter.FirstOrDefault());
                    return(RedirectToAction(nameof(Index)));
                }


                var folderIDs = _context.FileDeleteFolder.Where(x => x.FileDeleteId == id).Select(x => x.FolderId);

                ViewBag.FileDeleteFolderLeft  = new MultiSelectList(_context.Folder.Where(x => x.ApplicationId == fileDelete.ApplicationId && !folderIDs.Contains(x.Id)), "Id", "Path");
                ViewBag.FileDeleteFolderRight = new MultiSelectList(_context.Folder.Where(x => folderIDs.Contains(x.Id)), "Id", "Path");

                ViewBag.ApplicationIdFileDelete = new SelectList(_context.Application.Where(x => x.Enable).OrderBy(x => x.Name), "Id", "Name", fileDelete.ApplicationId);
                ViewBag.EnabledFileDelete       = new SelectList(new[] { new { ID = true, Name = "Sim" }, new { ID = false, Name = "Não" }, }, "ID", "Name", fileDelete.Enable);


                return(View(fileDelete));
            }
            catch (Exception erro)
            {
                GALibrary.GALogs.SaveLog("FileDelete", "Erro ao editar arquivo para apagar com id " + id + " pelo usuario " + User.Identity.Name + ": " + erro.ToString(), 1, _context.Parameter.FirstOrDefault());
                return(View("~/Views/Shared/Error.cshtml"));
            }
        }
示例#16
0
 public void Delete(FileDelete file)
 {
     api.Delete().With(file).Stream(repoPath + GetFilePath(file.Path, file.Branch), s => { });
 }
示例#17
0
 public Task DeleteAsync(FileDelete file)
 {
     return(api.Delete().With(file).StreamAsync(repoPath + GetFilePath(file.Path, file.Branch), s => Task.FromResult(0)));
 }
示例#18
0
 public void Delete(FileDelete file)
 {
     _api.Delete().With(file).Stream(_repoPath + "/files", s => { });
 }