Exemplo n.º 1
0
        private async Task SafeMoveFile(string source, string dest, string temp, bool copy)
        {
            string swapPath = null;

            try {
                if (copy)
                {
                    await _fileService.Copy(source, temp);
                }
                else
                {
                    await Task.Run(() => _fileService.Move(source, temp));
                }

                if (_fileService.FileExists(dest))
                {
                    swapPath = PathUtil.GetTempFilePath(dest);
                    _fileService.Move(dest, swapPath);
                }

                _fileService.Move(temp, dest);
            }
            finally {
                if (_fileService.FileExists(temp))
                {
                    _fileService.Delete(temp);
                }
                if (swapPath != null && _fileService.FileExists(swapPath) && _fileService.FileExists(dest))
                {
                    _fileService.Delete(swapPath);
                }
            }
        }
Exemplo n.º 2
0
 public async Task <IHttpActionResult> Delete(string fileName, string folder = "Published")
 {
     if (folder == "Published")
     {
         return(Ok(await _fileProvider.Delete(fileName, DirectoryEnum.Published)));
     }
     if (folder == "Uploaded")
     {
         return(Ok(await _fileProvider.Delete(fileName, DirectoryEnum.Uploaded)));
     }
     return(NotFound());
 }
Exemplo n.º 3
0
        public void Delete()
        {
            var fileName      = System.IO.Path.GetFileName(Path);
            var directoryEnum = Path.StartsWith(_fileProvider.UploadedFilesDirectory) ? DirectoryEnum.Uploaded : DirectoryEnum.Published;

            _fileProvider.Delete(fileName, directoryEnum).GetAwaiter().GetResult();
        }
Exemplo n.º 4
0
        public void Save(string filePath, IFileProvider fileProvider)
        {
            if (this.Config == null || !this.Config.HasData)
            {
                // empty config, removing file
                if (fileProvider.Exists(filePath))
                {
                    fileProvider.Delete(filePath);
                }
            }
            else
            {
                XmlSerializer serialiser = new XmlSerializer(typeof(RepoFolderXmlConfig));

                using (XmlTextWriter stream = new XmlTextWriter(
                           fileProvider.Open(filePath, FileMode.Create, FileAccess.Write)
                           , Encoding.UTF8))
                {
                    stream.Indentation = 1;
                    stream.IndentChar  = '\t';
                    stream.Formatting  = Formatting.Indented;
                    serialiser.Serialize(stream, this);
                }
            }
        }
Exemplo n.º 5
0
        public void FileProvider_Delete()
        {
            Setup.CreateEmptyFile(Constants.FilePath);

            FileProvider.Delete(Constants.FileName);

            Assert.IsFalse(Setup.FileExists(Constants.FilePath));
        }
        public async Task PutFileContent()
        {
            _service.EnsureAccess(_file.Path, FileAccess.Write);

            int start, finish, outOf;
            var etag = ETag.Create(_file);

            ValidateIfMatch();
            ValidateIfNoneMatch(etag);
            ValidateIfUnmodifiedSince();
            ValidateContentRange(out start, out finish, out outOf);

            string tempFilePath = CreateTempFile(_file.Path);

            try {
                using (var temp = _service.GetFileStream(tempFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) {
                    //
                    // Write to temp file
                    await _context.Request.Body.CopyToAsync(temp);

                    temp.Flush();
                    temp.Seek(0, SeekOrigin.Begin);

                    //
                    // Copy from temp
                    using (var real = TryOpenFile(_file.Path, FileMode.Open, FileAccess.Write, FileShare.Read)) {
                        if (start >= 0)
                        {
                            //
                            // Range request

                            int length = finish - start + 1;
                            real.Seek(start, SeekOrigin.Begin);
                        }

                        await temp.CopyToAsync(real);

                        if (finish > 0 && finish == outOf - 1)
                        {
                            real.SetLength(outOf);
                        }

                        //
                        // https://github.com/dotnet/corefx/blob/ec2a6190efa743ab600317f44d757433e44e859b/src/System.IO.FileSystem/src/System/IO/FileStream.Win32.cs#L1687
                        // Unlike Flush(), FlushAsync() always flushes to disk. This is intentional.
                        real.Flush();
                    }
                }
            }
            catch (IndexOutOfRangeException) {
                throw new ApiArgumentException(HeaderNames.ContentLength);
            }
            finally {
                _service.Delete(tempFilePath);
            }

            _context.Response.StatusCode = (int)HttpStatusCode.OK;
        }
Exemplo n.º 7
0
        private async Task SafeMoveFile(IFileInfo source, IFileInfo destination, string temp, bool copy)
        {
            IFileInfo swapInfo = null;
            IFileInfo tempInfo = _fileService.GetFile(temp);

            try {
                if (copy)
                {
                    await _fileService.Copy(source, tempInfo);
                }
                else
                {
                    await Task.Run(() => _fileService.Move(source, tempInfo));
                }

                if (destination.Exists)
                {
                    swapInfo = _fileService.GetFile(PathUtil.GetTempFilePath(destination.Path));
                    _fileService.Move(destination, swapInfo);
                }

                _fileService.Move(tempInfo, destination);
            }
            finally {
                // Refresh
                tempInfo = _fileService.GetFile(temp);
                if (swapInfo != null)
                {
                    swapInfo    = _fileService.GetFile(swapInfo.Path);
                    destination = _fileService.GetFile(destination.Path);
                }

                if (tempInfo.Exists)
                {
                    _fileService.Delete(tempInfo);
                }

                if (swapInfo != null && swapInfo.Exists && destination.Exists)
                {
                    _fileService.Delete(swapInfo);
                }
            }
        }
Exemplo n.º 8
0
 public static void Delete(string path)
 {
     if (_provider == null)
     {
         File.Delete(path);
     }
     else
     {
         _provider.Delete(path);
     }
 }
Exemplo n.º 9
0
        private void DeleteAllFilesInResultsDirectory(string testResultsFolder)
        {
            var files = _directoryProvider.GetFiles(testResultsFolder);

            foreach (var file in files)
            {
                if (_fileProvider.IsWithExtension(file, "trx"))
                {
                    _fileProvider.Delete(file);
                }
            }
        }
Exemplo n.º 10
0
        public IActionResult Delete(string id)
        {
            FileId fileId = FileId.FromUuid(id);

            IFileInfo info = _helper.GetExistingFileInfo(fileId.PhysicalPath);

            if (info != null)
            {
                _provider.Delete(info);
            }

            return(new NoContentResult());
        }
Exemplo n.º 11
0
 private void PrepareOutputFolder(string folderPath)
 {
     if (_fileProvider.DirectoryExists(folderPath))
     {
         foreach (var path in _fileProvider.EnumerateFiles(folderPath))
         {
             _fileProvider.Delete(path);
         }
     }
     else
     {
         _fileProvider.CreateDirectory(folderPath);
     }
 }
Exemplo n.º 12
0
        public async Task Close(bool deleteFile = false)
        {
            await _stream.FlushAsync();

            _stream.Close();
            if (deleteFile)
            {
                if (IsTranscoding)
                {
                    File.Delete(Path.Combine(VideoBufferDirectory, Path.GetFileName(FileName)));
                }
                else
                {
                    await _fileProvider.Delete(FileName, DirectoryEnum.Uploaded);
                }
            }
        }
        public IActionResult Delete(string id)
        {
            FileId fileId = FileId.FromUuid(id);

            if (_provider.FileExists(fileId.PhysicalPath) || _provider.DirectoryExists(fileId.PhysicalPath))
            {
                switch (FilesHelper.GetFileType(fileId.PhysicalPath))
                {
                case FileType.File:
                case FileType.Directory:
                    _provider.Delete(fileId.PhysicalPath);
                    break;

                default:
                    break;
                }
            }
            return(new NoContentResult());
        }
Exemplo n.º 14
0
        public bool Delete(string filename, string path = null)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                path = UserDirectory.Get();
            }

            if (string.IsNullOrWhiteSpace(filename))
            {
                Log.Logger().LogWarning("DELETE: FileName is missing");
                throw new NoFileNameException("DELETE: FileName is missing");
            }

            if (IsExist(filename, path))
            {
                var fullpath = PathProvider.Combine(path, filename);
                return(FileProvider.Delete(fullpath));
            }
            else
            {
                Log.Logger().LogWarning($"The file \"{filename}\" does not exist in the \"{path}\" directory");
                throw new FileExistException($"The file \"{filename}\" does not exist in the \"{path}\" directory");
            }
        }
Exemplo n.º 15
0
 public bool Delete(string fileName) =>
 _fileProvider.Delete(fileName);
Exemplo n.º 16
0
 public bool Delete(string fileName)
 {
     return(_fileProvider.Delete(fileName));
 }
Exemplo n.º 17
0
        public async Task <bool> ExecuteAsync(TestRunSettings testRunSettings)
        {
            if (!_pathProvider.IsFilePathValid(testRunSettings.ResultsFilePath))
            {
                throw new ArgumentException($"The specified test results file path is not valid. Specified path = {testRunSettings.ResultsFilePath}");
            }

            _pluginService.ExecuteAllTestRunnerPluginsPreTestRunLogic();

            await _testRunsCleanerServiceClient.DeleteOldTestRunsDataAsync();

            await _testCasesHistoryService.DeleteOlderTestCasesHistoryAsync();

            var activeTestAgents = await _testAgentService.GetAllActiveTestAgentsByTagAsync(testRunSettings.AgentTag);

            await _testAgentService.SetAllActiveAgentsToVerifyTheirStatusAsync(testRunSettings.AgentTag);

            await _testAgentService.WaitAllActiveAgentsToVerifyTheirStatusAsync(activeTestAgents);

            var availableTestAgents = await _testAgentService.GetAllActiveTestAgentsByTagAsync(testRunSettings.AgentTag);

            bool wasSuccessfulRun = false;

            if (availableTestAgents.Count > 0)
            {
                var tempFilePath = _pathProvider.GetTempFileName();
                _fileProvider.Delete(tempFilePath);
                _fileProvider.CreateZip(testRunSettings.OutputFilesLocation, tempFilePath);
                var zipData = _fileProvider.ReadAllBytes(tempFilePath);

                var testRunId = await _testRunProvider.CreateNewTestRunAsync(_pathProvider.GetFileName(testRunSettings.TestLibraryPath), zipData, testRunSettings.RetriesCount, testRunSettings.Threshold, testRunSettings.RunInParallel, testRunSettings.MaxParallelProcessesCount, testRunSettings.NativeArguments, testRunSettings.TestTechnology, testRunSettings.TimeBasedBalance, testRunSettings.CustomArguments);

                _testCasesProvider = _pluginService.GetNativeTestsRunnerTestCasesPluginService(testRunSettings.TestTechnology);
                var allTestCases      = _testCasesProvider.ExtractAllTestCasesFromTestLibrary(testRunSettings.TestLibraryPath);
                var filteredTestCases = _testCasesFilterService.FilterCases(allTestCases, testRunSettings.TestsFilter);

                var distributedTestsLists = testRunSettings.TimeBasedBalance ?
                                            await _testsTimesBasedDistributeService.GenerateDistributionListsAsync(availableTestAgents.Count, filteredTestCases) :
                                            _testCountsBasedDistributeService.GenerateDistributionLists(availableTestAgents.Count, filteredTestCases);

                var testAgentRuns = await _testAgentRunProvider.CreateNewTestAgentRunsAsync(testRunId, availableTestAgents, distributedTestsLists);

                try
                {
                    // TODO: pass ExecutionFrequency from args console?
                    await _testAgentRunProvider.WaitForTestAgentRunsToFinishAsync(testAgentRuns, testRunSettings.TestRunTimeout, ExecutionFrequency);

                    // DEBUG:
                    ////_consoleProvider.WriteLine("AFTER WaitForTestAgentRunsToFinishAsync");
                    _consoleProvider.WriteLine(TestAgentRunsHasFinished);
                }
                catch (TimeoutException)
                {
                    _consoleProvider.WriteLine(string.Format(TestRunHasTimedOut, testRunSettings.TestRunTimeout));
                    await _testAgentRunProvider.AbortAllTestAgentRunsInTestRunAsync(testRunId);
                }

                var areThereAbortedTestAgentRuns = await _testAgentRunProvider.AreThereAbortedTestAgentRunsAsync(testRunId);

                if (!areThereAbortedTestAgentRuns)
                {
                    // DEBUG:
                    ////_consoleProvider.WriteLine("START COMPLEETING TEST RUN");
                    await _testRunProvider.CompleteTestRunAsync(testRunId, TestRunStatus.Completed);

                    wasSuccessfulRun = true;

                    // DEBUG:
                    _consoleProvider.WriteLine("TEST RUN COMPLETED");
                    await _testResultsService.SaveTestResultsForCurrentRunAsync(testRunSettings.TestTechnology, testRunSettings.ResultsFilePath, testRunSettings.RetriedResultsFilePath, testRunId);

                    try
                    {
                        await _testRunsCleanerServiceClient.DeleteOldTestRunDataByTestRunIdAsync(testRunId);
                    }
                    catch (Exception e)
                    {
                        _consoleProvider.WriteLine(e.ToString());
                    }
                }
                else
                {
                    _consoleProvider.WriteLine("Test Run Aborted!");
                    await _testRunProvider.CompleteTestRunAsync(testRunId, TestRunStatus.Aborted);
                }
            }
            else
            {
                _consoleProvider.WriteLine(NoTestAgentsAreAvailable);
            }

            _pluginService.ExecuteAllTestRunnerPluginsPostTestRunLogic();

            return(wasSuccessfulRun);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Releases server resources for a session termination caused by either:
        /// Close-Session or Cancel-Session
        /// </summary>
        async Task <HttpResponseMessage> ReleaseResources(HttpRequestMessage request, CancellationToken cancellationToken, bool deleteFile = false)
        {
            HttpStatusCode      status_code = HttpStatusCode.OK;
            HttpResponseMessage response    = request.CreateResponse();

            response.Headers.Add(Bits.K_BITS_PACKET_TYPE, Bits.V_ACK);
            //response.Headers.Add(Bits.K_CONTENT_LENGTH, "0");

            try
            {
                string session_id = request.Headers.GetValues(Bits.K_BITS_SESSION_ID)?.First();
                if (string.IsNullOrEmpty(session_id))
                {
                    throw new NotSupportedException();
                }
                _traceManager.TraceDebug($"Closing BITS-Session-Id: {session_id}");

                if (Sessions.ContainsKey(session_id))
                {
                    await Sessions[session_id].Close(deleteFile);
                }
                else
                {
                    FileInfo fileInfo = new FileInfo(Path.Combine(BITSUploadSession.VideoBufferDirectory, session_id));
                    if (fileInfo.Exists)
                    {
                        fileInfo.Delete();
                    }
                    else
                    {
                        await _fileProvider.Delete(session_id, DirectoryEnum.Uploaded);
                    }
                }
                if (Sessions.ContainsKey(session_id) && Sessions[session_id].Move)
                {
                    if (Sessions[session_id].IsTranscoding)
                    {
                        Progress <double> progress = new Progress <double>();
                        CancellationToken ct       = CancellationToken.None;
                        var transcodeSession       = new TaskProgressObservable <bool>
                        {
                            Task              = TranscodeFileToFileProvider(Sessions[session_id], progress, ct),
                            Progress          = progress,
                            CancellationToken = ct
                        };
                        TranscodingSessions.Add($"TRANSCODED_{Path.GetFileName(Sessions[session_id].FileName)}", transcodeSession);
                    }
                    else
                    {
                        await _fileProvider.Complete(Sessions[session_id].FileName);
                    }
                }
                if (Sessions.ContainsKey(session_id))
                {
                    Sessions.Remove(session_id);
                }

                status_code = HttpStatusCode.OK;
            }
            catch (NotSupportedException)
            {
                return(SendResponse(response, HttpStatusCode.BadRequest));
            }
            catch (Exception e)
            {
                throw new Bits.ServerInternalError(e);
            }

            return(SendResponse(response, status_code));
        }
 public void Delete(IFileInfo info)
 {
     _next.Delete(info);
 }