Ejemplo n.º 1
0
        private async Task <FileInfo> InstallUpdater(UpdatePackageData pkgData)
        {
            var updaterExecutable = this.locator.GetUpdater(this.programInfo);

            if (pkgData == null)
            {
                return(updaterExecutable);
            }

            FileDownloadResult result = await this.messenger.DownloadFile(pkgData.DownloadUrl).ConfigureAwait(false);

            FileInfo pkgFile = this.locator.GetInstallerPackagePath(result);

            if (pkgFile.Exists)
            {
                pkgFile.Delete();
            }

            try
            {
                await SaveStreamToPath(pkgData, pkgFile, result.Stream).ConfigureAwait(false);
            }
            catch (IOException)
            {
            }
            await this.updateInstaller.InstallUpdaterUpdate(pkgFile, updaterExecutable).ConfigureAwait(false);

            return(updaterExecutable);
        }
Ejemplo n.º 2
0
        public async Task DownloadPackageFileToDiskAsyncWithSasDefinition()
        {
            _fileStorageService
            .Setup(x => x.GetFileUriAsync(
                       _packagesContainerName,
                       _packageFileName))
            .ReturnsAsync(_testUri)
            .Verifiable();

            _packageDownloader
            .Setup(x => x.DownloadAsync(_testSasUri, CancellationToken.None))
            .ReturnsAsync(() => FileDownloadResult.Ok(_packageStream))
            .Verifiable();

            var validationSet = new PackageValidationSet()
            {
                PackageNormalizedVersion = _package.NormalizedVersion,
                PackageKey = _package.Key,
                PackageId  = _package.PackageRegistration.Id
            };

            var actual = await _target.DownloadPackageFileToDiskAsync(validationSet, _sasDefinition);

            Assert.Same(_packageStream, actual);
            _fileStorageService.Verify();
            _packageDownloader.Verify();
            _sasService.Verify();
        }
Ejemplo n.º 3
0
        public async Task DownloadFile_WhenInvoked_ResultIsSuccessAndContainsDownloadData()
        {
            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.True);
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 4
0
        public static bool Sync()
        {
            if (!System.Threading.Monitor.TryEnter(_lock))
            {
                //Already syncing, return when on-going sync is done
                lock (_lock) {
                    return(true);
                }
            }
            else
            {
                try {
                    InteropEmu.DisplayMessage("GoogleDrive", "SynchronizationStarted");
                    using (_accessor = new GoogleDriveAccessor()) {
                        FileDownloadResult result = CloudSyncHelper.DownloadData();
                        if (result == FileDownloadResult.Error)
                        {
                            InteropEmu.DisplayMessage("GoogleDrive", "SynchronizationFailed");
                            return(false);
                        }

                        CloudSyncHelper.UploadData();
                        InteropEmu.DisplayMessage("GoogleDrive", "SynchronizationCompleted");
                        ConfigManager.Config.PreferenceInfo.CloudLastSync = DateTime.Now;
                        ConfigManager.ApplyChanges();

                        return(true);
                    }
                } finally {
                    System.Threading.Monitor.Exit(_lock);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <IList <ImportResult> > PerformImport()
        {
            IList <ImportResult> results = new List <ImportResult>();

            //clean the files
            await CleanEnvironment();

            //Download the zipfile
            FileDownloadResult downloadResult =
                await FileDownloadUtilities.DownloadFile(new Uri(Path.Combine(CsvImportSettings.FtpSource, CsvImportSettings.FacZipFilename)),
                                                         CsvImportSettings.LocalImportDirectory);

            if (downloadResult.Success)
            {
                ZipUtility.UnZipFile(downloadResult.LocalFilePath, downloadResult.TargetDirectory);

                results.Add(await PassthroughImporter.Import());
                results.Add(await FormattedFindingsTextImporter.Import());
                results.Add(await FormattedCapTextImporter.Import());
                results.Add(await FindingTextImporter.Import());
                results.Add(await FindingImporter.Import());
                results.Add(await EinImporter.Import());
                results.Add(await DunImporter.Import());
                results.Add(await CpaImporter.Import());
                results.Add(await CapTextImporter.Import());
                results.Add(await AgencyImporter.Import());
                results.Add(await GeneralImporter.Import());
                results.Add(await CfdaImporter.Import());
            }

            return(results);
        }
Ejemplo n.º 6
0
        public void downloadFile()
        {
            string             fileId = "F8213DA8A1D62B0B7A517D1B15429DE1AD12A0DF40009CDBD2F8F1064FAB90BBA536CAA735816A3658533C56B8E6877BB0A9FAE96F48A9E7E71143DCF61C7CD4";
            FileDownloadResult result = client.DownloadFile(fileId).GetAwaiter().GetResult();

            Assert.AreEqual(0, result.error_code, result.error_message);
        }
Ejemplo n.º 7
0
        public void downloadSharedFile()
        {
            string             fileId = "00EF5A9502FA1C4CD327CFE524AF419D64E9DEA93EF2F04D40B919AA8E8BF5CF87922161995344F40FA0E95656D5636C59F07B9E92FEEAB1E358F7DB4F835F8F";
            FileDownloadResult result = client.DownloadSharedFile(fileId).GetAwaiter().GetResult();

            Assert.AreEqual(0, result.error_code, result.error_message);
        }
Ejemplo n.º 8
0
        public async Task TestDownloadFileSuccess()
        {
            string downloadDir = Path.GetTempPath();

            Uri source = new Uri("https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf");

            IFileDownloadUtilities fileDownloadUtilities = new FileDownloadUtilities();

            FileDownloadResult result = await fileDownloadUtilities.DownloadFile(source, downloadDir);

            Assert.IsTrue(result.Success);
            Assert.IsNotNull(result.Source);
            Assert.IsTrue(!String.IsNullOrEmpty(result.TargetDirectory));
            Assert.IsTrue(!String.IsNullOrEmpty(result.LocalFilePath));
            Assert.IsTrue(!String.IsNullOrEmpty(result.Filename));
            Assert.IsTrue(!String.IsNullOrEmpty(result.MimeType));
            Assert.Greater(result.FileSize, 0);
            Assert.IsNotNull(result.DownloadTime);
            Assert.IsNull(result.ErrorDetail);

            //Clean up the file
            File.Delete(result.LocalFilePath);

            Assert.IsFalse(File.Exists(result.LocalFilePath));
        }
Ejemplo n.º 9
0
        public void Cleanup(FileDownloadResult fileDownloadResult)
        {
            FilePayload filePayload = fileDownloadResult.FilePayload;

            string downloadFilePath             = filePayload.DownloadFilePath;
            string decompressedDownloadFilePath = filePayload.DecompressedDownloadFilePath;
            string failedDownloadFilePath       = filePayload.FailedDownloadFilePath;

            LogVerbose($"{nameof(Cleanup)} Invoked");

            if (Exists(decompressedDownloadFilePath))
            {
                LogVerbose($"Deleting: {decompressedDownloadFilePath}");
                Delete(decompressedDownloadFilePath);
            }

            if (Exists(downloadFilePath))
            {
                if (fileDownloadResult.FailedReason == FailedReason.FileDownloadFailedDecompression)
                {
                    LogVerbose($"Moving: {downloadFilePath} to {failedDownloadFilePath}");
                    Move(downloadFilePath, failedDownloadFilePath);
                }
                else
                {
                    LogVerbose($"Deleting: {downloadFilePath}");
                    Delete(downloadFilePath);
                }
            }
        }
            public async Task VerifiesTheDownloadedStream()
            {
                // Arrange
                var stream = TestResources.GetResourceStream(TestResources.SignedPackageLeaf1);

                _packageDownloader
                .Setup(x => x.DownloadAsync(_message.NupkgUri, It.IsAny <CancellationToken>()))
                .ReturnsAsync(() => FileDownloadResult.Ok(stream));

                // Act
                var success = await _target.HandleAsync(_message);

                // Assert
                Assert.True(success, "The handler should have succeeded processing the message.");
                _signatureValidator.Verify(
                    x => x.ValidateAsync(
                        _validation.PackageKey,
                        stream,
                        _message,
                        CancellationToken.None),
                    Times.Once);
                _signatureValidator.Verify(
                    x => x.ValidateAsync(
                        It.IsAny <int>(),
                        It.IsAny <Stream>(),
                        It.IsAny <SignatureValidationMessage>(),
                        It.IsAny <CancellationToken>()),
                    Times.Once);
            }
Ejemplo n.º 11
0
        /// <summary>
        /// Download given file id from Telegram server and save it in physical path
        /// </summary>
        /// <param name="fileId">File id that must download</param>
        /// <param name="savePath">Path that file must save on it</param>
        /// <returns>Determine operation compelete successfully or not</returns>
        public FileDownloadResult DownloadFileById(string fileId, string savePath)
        {
            if (string.IsNullOrEmpty(fileId))
            {
                throw new ArgumentNullException(nameof(fileId));
            }

            if (string.IsNullOrEmpty(savePath))
            {
                throw new ArgumentNullException(nameof(savePath));
            }

            try
            {
                FileDownloadResult fileDownload = DownloadFileById(fileId);

                if (fileDownload == null)
                {
                    return(null);
                }

                string filePath = Path.Combine(savePath, fileId) + fileDownload.FileExtension;
                System.IO.File.WriteAllBytes(filePath, fileDownload.Buffer);

                return(fileDownload);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 12
0
        public async Task DownloadFile_WhenFileDownloadTimeout_SendsEmail()
        {
            SetUpFileDownloadTimeout();

            FileDownloadResult actual = await InvokeDownloadFile();

            fileDownloadEmailServiceMock.Received().SendEmail(actual);
        }
Ejemplo n.º 13
0
        public async Task DownloadFile_WhenDataStoreIsNotAvailable_SendsEmail()
        {
            SetUpWhenDataStoreIsNotAvailable();

            FileDownloadResult actual = await InvokeDownloadFile();

            fileDownloadEmailServiceMock.Received().SendEmail(actual);
        }
Ejemplo n.º 14
0
        public async Task DownloadFile_WhenMinimumWaitTimeNotMet_SendsEmail()
        {
            SetUpWhenMinimumWaitTimeNotMet();

            FileDownloadResult actual = await InvokeDownloadFile();

            fileDownloadEmailServiceMock.Received().SendEmail(actual);
        }
Ejemplo n.º 15
0
        public async Task DownloadFile_WhenFileDownloadFails_ResourceCleanupInvoked()
        {
            SetUpFileDownloadFails();

            FileDownloadResult actual = await InvokeDownloadFile();

            resourceCleanupServiceMock.Received().Cleanup(actual);
        }
Ejemplo n.º 16
0
        public async Task DownloadFile_WhenExceptionThrown_SendsEmail()
        {
            SetUpWhenExceptionThrown();

            FileDownloadResult actual = await InvokeDownloadFile();

            fileDownloadEmailServiceMock.Received().SendEmail(actual);
        }
Ejemplo n.º 17
0
        public void SendEmail(FileDownloadResult fileDownloadResult)
        {
            FailedReason failedReason = fileDownloadResult.FailedReason;

            string errorMessage = errorMessageService.GetErrorMessage(failedReason, fileDownloadResult.FilePayload,
                                                                      StatsDownloadService.FileDownload);

            SendEmail(FileDownloadFailedSubject, errorMessage);
        }
        public void CleanUp_WhenFileDownloadFailedDecompression_MovesDownloadFile()
        {
            fileDownloadResult = new FileDownloadResult(FailedReason.FileDownloadFailedDecompression, filePayload);

            systemUnderTest.Cleanup(fileDownloadResult);

            loggingServiceMock.Received().LogVerbose("Moving: DownloadFilePath to FailedDownloadFilePath");
            fileServiceMock.Received().Move("DownloadFilePath", "FailedDownloadFilePath");
        }
Ejemplo n.º 19
0
        private FileDownloadResult HandleDownloadNotReadyToRun(FailedReason failedReason, FilePayload filePayload)
        {
            FileDownloadResult failedResult = NewFailedFileDownloadResult(failedReason, filePayload);

            LogResult(failedResult);
            FileDownloadError(failedResult);
            SendEmail(failedResult);
            return(failedResult);
        }
Ejemplo n.º 20
0
        public DbParameter CreateErrorMessageParameter(IDatabaseConnectionService databaseConnection,
                                                       FileDownloadResult fileDownloadResult)
        {
            FilePayload filePayload = fileDownloadResult.FilePayload;
            string      message     = errorMessageService.GetErrorMessage(fileDownloadResult.FailedReason, filePayload,
                                                                          StatsDownloadService.FileDownload);

            return(CreateErrorMessageParameter(databaseConnection, message));
        }
Ejemplo n.º 21
0
        public async Task DownloadFile_WhenDataStoreIsNotAvailable_ReturnsDatabaseUnavailableResult()
        {
            SetUpWhenDataStoreIsNotAvailable();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.DataStoreUnavailable));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 22
0
        public async Task DownloadFile_WhenFileDownloadFails_ReturnsFailedResultUnexpectedException()
        {
            SetUpFileDownloadFails();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.UnexpectedException));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 23
0
        public async Task DownloadFile_WhenFileDownloadProtocolError_ReturnsFailedResultFileDownloadNotFound()
        {
            SetUpFileDownloadProtocolError();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.FileDownloadNotFound));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 24
0
        public async Task DownloadFile_WhenFileDownloadSettingsInvalid_ReturnsFailedReasonRequiredSettingsInvalid()
        {
            SetUpFileDownloadSettingsInvalid();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.RequiredSettingsInvalid));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 25
0
        public async Task DownloadFile_WhenFileDownloadTimeout_ReturnsFailedResultFileDownloadTimeout()
        {
            SetUpFileDownloadTimeout();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.FileDownloadTimeout));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 26
0
        public async Task DownloadFile_WhenMinimumWaitTimeNotMet_ReturnsFailedResultMinimumWaitTimeNotMet()
        {
            SetUpWhenMinimumWaitTimeNotMet();

            FileDownloadResult actual = await InvokeDownloadFile();

            Assert.That(actual.Success, Is.False);
            Assert.That(actual.FailedReason, Is.EqualTo(FailedReason.MinimumWaitTimeNotMet));
            Assert.That(actual.FilePayload, Is.InstanceOf <FilePayload>());
        }
Ejemplo n.º 27
0
        private static FileDownloadResult GetFileInfo(Message message, string savePath)
        {
            FileDownloadResult fileInfo = null;

            if (message.Document != null)
            {
                fileInfo = Program.Bot.DownloadFileById(message.Document.FileId, savePath);
            }
            return(fileInfo);
        }
        public void SetUp()
        {
            databaseConnectionServiceMock = Substitute.For <IDatabaseConnectionService>();

            statsDownloadDatabaseServiceMock = Substitute.For <IStatsDownloadDatabaseService>();
            statsDownloadDatabaseServiceMock.When(service =>
                                                  service.CreateDatabaseConnectionAndExecuteAction(
                                                      Arg.Any <Action <IDatabaseConnectionService> >())).Do(callInfo =>
            {
                var service = callInfo.Arg <Action <IDatabaseConnectionService> >();

                service.Invoke(databaseConnectionServiceMock);
            });

            statsDownloadDatabaseParameterServiceMock = Substitute.For <IStatsDownloadDatabaseParameterService>();

            loggingServiceMock = Substitute.For <ILoggingService>();

            systemUnderTest = NewFileDownloadDatabaseProvider(statsDownloadDatabaseServiceMock,
                                                              statsDownloadDatabaseParameterServiceMock, loggingServiceMock);

            DatabaseProviderTestingHelper.SetUpDatabaseConnectionServiceReturns(databaseConnectionServiceMock);

            filePayload = new FilePayload
            {
                DownloadId            = 100,
                UploadPath            = "UploadPath",
                DownloadFileName      = "DownloadFileName",
                DownloadFileExtension = "DownloadFileExtension",
                FileUtcDateTime       = DateTime.Today
            };

            fileDownloadResult = new FileDownloadResult(filePayload);

            dbDataReaderMock = Substitute.For <DbDataReader>();
            dbDataReaderMock.Read().Returns(true, true, true, false);
            dbDataReaderMock.GetInt32(0).Returns(100, 200, 300);

            databaseConnectionServiceMock
            .ExecuteReader("SELECT DownloadId FROM [FoldingCoin].[DownloadsReadyForUpload]")
            .Returns(dbDataReaderMock);

            downloadIdParameterMock = Substitute.For <DbParameter>();
            downloadIdParameterMock.Value.Returns(100);
            statsDownloadDatabaseParameterServiceMock.CreateDownloadIdParameter(databaseConnectionServiceMock, 100)
            .Returns(downloadIdParameterMock);
            statsDownloadDatabaseParameterServiceMock.CreateDownloadIdParameter(databaseConnectionServiceMock)
            .Returns(downloadIdParameterMock);
            statsDownloadDatabaseParameterServiceMock
            .CreateDownloadIdParameter(databaseConnectionServiceMock, ParameterDirection.Output)
            .Returns(downloadIdParameterMock);

            errorMessageParameterMock = Substitute.For <DbParameter>();
        }
Ejemplo n.º 29
0
 private void UpdateToError(FileDownloadResult exceptionResult)
 {
     if (IsFileDownloadError(exceptionResult))
     {
         fileDownloadDatabaseService.FileDownloadError(exceptionResult);
     }
     else
     {
         fileDownloadDatabaseService.FileValidationError(exceptionResult);
     }
 }
Ejemplo n.º 30
0
        private async Task <FileDownloadResult> HandleSuccessAndUpload(FilePayload filePayload)
        {
            LogVerbose($"Stats file download completed: {DateTimeNow()}");
            await UploadFile(filePayload);

            FileDownloadResult successResult = NewSuccessFileDownloadResult(filePayload);

            Cleanup(successResult);
            LogResult(successResult);
            return(successResult);
        }