public void Test_DeleteDestinationDestination()
        {
            Destination firstDestination = new Destination("multnomah falls", 1, 1);

            firstDestination.Save();
            Destination secondDestination = new Destination("paradise falls", 2, 1);

            secondDestination.Save();

            secondDestination.Delete();
            List <Destination> allDestinations  = Destination.GetAll();
            List <Destination> testDestinations = new List <Destination> {
                firstDestination
            };

            Assert.Equal(testDestinations, allDestinations);
        }
        /// <summary>
        /// Delete local (source) files that do not exist in the destination.
        /// </summary>
        private bool DeleteLocalGhostFiles()
        {
            Logger.WriteLog(ErrorCodes.SyncPhase_DeletionBegun2,
                            ErrorResources.SyncPhase_DeletionBegun, Severity.Information, VerboseLevel.User, true);

            DiscoveredObject[] files = Destination.GetObjects();

            for (int i = 0; i < files.Length; i++)
            {
                ScanProgress(i, files.Length, files[i].FullName);

                if (files[i].Kind == ObjectKind.File)
                {
                    string gcsObject = Helpers.RemoveSecExt(files[i].FullName);

                    if (!ObjectExists(gcsObject))
                    {
                        if (Destination.Delete(gcsObject, _wideDisplay))
                        {
                            Interlocked.Increment(ref _deletedCount);
                        }
                        else
                        {
                            Interlocked.Increment(ref _errorCount);
                        }
                    }
                }
                else if (files[i].Kind == ObjectKind.Directory)
                {
                    if (!Destination.AfterDirectoryScan(files[i].FullName, _wideDisplay))
                    {
                        Interlocked.Increment(ref _errorCount);
                    }
                }
                else
                {
                    throw new SmkException($"Unsupported type for {files[i].GetType().Name}.{files[i].Kind}");
                }
            }

            Logger.WriteLog(ErrorCodes.SyncPhase_DeletionEnded2,
                            ErrorResources.SyncPhase_DeletionEnded, Severity.Information, VerboseLevel.User, true);

            return(_errorCount == 0);
        }
Exemplo n.º 3
0
        private ProcessingResult DeleteDocTemplate(int id)
        {
            ProcessingResult pr         = new ProcessingResult();
            SqlConnection    connection = new SqlConnection(Config.ConnectionString);

            try
            {
                connection.Open();
                SqlTransaction trans = null;
                try
                {
                    trans = connection.BeginTransaction();

                    DocTemplate docTemplate = new DocTemplate(trans, id, UserName);

                    DocTemplate.Delete(trans, docTemplate.ID, UserName);

                    Destination.Delete(trans, docTemplate.DocumentID, UserName);
                    Source.Delete(trans, docTemplate.DocumentID, UserName);

                    DocumentFile.DeleteFiles(trans, docTemplate.DocumentID, Worker);

                    Document.Document.Delete(trans, docTemplate.DocumentID, UserName);

                    trans.Commit();

                    pr.Success = true;
                }
                catch (Exception e)
                {
                    if (trans != null)
                    {
                        trans.Rollback();
                    }

                    pr.Message = e.Message;
                    throw;
                }
            }
            finally
            {
                connection.Close();
            }
            return(pr);
        }
Exemplo n.º 4
0
        public HomeModule()
        {
            Get["/"] = _ => {
                Console.WriteLine("Return View");
                return(View["index.cshtml"]);
            };
            Get["/roadTrip/{id}"] = x => {
                Console.WriteLine("View Road Trip");
                return(View["viewRoadTrip.cshtml", RoadTrip.Find(int.Parse(x.id))]);
            };
            Get["/getStop/{id}"] = x => {
                Console.WriteLine("View Stop");
                return(View["destination.cshtml", Destination.Find(int.Parse(x.id))]);
            };
            Get["/getAllRoadTrips"] = _ => {
                return(View["viewAllRoadTrips.cshtml", RoadTrip.GetAll()]);
            };
            Get["/deleteDestination/{id}"] = parameters => {
                Console.WriteLine("Deleteing: " + parameters.id);
                Destination selectedDestination = Destination.Find(parameters.id);
                selectedDestination.Delete();
                return(View["empty.cshtml"]);
            };

            Get["/moveUp/{id}"] = parameters => {
                Console.WriteLine("Move Up: " + parameters.id);
                Destination selectedDestination = Destination.Find(parameters.id);
                selectedDestination.MoveUp();
                return(View["empty.cshtml"]);
            };

            Get["/moveDown/{id}"] = parameters => {
                Console.WriteLine("Move Down: " + parameters.id);
                Destination selectedDestination = Destination.Find(parameters.id);
                Console.WriteLine("Destination Found, RoadTripId: " + selectedDestination.GetRoadTripId());
                selectedDestination.MoveDown();
                return(View["empty.cshtml"]);
            };

            Post["/nameTrip"] = _ => {
                RoadTrip newTrip = RoadTrip.Find(int.Parse(Request.Form["id"]));
                newTrip.SetName(Request.Form["name"]);
                newTrip.Update();
                return(View["empty.cshtml"]);
            };

            // AJAX ROUTE ONLY RETURNS A PARTIAL HTML VIEW

            Post["/addStop"] = _ => {
                Dictionary <string, object> model = new Dictionary <string, object>()
                {
                };                                                           // instantiate model
                int roadTripId = 0;
                try {
                    roadTripId = int.Parse(Request.Form["roadTripId"]);                         // get roadtrip id
                } catch (Exception e) {}
                string   destinationName = Request.Form["command"];                             // get new destination name
                RoadTrip rtrip;
                if (roadTripId == 0)                                                            // there is no road trip yet
                {
                    rtrip = new RoadTrip("The awesome " + destinationName + " Road Trip!", ""); // so make a road trip
                    rtrip.Save();                                                               // save road trip to db
                    roadTripId = rtrip.GetId();
                }
                else
                {
                    rtrip = RoadTrip.Find(roadTripId);
                }
                Destination newStop = new Destination(destinationName, roadTripId); // make a new destination
                newStop.Save();                                                     // save the new stop to the database
                if (newStop.GetStop() == 1)                                         // if theres only one stop in the road trip so far
                {
                    Console.WriteLine("First Stop");
                    model.Add("map", Scrubber.GetMapOnLocation(newStop.GetName())); // show the map with only one location
                }
                else // there are already multiple stops in the trip
                {
                    Console.WriteLine("Not First Stop");
                    model.Add("map", Scrubber.GetMapDirections(rtrip.GetDestinations()[rtrip.GetDestinations().Count - 2].GetName(), newStop.GetName())); // show direciton map
                }
                model.Add("images", Scrubber.Search(newStop.GetName(), 6));
                model.Add("roadTripId", roadTripId);
                model.Add("destination", newStop);
                Console.WriteLine(model);
                Console.WriteLine("Return View");
                return(View["stop.cshtml", model]);
            };
        }
Exemplo n.º 5
0
 public IActionResult Delete(int id)
 {
     Destination.Delete(id);
     return(RedirectToAction("Index"));
 }
Exemplo n.º 6
0
        /// <summary>
        /// The actual functionality to download with optional hash verification
        /// subclasses that wish to return the contents of the downloaded file
        /// or do something else with it can override this instead of RunWithReturn.
        /// If you do, you must call RaiseOnStart()/RaiseOnEnd()
        /// </summary>
        /// <param name="success"></param>
        /// <returns></returns>
        protected virtual string RunDownload(bool success)
        {
            Exception exception = null;
            var       attempts  = 0;
            bool      result    = false;

            do
            {
                if (Token.IsCancellationRequested)
                {
                    break;
                }

                exception = null;

                try
                {
                    Logger.Trace($"Download of {Url} to {Destination} Attempt {attempts + 1} of {RetryCount + 1}");

                    var fileExistsAndValid = false;
                    if (Destination.FileExists())
                    {
                        if (ValidationHash == null)
                        {
                            Destination.Delete();
                        }
                        else
                        {
                            var md5 = fileSystem.CalculateFileMD5(Destination);
                            result = md5.Equals(ValidationHash, StringComparison.CurrentCultureIgnoreCase);

                            if (result)
                            {
                                Logger.Trace($"Download previously exists & confirmed {md5}");
                                fileExistsAndValid = true;
                            }
                        }
                    }

                    if (!fileExistsAndValid)
                    {
                        using (var destinationStream = fileSystem.OpenWrite(Destination, FileMode.Append))
                        {
                            result = Utils.Download(Logger, Url, destinationStream,
                                                    (value, total) =>
                            {
                                UpdateProgress(value, total);
                                return(!Token.IsCancellationRequested);
                            });
                        }

                        if (result && ValidationHash != null)
                        {
                            var md5 = fileSystem.CalculateFileMD5(Destination);
                            result = md5.Equals(ValidationHash, StringComparison.CurrentCultureIgnoreCase);

                            if (!result)
                            {
                                Logger.Warning($"Downloaded MD5 {md5} does not match {ValidationHash}. Deleting {Destination}.");
                                fileSystem.FileDelete(TargetDirectory);
                            }
                            else
                            {
                                Logger.Trace($"Download confirmed {md5}");
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            } while (attempts++ < RetryCount);

            if (!result)
            {
                Token.ThrowIfCancellationRequested();
                throw new DownloadException("Error downloading file", exception);
            }

            return(Destination);
        }
Exemplo n.º 7
0
        public async Task CopyAsync(CancellationToken cancellation = default)
        {
            if (Options.HasFlag(FileCopyOptions.VerifyFileHash) && HashAlgorithm == default)
            {
                throw new Exception($"The {FileCopyOptions.VerifyFileHash} bit flag was set, but no hashing algorithm was specified.");
            }

            stopwatch.Start();
            OnStarted(this, new FileCopyStartedEventArgs2(Source, Destination));
            try
            {
                using (var freader = OpenSource())
                    using (var fwriter = OpenDestination())
                    {
                        if (freader.Position != fwriter.Position)
                        {
                            freader.Position = fwriter.Position;
                        }

                        var inputBuffer  = new byte[BufferSize];
                        var bytesWritten = 0;
                        var tries        = 0;

                        while (true)
                        {
                            try
                            {
                                int bytesRead;
                                while (0 != (bytesRead = await freader.ReadAsync(inputBuffer, 0, inputBuffer.Length, cancellation)) &&
                                       !cancellation.IsCancellationRequested)
                                {
                                    cancellation.ThrowIfCancellationRequested();
                                    bytesWritten += await CopyBytesAsync(inputBuffer, bytesRead, fwriter);

                                    if (Options.HasFlag(FileCopyOptions.VerifyFileHash))
                                    {
                                        HashAlgorithm.TransformBlock(inputBuffer, 0, bytesRead, inputBuffer, 0);
                                        OnChunkHashed(this, new FileHashProgressEventArgs(Source, new FileHashProgressData(Source.Length, bytesRead, sourceHash.Count, stopwatch.Elapsed)));
                                    }

                                    OnChunkTransferred(this, new FileTransferProgressEventArgs(Source, Destination, new FileTransferProgressData(Source.Length, bytesRead, bytesWritten, stopwatch.Elapsed)));
                                }


                                if (Options.HasFlag(FileCopyOptions.VerifyFileHash))
                                {
                                    HashAlgorithm.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
                                    sourceHash = HashAlgorithm.Hash.ToList();
                                }


                                break;
                            }
                            catch (Exception e)
                            {
                                if (e is OperationCanceledException)
                                {
                                    throw;
                                }
                                if (!RetrySettings.Retry || tries >= RetrySettings.RetryCount)
                                {
                                    throw;
                                }

                                OnRetryStarted(this, new FileCopyRetryStartedEventArgs(tries++, RetrySettings.RetryInterval, e));
                            }
                        }
                    }

                cancellation.ThrowIfCancellationRequested();

                if (Options.HasFlag(FileCopyOptions.VerifyFileHash))
                {
                    stopwatch.Reset();
                    Destination.Refresh();
                    EnsureChecksumsMatch(cancellation);
                }
            }
            catch (OperationCanceledException)
            {
                if (!Options.HasFlag(FileCopyOptions.Restartable))
                {
                    Destination.Delete();
                }

                throw;
            }

            if (Options.HasFlag(FileCopyOptions.DeleteSourceOnSuccessfulCopy))
            {
                Source.Delete();
            }

            OnCompleted(this, EventArgs.Empty);
        }
        /// <summary>
        /// Delete local (source) files that do not exist in the destination.
        /// </summary>
        private bool DeleteLocalGhostFiles()
        {
            Logger.WriteLog(ErrorCodes.SyncPhase_DeletionBegun,
                            ErrorResources.SyncPhase_DeletionBegun, Severity.Information, VerboseLevel.User, true);

            DiscoveredObject[] files      = Destination.GetObjects();
            string             currentDir = null;

            for (int i = 0; i < files.Length; i++)
            {
                string localFile = $"{_path}{files[i].FullName}";

                ScanProgress(i, files.Length, localFile);

                if (files[i].Kind == ObjectKind.File)
                {
                    if ((Transform != null) && (Transform.IsSecured))
                    {
                        localFile = Helpers.RemoveSecExt(localFile);
                    }
                    else if ((Transform != null) && (!Transform.IsSecured))
                    {
                        localFile = $"{localFile}{Constants.EncryptedExt}";
                    }

                    if (!File.Exists(localFile))
                    {
                        if (Destination.Delete(files[i].FullName, _wideDisplay))
                        {
                            Interlocked.Increment(ref _deletedCount);
                        }
                        else
                        {
                            Interlocked.Increment(ref _errorCount);
                        }
                    }

                    if ((currentDir == null) && (currentDir != files[i].DirectoryName))
                    {
                        if ((currentDir != null) && !Destination.AfterDirectoryScan(currentDir, _wideDisplay))
                        {
                            Interlocked.Increment(ref _errorCount);
                        }

                        currentDir = files[i].DirectoryName;
                    }
                }
                else if (files[i].Kind == ObjectKind.Directory)
                {
                    if (!Destination.AfterDirectoryScan(files[i].FullName, _wideDisplay))
                    {
                        Interlocked.Increment(ref _errorCount);
                    }
                }
                else
                {
                    throw new SmkException($"Unsupported type for {files[i].GetType().Name}.{files[i].Kind}");
                }
            }

            Logger.WriteLog(ErrorCodes.SyncPhase_DeletionEnded,
                            ErrorResources.SyncPhase_DeletionEnded, Severity.Information, VerboseLevel.User, true);

            return(_errorCount == 0);
        }