Exemplo n.º 1
0
        public static void DbDirectCopyWriter <TKey>(DbDebugItem <TKey> debug, AbstractDb <TKey> db)
        {
            try {
                if (debug.OldPath != debug.FilePath)
                {
                    var storeCompareList = db.Attached["StoreCompare"] as List <string>;

                    if (storeCompareList != null)
                    {
                        foreach (var path in storeCompareList)
                        {
                            var oldPath = DbPathLocator.GetStoredFile(path);

                            if (!IOHelper.SameFile(oldPath, path))
                            {
                                // Test their modified date
                                IOHelper.Delete(path);
                                IOHelper.Copy(oldPath, path);
                            }
                        }
                    }
                    else if (!IOHelper.SameFile(debug.OldPath, debug.FilePath))
                    {
                        // Test their modified date
                        IOHelper.Delete(debug.FilePath);
                        IOHelper.Copy(debug.OldPath, debug.FilePath);
                    }
                }
            }
            catch (Exception err) {
                debug.ReportException(err);
            }
        }
Exemplo n.º 2
0
        public void Backup(string file)
        {
            if (!SdeAppConfiguration.BackupsManagerState || !IsStarted || _backupThread.IsCrashed)
            {
                return;
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            try {
                string relativePath = file.ReplaceFirst(GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath) + IOHelper.Slash, "");

                if (String.IsNullOrEmpty(relativePath))
                {
                    return;
                }

                _validateOpened();

                string fullPath = GrfPath.Combine(_paths[_currentId], relativePath);
                string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}");
                IOHelper.Copy(file, tempFile);

                _localToGrfPath[_currentId][tempFile] = fullPath;
            }
            catch {
            }
        }
Exemplo n.º 3
0
        public void CopyThrowsOnMissing()
        {
            var dirSource = Path.Combine(Path.Combine(testDir, "CopyThrowsOnExisting"), "source");
            var dirTarget = Path.Combine(Path.Combine(testDir, "CopyThrowsOnExisting"), "target");

            var sourceFile = Path.Combine(dirSource, "testfile.txt");
            var targetFile = Path.Combine(dirTarget, "testfile.txt");

            Assert.Throws <ArgumentException>(() => IOHelper.Copy(sourceFile, targetFile));
        }
Exemplo n.º 4
0
        public void CopyThrowsOnMismatch()
        {
            var dirSource = Path.Combine(Path.Combine(testDir, "CopyThrowsOnMismatch"), "source");
            var dirTarget = Path.Combine(Path.Combine(testDir, "CopyThrowsOnMismatch"), "target");

            var sourceFile = Path.Combine(dirSource, "testfile.txt");
            var targetFile = Path.Combine(dirTarget, "testfile2.txt");

            IOHelper.CreateFile(sourceFile);
            IOHelper.CreateFile(targetFile);

            Assert.Throws <ArgumentException>(() => IOHelper.Copy(sourceFile, dirTarget));
            Assert.Throws <ArgumentException>(() => IOHelper.Copy(dirSource, targetFile));
        }
Exemplo n.º 5
0
        public void CopyFileFromAtoB()
        {
            var dirA = Path.Combine(Path.Combine(testDir, "CopyFileFromAtoB"), "a");
            var dirB = Path.Combine(Path.Combine(testDir, "CopyFileFromAtoB"), "b");

            var fileA = Path.Combine(dirA, "testfile.txt");
            var fileB = Path.Combine(dirB, "testfile.txt");

            IOHelper.EnsureDirExists(dirA);
            IOHelper.CreateFile(fileA);
            //B does not exist!

            IOHelper.Copy(fileA, fileB);

            Assert.That(File.Exists(fileA), Is.True);     //file was copied, old file still exists
            Assert.That(Directory.Exists(dirA), Is.True); //directory was not touched either
            Assert.That(File.Exists(fileB), Is.True);     // new directory and file now exist!
        }
Exemplo n.º 6
0
        public static void StoreFile(string path)
        {
            if (path == null)
            {
                return;
            }

            if (IOHelper.Exists(path))
            {
                string temp = TemporaryFilesManager.GetTemporaryFilePath("sdb_store_{0:0000}.dat");
                _storedFiles[path]  = temp;
                _lastModified[path] = new FileInfo(temp).LastWriteTime;
                IOHelper.Copy(path, temp);
            }
            else
            {
                _lastModified[path] = default(DateTime);
                _storedFiles[path]  = null;
            }
        }
Exemplo n.º 7
0
        public void CopyWithOverwrite()
        {
            var dirA     = Path.Combine(Path.Combine(testDir, "CopyInPartExist"), "a");
            var subDirA1 = Path.Combine(dirA, "subdir1");
            var subDirA2 = Path.Combine(dirA, "sub dir2");
            var dirB     = Path.Combine(Path.Combine(testDir, "CopyInPartExist"), "b");
            var subDirB1 = Path.Combine(dirB, "subdir1");
            var subDirB2 = Path.Combine(dirB, "sub dir2");

            var fileA     = Path.Combine(dirA, "upperfile.txt");
            var fileB     = Path.Combine(dirB, "upperfile.txt");
            var subfileA1 = Path.Combine(subDirA1, "testfile.txt");
            var subfileB1 = Path.Combine(subDirB1, "testfile.txt");
            var subfileA2 = Path.Combine(subDirA2, "testfile II.txt");
            var subfileB2 = Path.Combine(subDirB2, "testfile II.txt");

            var oldFileInB = Path.Combine(subDirB1, "oldfile.txt");

            IOHelper.EnsureDirExists(subDirA1);
            IOHelper.CreateFile(fileA);
            IOHelper.CreateFile(subfileA1);
            IOHelper.CreateFile(subfileA2);

            IOHelper.EnsureDirExists(subDirB1); // B's dir-structure exists partially and...
            IOHelper.CreateFile(oldFileInB);    // ...has an existing file in there!

            IOHelper.Copy(dirA, dirB, true /* must overwrite */);

            Assert.That(Directory.Exists(dirA), Is.True);   // old directory exists...
            Assert.That(File.Exists(fileA), Is.True);       // ...and has the right content...
            Assert.That(File.Exists(subfileA1), Is.True);   // ...including first...
            Assert.That(File.Exists(subfileA2), Is.True);   // ...and second nested ones.

            Assert.That(Directory.Exists(dirB), Is.True);   // new directory exists...
            Assert.That(File.Exists(fileB), Is.True);       // ...and has the right content...
            Assert.That(File.Exists(subfileB1), Is.True);   // ...including first...
            Assert.That(File.Exists(subfileB2), Is.True);   // ...and second nested ones.

            Assert.That(File.Exists(oldFileInB), Is.False); // however, previous content in B was overwritten!
        }
Exemplo n.º 8
0
        public void InvalidPath()
        {
            var existingDir = Path.Combine(testDir, "ForInvalidPathTest");

            IOHelper.EnsureDirExists(existingDir);
            IOHelper.CreateFile(Path.Combine(existingDir, "testfile.txt"));

            var dirForTest = Path.Combine(testDir, "InvalidPath");

            IOHelper.EnsureDirExists(dirForTest);

            Func <string, string> MakeInput = (string casename) =>
                                              Path.Combine(Path.Combine(dirForTest, casename), "3k%f:4,h<.(f{d{s;@k#^h&j!");

            Assert.Throws <IOException>(() => IOHelper.EnsureDirExists(MakeInput("CreateDir")));
            Assert.Throws <IOException>(() => IOHelper.CreateFile(MakeInput("CreateFile")));
            Assert.Throws <ArgumentException>(() => IOHelper.Move(MakeInput("MoveFrom"), existingDir));
            Assert.Throws <ArgumentException>(() => IOHelper.Copy(MakeInput("CreateFrom"), existingDir));
            Assert.Throws <IOException>(() => IOHelper.Move(existingDir, MakeInput("MoveTo")));
            Assert.Throws <IOException>(() => IOHelper.Copy(existingDir, MakeInput("CopyTo")));

            IOHelper.Delete(MakeInput("Delete"));  //throws nothing because the input can NEVER exist on a Windows FileSystem
        }
        private void StartDownloadLastRdFile()
        {
            if (string.IsNullOrEmpty(this.SequenceId))
            {
                throw new InvalidOperationException("SequenceId is missing. RD file not downloaded.");
            }
            if (string.IsNullOrEmpty(this.SaveFolderAbsolutePath))
            {
                throw new InvalidOperationException("SaveFolderPath is missing. RD file not downloaded.");
            }

            this.IsTransferring = true;

            this.CurrentFileTransfer = Task.Run(
                async() =>
            {
                try
                {
                    using (var client = new UdpClient(new IPEndPoint(this.RemoteAddress, this.UdpSenderPort)))
                    {
                        byte[] sendBytes = Encoding.ASCII.GetBytes("!LOG RD OFF \r\n");
                        await client.SendAsync(sendBytes, sendBytes.Length).ConfigureAwait(false);
                    }

                    using (var ftp = new FtpClient())
                    {
                        ftp.Host = this.RemoteAddress.ToString();

                        await ftp.ConnectAsync().ConfigureAwait(false);

                        var configFiles       = await ftp.GetNameListingAsync().ConfigureAwait(false);
                        string lastRdFileName = configFiles.OrderByDescending(_ => _).FirstOrDefault(filename => filename.EndsWith(".rd"));

                        if (lastRdFileName == null)
                        {
                            throw new InvalidOperationException("No RD file found.");
                        }

                        lastRdFileName = lastRdFileName.Replace('\\', '/');

                        var transferData = new FileTransferData {
                            MonitoredFolderPath   = string.Format(@"\\{0}", this.RemoteAddress),
                            FileName              = this.SequenceId + ".rd",
                            MachineName           = Environment.MachineName,
                            DestinationFolderPath = this.SaveFolderAbsolutePath
                        };

                        this.LastTransferredFile = transferData;

                        using (var source = await ftp.OpenReadAsync(lastRdFileName).ConfigureAwait(false))
                            using (var destination = File.Open(Path.Combine(transferData.DestinationFolderPath, transferData.FileName), FileMode.OpenOrCreate))
                            {
                                await IOHelper.Copy(source, destination,
                                                    progressCallback: (copied, total) =>
                                {
                                    this.LastTransferredFile = new FileTransferData(transferData)
                                    {
                                        CopiedBytes = copied,
                                        TotalBytes  = total
                                    };
                                })
                                .ConfigureAwait(false);
                            }
                    }
                }
                finally
                {
                    using (var client = new UdpClient(new IPEndPoint(this.RemoteAddress, this.UdpSenderPort)))
                    {
                        byte[] sendBytes = Encoding.ASCII.GetBytes("!LOG RD ON \r\n");
                        client.Send(sendBytes, sendBytes.Length);
                    }

                    this.IsTransferring = false;
                }
            });
        }
Exemplo n.º 10
0
        private async Task TransferFile(string sourceFilePath, CancellationToken ct)
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentNullException("sourceFilePath");
            }

            var sourceFilename = Path.GetFileName(sourceFilePath);

            if (string.IsNullOrEmpty(sourceFilename))
            {
                throw new InvalidOperationException("sourceFilePath does not contain a filename.");
            }

            try
            {
                var results = await Task.WhenAll(
                    this.Settings.DestinationFolders.Select(
                        async destinationFolder =>
                {
                    try
                    {
                        string destinationFilePath = GetDestinationFilePath(sourceFilePath, destinationFolder);

                        await IOHelper.Copy(sourceFilePath, destinationFilePath, OverwriteMode.OverwriteIfDifferent, CopyOptions.AllowHardLinkCreation | CopyOptions.DisableBuffering, ct,
                                            (copiedBytes, totalBytes) =>
                        {
                            var fileProgressData = new FileTransferData {
                                MachineName           = Environment.MachineName,
                                MonitoredFolderPath   = _monitor.Path,
                                DestinationFolderPath = destinationFolder,
                                FileName    = Path.GetFileName(sourceFilePath),
                                CopiedBytes = copiedBytes,
                                TotalBytes  = totalBytes
                            };

                            _fileTransferSubject.OnNext(fileProgressData);
                        }).ConfigureAwait(false);

                        return(true);
                    }
                    catch (OperationCanceledException)
                    {
                        return(false);
                    }
                    catch (Exception ex)
                    {
                        // level set to Trace because it generates a lot of events
                        Log.Trace().Exception(ex).Write();

                        long fileLength = 0;
                        try
                        {
                            fileLength = new FileInfo(sourceFilePath).Length;
                        }
                        catch { }

                        var errorData = new FileTransferData {
                            MachineName           = Environment.MachineName,
                            DestinationFolderPath = destinationFolder,
                            MonitoredFolderPath   = _monitor.Path,
                            FileName   = Path.GetFileName(sourceFilePath),
                            TotalBytes = fileLength,
                            Exception  = ex
                        };

                        _fileTransferSubject.OnNext(errorData);

                        return(false);
                    }
                })).ConfigureAwait(false);

                if (!ct.IsCancellationRequested && results.All(result => result))
                {
                    File.Delete(sourceFilePath);
                }
            }
            catch (Exception ex)
            {
                Log.Warn().Exception(ex).Write();
            }
        }