Exemple #1
0
        public void Disable_transfer_settings_test()
        {
            // Arrange
            var transferSettings = new TransferSettings();

            transferSettings.Id      = new Guid("84c60b9f-16ad-49e0-bb9a-0e7670054dd5");
            transferSettings.Enabled = true;

            //required for event processing
            //will chnged in the future
            transferSettings.Brand = new Core.Payment.Data.Brand
            {
                Name         = TestDataGenerator.GetRandomString(),
                LicenseeName = TestDataGenerator.GetRandomString()
            };
            transferSettings.TransferType = TransferFundType.FundIn;

            _paymentRepository.TransferSettings.Add(transferSettings);

            // Act
            _commands.Disable(transferSettings.Id, TestDataGenerator.GetRandomTimeZone().Id, "remark");

            //Assert
            var settings = _paymentRepository.TransferSettings.Single(x => x.Id == transferSettings.Id);

            settings.Enabled.Should().BeFalse();
            settings.DisabledBy.ShouldBeEquivalentTo(_securityProvider.Actor.UserName);
            settings.DisabledDate.Should().BeCloseTo(DateTime.Now, 5000);
        }
Exemple #2
0
        public void Update_transfer_settgins_limits_test()
        {
            // Arrange
            var transferSettings = new TransferSettings();

            transferSettings.Id = new Guid("84c60b9f-16ad-49e0-bb9a-0e7670054dd5");
            _paymentRepository.TransferSettings.Add(transferSettings);

            var saveTransferSettingsCommand = new SaveTransferSettingsCommand();

            saveTransferSettingsCommand.Id = transferSettings.Id;
            saveTransferSettingsCommand.MinAmountPerTransaction = 10;
            saveTransferSettingsCommand.MaxAmountPerTransaction = 20;
            saveTransferSettingsCommand.MaxAmountPerDay         = 30;
            saveTransferSettingsCommand.MaxTransactionPerDay    = 40;
            saveTransferSettingsCommand.MaxTransactionPerWeek   = 50;
            saveTransferSettingsCommand.MaxTransactionPerMonth  = 60;
            saveTransferSettingsCommand.TimezoneId = TestDataGenerator.GetRandomTimeZone().Id;

            // Act
            _commands.UpdateSettings(saveTransferSettingsCommand);

            //Assert
            var settings = _paymentRepository.TransferSettings.Single(x => x.Id == transferSettings.Id);

            settings.MinAmountPerTransaction.ShouldBeEquivalentTo(10);
            settings.MaxAmountPerTransaction.ShouldBeEquivalentTo(20);
            settings.MaxAmountPerDay.ShouldBeEquivalentTo(30);
            settings.MaxTransactionPerDay.ShouldBeEquivalentTo(40);
            settings.MaxTransactionPerWeek.ShouldBeEquivalentTo(50);
            settings.MaxTransactionPerMonth.ShouldBeEquivalentTo(60);
            settings.UpdatedBy.ShouldBeEquivalentTo(_securityProvider.Actor.UserName);
            settings.UpdatedDate.Should().BeCloseTo(DateTime.Now, 5000);
        }
        public void UploadFileTest_privateKeyConnection_canUploadFile()
        {
            // arrange
            ConnectivitySettings connectivitySettings = SftpTestsHelperRoutines.CreateConnectivitySettingsFromConfig();
            string physicalPathToPrivateKeyFile       = SftpTestsHelperRoutines.GetTestFilesPath() + connectivitySettings.PrivateKeyPath;

            connectivitySettings.PrivateKeyPath = physicalPathToPrivateKeyFile;

            DotNetSftpClient dotNetSftpClient = new DotNetSftpClient(connectivitySettings, testLogger);

            dotNetSftpClient.CreateConnection();

            // act/assert - 'assert' as in no exceptions are thrown
            string           newTempFilePath  = Path.GetTempFileName();
            TransferSettings transferSettings = new TransferSettings()
            {
                TransferType    = 'u',
                DestinationPath = string.Empty,
                SourcePath      = newTempFilePath
            };

            // act/assert - 'assert' as in no exceptions are thrown
            using (dotNetSftpClient)
            {
                dotNetSftpClient.Upload(transferSettings);
            }
        }
        public void Upload(TransferSettings transferSettings)
        {
            #region guard clause

            if (String.IsNullOrWhiteSpace(transferSettings.DestinationPath))
            {
                if (string.IsNullOrWhiteSpace(_connectivitySettings.UserName))
                {
                    throw new NotImplementedException("Could not form a destination path based on the user's name - it is blank");
                }

                _logger.LogInformation($"Blank destination-path, will rename to user's home dir");
                transferSettings.DestinationPath = $@"/home/{_connectivitySettings.UserName}";
            }

            #endregion guard clause

            _logger.LogInformation($"Will upload into directory '{transferSettings.DestinationPath}'");
            CreateServerDirectoryIfItDoesntExist(transferSettings.DestinationPath);

            // Create uploader-implementation
            ISftpFileUploader fileUploaderImplementation = CreateSftpUploaderFromTransferSettings(transferSettings, _logger);

            //detect whether its a directory or file, and act accordingly
            FileAttributes fileSystemEntryAttributes = File.GetAttributes(transferSettings.SourcePath);
            if ((fileSystemEntryAttributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                bool shouldZipCompressDirectoryBeforeUpload = transferSettings.CompressDirectoryBeforeUpload;
                if (shouldZipCompressDirectoryBeforeUpload)
                {
                    string        tempPath = Path.GetTempPath();
                    DirectoryInfo dirInfo  = new DirectoryInfo(transferSettings.SourcePath);
                    string        compressedZipFileFullPath = tempPath + @"\" + dirInfo.Name + ".zip";
                    if (File.Exists(compressedZipFileFullPath))
                    {
                        File.Delete(compressedZipFileFullPath);
                    }

                    ZipFile.CreateFromDirectory(transferSettings.SourcePath, compressedZipFileFullPath);

                    UploadSingleFile(fileUploaderImplementation, compressedZipFileFullPath, transferSettings.DestinationPath, transferSettings.OverWriteExistingFiles);
                }
                else
                {
                    UploadDirectory(transferSettings, fileUploaderImplementation);
                }
            }
            else // is file
            {
                string pathOfFileToUpload = transferSettings.SourcePath;
                UploadSingleFile(fileUploaderImplementation, pathOfFileToUpload, transferSettings.DestinationPath, transferSettings.OverWriteExistingFiles);
            }
        }
Exemple #5
0
        /// <summary>
        /// Sets the settings according to the controls.
        /// </summary>
        public void ControlsToSettings(TransferSettings transferSettings)
        {
            if (transferSettings == null)
            {
                throw new ArgumentNullException("transferSettings");
            }

            transferSettings.IncludeBase      = chkIncludeBase.Checked;
            transferSettings.IncludeInterface = chkIncludeInterface.Checked;
            transferSettings.IncludeServer    = chkIncludeServer.Checked;
            transferSettings.IncludeComm      = chkIncludeComm.Checked;
            transferSettings.IncludeWeb       = chkIncludeWeb.Checked;
            transferSettings.IgnoreRegKeys    = chkIgnoreRegKeys.Checked;
            transferSettings.IgnoreWebStorage = chkIgnoreWebStorage.Checked;
        }
        /// <summary>
        /// Will upload an entire directory of files and, recursively, directories within.
        /// </summary>
        public void UploadDirectory(TransferSettings transferSettings, ISftpFileUploader fileUploaderImplementation)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"Uploading directory {transferSettings.SourcePath}");
                _logger.LogInformation($"Uploading directory {transferSettings.SourcePath}");

                // upload files within directory
                IEnumerable <string> filesToUpload = Directory.EnumerateFiles(transferSettings.SourcePath, "*.*").ToList();

                // upload all individual files into the server directory
                int uploadedFileCounter = 1;
                foreach (string fileToUpload in filesToUpload)
                {
                    UploadSingleFile(fileUploaderImplementation, fileToUpload, transferSettings.DestinationPath, transferSettings.OverWriteExistingFiles);
                    uploadedFileCounter++;
                }

                // Traverse any sub-directories
                DirectoryInfo   dirInfo        = new DirectoryInfo(transferSettings.SourcePath);
                DirectoryInfo[] subDirectories = dirInfo.GetDirectories();
                if (!subDirectories.Any())
                {
                    return;
                }

                foreach (DirectoryInfo subDir in subDirectories)
                {
                    // Shallow copy transfer-settings object ...
                    TransferSettings copiedTransferSettings = new TransferSettings
                    {
                        OverWriteExistingFiles = transferSettings.OverWriteExistingFiles,
                        SourcePath             = subDir.FullName,
                        DestinationPath        = transferSettings.DestinationPath + @"/" + subDir.Name
                    };
                    _logger.LogInformation($"Will upload into directory '{subDir.Name}'");

                    // ... then call UploadDirectory() recursively.
                    CreateServerDirectoryIfItDoesntExist(copiedTransferSettings.DestinationPath);
                    UploadDirectory(copiedTransferSettings, fileUploaderImplementation);
                }
            }
            catch (Exception e)
            {
                throw new DotNetSftpClientException(e.Message, e);
            }
        }
Exemple #7
0
        /// <summary>
        /// Setup the controls according to the settings.
        /// </summary>
        public void SettingsToControls(TransferSettings transferSettings)
        {
            if (transferSettings == null)
            {
                throw new ArgumentNullException("transferSettings");
            }

            changing = true;
            chkIncludeBase.Checked      = transferSettings.IncludeBase;
            chkIncludeInterface.Checked = transferSettings.IncludeInterface;
            chkIncludeServer.Checked    = transferSettings.IncludeServer;
            chkIncludeComm.Checked      = transferSettings.IncludeComm;
            chkIncludeWeb.Checked       = transferSettings.IncludeWeb;
            chkIgnoreRegKeys.Checked    = transferSettings.IgnoreRegKeys;
            chkIgnoreWebStorage.Checked = transferSettings.IgnoreWebStorage;
            gbOptions.Enabled           = true;
            changing = false;
        }
Exemple #8
0
        public void Enable_transfer_settings_test()
        {
            // Arrange
            var transferSettings = new TransferSettings();

            transferSettings.Id = new Guid("84c60b9f-16ad-49e0-bb9a-0e7670054dd5");
            _paymentRepository.TransferSettings.Add(transferSettings);

            // Act
            _commands.Enable(transferSettings.Id, TestDataGenerator.GetRandomTimeZone().Id, "remark");

            //Assert
            var settings = _paymentRepository.TransferSettings.Single(x => x.Id == transferSettings.Id);

            settings.Enabled.Should().BeTrue();
            settings.EnabledBy.ShouldBeEquivalentTo(_securityProvider.Actor.UserName);
            settings.EnabledDate.Should().BeCloseTo(DateTime.Now, 5000);
        }
        public TransferStatus PerformDataTransfer(string sourceFilePath, string targetFilePath, int operationStepsCount, BackgroundWorker worker, ManualResetEvent locker)
        {
            var dataTransferObject = new DataTransferObject();

            TransferSettings.RegisterOperation(targetFilePath);

            try
            {
                var fileBytes = File.ReadAllBytes(sourceFilePath);
                dataTransferObject.BytesAmountPerTransfer = (int)Math.Ceiling((double)fileBytes.Length / operationStepsCount);

                for (var i = 0; i < operationStepsCount; i++)
                {
                    locker.WaitOne();

                    var startIndex = i == 0 ? 0 : dataTransferObject.EndByte.Index + 1;
                    dataTransferObject.SetTransferParameters(fileBytes, startIndex);

                    dataTransferObject = TransferData(targetFilePath, dataTransferObject);

                    if (CheckForOperationError(dataTransferObject.Status))
                    {
                        return(dataTransferObject.Status);
                    }

                    worker.ReportProgress(i);

                    if (CheckForOperationSuccess(dataTransferObject))
                    {
                        return(dataTransferObject.Status);
                    }

                    Thread.Sleep(1000);
                }
            }
            catch (Exception e)
            {
                dataTransferObject.Status = TransferStatus.Failed;

                return(dataTransferObject.Status);
            }

            return(dataTransferObject.Status);
        }
        private ISftpFileUploader CreateSftpUploaderFromTransferSettings(TransferSettings transferSettings, ILogger logger)
        {
            // TODO: add decorators based on transfersettings
            ISftpFileUploadDecorator uploader = new BasicSftpFileUploaderDecorator(new NullObjectSftpuploadDecorator());

            if (!string.IsNullOrWhiteSpace(transferSettings.UploadPrefix))
            {
                uploader = new UploadPrefixIndicatorDecorator(transferSettings.UploadPrefix, uploader);
            }

            if (transferSettings.CalculateChecksum == true)
            {
                uploader = new ChecksumFileDecorator(uploader);
            }

            //uploader = new ChecksumFileDecorator(uploader);

            ISftpFileUploader standardFileUploader = new StandardSftpFileUploader(uploader, logger);

            return(standardFileUploader);
        }
Exemple #11
0
        /// <summary>
        /// Setup the controls according to the settings.
        /// </summary>
        public void SettingsToControls(TransferSettings transferSettings)
        {
            if (transferSettings == null)
            {
                throw new ArgumentNullException("transferSettings");
            }

            changing                    = true;
            gbOptions.Enabled           = true;
            chkIncludeBase.Checked      = transferSettings.IncludeBase;
            chkIncludeInterface.Checked = transferSettings.IncludeInterface;
            chkIncludeServer.Checked    = transferSettings.IncludeServer;
            chkIncludeComm.Checked      = transferSettings.IncludeComm;
            chkIncludeWeb.Checked       = transferSettings.IncludeWeb;
            chkIgnoreRegKeys.Checked    = transferSettings.IgnoreRegKeys;
            chkIgnoreWebStorage.Checked = transferSettings.IgnoreWebStorage;

            if (transferSettings is UploadSettings uploadSettings)
            {
                chkRestartServer.Visible = true;
                chkRestartComm.Visible   = true;
                lblObjFilter.Visible     = true;
                txtObjFilter.Visible     = true;
                btnSelectObj.Visible     = true;

                chkRestartServer.Checked = uploadSettings.RestartServer;
                chkRestartComm.Checked   = uploadSettings.RestartComm;
                txtObjFilter.Text        = RangeUtils.RangeToStr(uploadSettings.ObjNums);
            }
            else
            {
                chkRestartServer.Visible = false;
                chkRestartComm.Visible   = false;
                lblObjFilter.Visible     = false;
                txtObjFilter.Visible     = false;
                btnSelectObj.Visible     = false;
            }

            changing = false;
        }
Exemple #12
0
        /// <summary>
        /// Sets the settings according to the controls.
        /// </summary>
        public void ControlsToSettings(TransferSettings transferSettings)
        {
            if (transferSettings == null)
            {
                throw new ArgumentNullException("transferSettings");
            }

            transferSettings.IncludeBase      = chkIncludeBase.Checked;
            transferSettings.IncludeInterface = chkIncludeInterface.Checked;
            transferSettings.IncludeServer    = chkIncludeServer.Checked;
            transferSettings.IncludeComm      = chkIncludeComm.Checked;
            transferSettings.IncludeWeb       = chkIncludeWeb.Checked;
            transferSettings.IgnoreRegKeys    = chkIgnoreRegKeys.Checked;
            transferSettings.IgnoreWebStorage = chkIgnoreWebStorage.Checked;

            if (transferSettings is UploadSettings uploadSettings)
            {
                uploadSettings.RestartServer = chkRestartServer.Checked;
                uploadSettings.RestartComm   = chkRestartComm.Checked;
                uploadSettings.SetObjNums(RangeUtils.StrToRange(txtObjFilter.Text, true, true));
            }
        }
        public void UploadFileTest_usernamePasswordConnection_canUploadFile()
        {
            // arrange
            ConnectivitySettings connectivitySettings = SftpTestsHelperRoutines.CreateConnectivitySettingsFromConfig();

            connectivitySettings.PrivateKeyPath = String.Empty; // clear private key path, so we only connect via username/password
            DotNetSftpClient dotNetSftpClient = new DotNetSftpClient(connectivitySettings, testLogger);

            dotNetSftpClient.CreateConnection();

            string           newTempFilePath  = Path.GetTempFileName();
            TransferSettings transferSettings = new TransferSettings()
            {
                TransferType    = 'u',
                DestinationPath = " ",
                SourcePath      = newTempFilePath
            };

            // act/assert - 'assert' as in no exceptions are thrown
            using (dotNetSftpClient)
            {
                dotNetSftpClient.Upload(transferSettings);
            }
        }
Exemple #14
0
        private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TransferSettings.UnRegisterOperation(_targetFilePath);

            if (_operationStatus == TransferStatus.Success)
            {
                _resetAction?.Invoke(_folderToReset, _listBoxToReset);
                Close();

                _fileProvider.SimalateUsersCalculationHash(_targetFilePath);
            }
            else
            {
                if (MessageBox.Show("Try again", "Operation failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    _worker.RunWorkerAsync();
                }
                else
                {
                    File.Delete(_targetFilePath);
                    this.Close();
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Exports the configuration to the specified archive.
        /// </summary>
        public void ExportToArchive(string destFileName, ScadaProject project, Instance instance,
                                    TransferSettings transferSettings)
        {
            if (destFileName == null)
            {
                throw new ArgumentNullException("destFileName");
            }
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            FileStream fileStream = null;
            ZipArchive zipArchive = null;

            try {
                fileStream = new FileStream(destFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
                zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create);
                bool ignoreRegKeys = transferSettings.IgnoreRegKeys;

                // add the configuration database to the archive
                if (transferSettings.IncludeBase)
                {
                    foreach (IBaseTable srcTable in project.ConfigBase.AllTables)
                    {
                        string entryName  = "BaseDAT/" + srcTable.Name.ToLowerInvariant() + ".dat";
                        var    tableEntry = zipArchive.CreateEntry(entryName, CompressionLevel.Fastest);

                        using (var entryStream = tableEntry.Open()) {
                            // convert the table to DAT format
                            BaseAdapter baseAdapter = new BaseAdapter()
                            {
                                Stream = entryStream
                            };
                            baseAdapter.Update(srcTable);
                        }
                    }
                }

                // add the interface files to the archive
                if (transferSettings.IncludeInterface)
                {
                    PackDirectory(zipArchive, project.Interface.InterfaceDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Interface, '/'), ignoreRegKeys);
                }

                // add the Server settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, instance.ServerApp.AppDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Server, '/'), ignoreRegKeys);
                }

                // add the Communicator settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, instance.CommApp.AppDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Comm, '/'), ignoreRegKeys);
                }

                // add the Webstation settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, Path.Combine(instance.WebApp.AppDir, "config"),
                                  DirectoryBuilder.GetDirectory(ConfigParts.Web, AppFolder.Config, '/'), ignoreRegKeys);

                    if (!transferSettings.IgnoreWebStorage)
                    {
                        PackDirectory(zipArchive, Path.Combine(instance.WebApp.AppDir, "storage"),
                                      DirectoryBuilder.GetDirectory(ConfigParts.Web, AppFolder.Storage, '/'), ignoreRegKeys);
                    }
                }
            } catch (Exception ex) {
                throw new ScadaException(AdminPhrases.ExportToArchiveError, ex);
            } finally {
                zipArchive?.Dispose();
                fileStream?.Dispose();
            }
        }
Exemple #16
0
        /// <summary>
        /// Transfers files to the destination directory. Each file gets new name, which is constructed of prefix, a number and a extension.
        /// </summary>
        /// <param name="sources">Files to be transfered</param>
        /// <param name="destinationDirectory">Destination directory</param>
        /// <param name="namePrefix">Template for destination file names</param>
        /// <param name="transferSettings">Settings of the transfer</param>
        public static void TransferFiles(IEnumerable <FileInfo> sources, DirectoryInfo destinationDirectory, string namePrefix, TransferSettings transferSettings)
        {
            if (sources == null)
            {
                throw new ArgumentNullException(nameof(sources));
            }

            if (destinationDirectory == null)
            {
                throw new ArgumentNullException(nameof(destinationDirectory));
            }

            if (namePrefix == null)
            {
                throw new ArgumentNullException(nameof(namePrefix));
            }

            NameExtensionSplit(namePrefix, out string name, out string extension);

            IEnumerable <(FileInfo, FileInfo)> GenerateMoves()
            {
                int counter = 0;

                foreach (var source in sources)
                {
                    yield return(source, new FileInfo(Path.Combine(destinationDirectory.FullName, name + counter + extension)));

                    counter++;
                }
            }

            TransferFiles(GenerateMoves(), transferSettings);
        }
Exemple #17
0
        /// <summary>
        /// Transfers files to the destination directory, maintaining the original file names.
        /// </summary>
        /// <param name="sources">Files to be transferd</param>
        /// <param name="destinationDirectory">Destination directory</param>
        /// <param name="settings">Settings of the transfer</param>
        public static void TransferFiles(IEnumerable <FileInfo> sources, DirectoryInfo destinationDirectory, TransferSettings settings)
        {
            if (sources == null)
            {
                throw new ArgumentNullException(nameof(sources));
            }

            if (destinationDirectory == null)
            {
                throw new ArgumentNullException(nameof(destinationDirectory));
            }

            IEnumerable <(FileInfo, FileInfo)> GenerateMoves()
            {
                foreach (var source in sources)
                {
                    yield return(source, new FileInfo(Path.Combine(destinationDirectory.FullName, source.Name)));
                }
            }

            TransferFiles(GenerateMoves(), settings);
        }
Exemple #18
0
        protected override FileTransferErrorActionRepeatable HandleTransferErrorRepeatable(string errorMessage, Exception e, FileInfo originFile,
                                                                                           string destinyDir, TransferSettings settings)
        {
            FormErrorDialog form = new FormErrorDialog(typeof(FileTransferErrorActionRepeatable), errorMessage);

            form.ShowDialog();
            return((FileTransferErrorActionRepeatable)form.Result);
        }
Exemple #19
0
        protected override void HandleCurrentFileExecution(string trimmedPathWithFileName, FileInfo originFile, string destinyDir, TransferSettings settings)
        {
            if (trimmedPathWithFileName.Length > 100)
            {
                trimmedPathWithFileName = $"...{trimmedPathWithFileName.Substring(trimmedPathWithFileName.Length - 100)}";
            }

            Menu.ShowCurrentFileExecution(trimmedPathWithFileName);
        }
Exemple #20
0
 public FileTransferArguments(FileInfo from, FileInfo to, TransferSettings settings)
 {
     From     = from;
     To       = to;
     Settings = settings;
 }
 public void Download(TransferSettings settingsParserTransferSettings)
 {
     throw new NotImplementedException();
 }
 protected override void HandleCurrentFileExecution(string trimmedPathWithFileName, FileInfo originFile, string destinyDir, TransferSettings settings)
 {
     //Console.WriteLine($"Transfering: {trimmedPathWithFileName}");
 }
 public DirectoryTransferArguments(DirectoryInfo from, DirectoryInfo to, TransferSettings settings)
 {
     From     = from;
     To       = to;
     Settings = settings;
 }