Esempio n. 1
0
        /// <summary>
        /// Background thread to do the downloading and installing of updates.
        /// </summary>
        /// <param name="sender">The object triggering this event/</param>
        /// <param name="e">Event argument.</param>
        private void downloader_DoWork(object sender, DoWorkEventArgs e)
        {
            List <DownloadInfo>    downloads       = (List <DownloadInfo>)e.Argument;
            SteppedProgressManager overallProgress = new SteppedProgressManager();
            long totalDownloadSize = downloads.Sum(delegate(DownloadInfo download)
            {
                return(download.FileSize);
            });

            foreach (DownloadInfo download in downloads)
            {
                ProgressManagerBase         downloadProgress = null;
                ProgressChangedEventHandler localHandler     =
                    delegate(object sender2, ProgressChangedEventArgs e2)
                {
                    DownloadInfo downloadInfo = (DownloadInfo)sender2;
                    if (downloadProgress == null)
                    {
                        downloadProgress = e2.Progress;
                        overallProgress.Steps.Add(new SteppedProgressManagerStep(
                                                      e2.Progress, download.FileSize / (float)totalDownloadSize));
                    }

                    downloader_ProgressChanged(sender2,
                                               new ProgressChangedEventArgs(overallProgress, e2.UserState));
                };

                download.Download(localHandler);
            }

            e.Result = e.Argument;
        }
Esempio n. 2
0
        /// <summary>
        /// Handles the progress event by the task.
        /// </summary>
        private void progressTimer_Tick(object sender, EventArgs e)
        {
            ListViewItem item = (ListViewItem)schedulerProgress.Tag;

            if (item == null)
            {
                return;
            }
            Task task = (Task)item.Tag;

            if (!task.Executing)
            {
                //The task is done! Bail out and let the completion handler reset the UI
                return;
            }

            //Update the progress bar
            SteppedProgressManager progress = task.Progress;

            if (progress != null)
            {
                schedulerProgress.Style = progress.ProgressIndeterminate ?
                                          ProgressBarStyle.Marquee : ProgressBarStyle.Continuous;

                if (!progress.ProgressIndeterminate)
                {
                    schedulerProgress.Value = (int)(progress.Progress * 1000.0);
                }
            }
        }
Esempio n. 3
0
        private void UploadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            IList <BlackBoxReport> reports         = (IList <BlackBoxReport>)e.Argument;
            SteppedProgressManager overallProgress = new SteppedProgressManager();

            for (int i = 0; i < reports.Count; ++i)
            {
                //Create the progress object that will handle the progress for this report.
                ProgressManager reportProgress = new ProgressManager();
                overallProgress.Steps.Add(new SteppedProgressManagerStep(reportProgress,
                                                                         1.0f / reports.Count));

                //Allow us to bail out.
                if (UploadWorker.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                //If we have not submitted the report before upload it.
                if (reports[i].Status == BlackBoxReportStatus.New)
                {
                    Upload(reports[i], overallProgress, reportProgress);
                }

                //Otherwise check for solutions.
                else
                {
                    CheckStatus(reports[i], overallProgress, reportProgress);
                }
            }
        }
Esempio n. 4
0
        public override void Execute()
        {
            //If the path doesn't exist, exit.
            if (!(File.Exists(Path) || Directory.Exists(Path)))
            {
                return;
            }

            //Create the progress manager.
            Progress = new SteppedProgressManager();

            try
            {
                //Depending on whether the path is a file or directory, execute the
                //correct function.
                if ((File.GetAttributes(Path) & FileAttributes.Directory) != 0)
                {
                    DirectoryInfo info = new DirectoryInfo(Path);
                    CopyDirectory(info);
                }
                else
                {
                    FileInfo info = new FileInfo(Path);
                    CopyFile(info);
                }
            }
            finally
            {
                Progress = null;
            }
        }
Esempio n. 5
0
        private void Upload(BlackBoxReport report, SteppedProgressManager overallProgress,
                            ProgressManager reportProgress)
        {
            //Upload the report.
            UploadWorker.ReportProgress((int)(overallProgress.Progress * 100),
                                        S._("Compressing Report {0}", report.Name));

            reportProgress.Total = int.MaxValue;
            BlackBoxReportUploader uploader = new BlackBoxReportUploader(report);

            uploader.Submit(delegate(object from, EraserProgressChangedEventArgs e2)
            {
                SteppedProgressManager reportSteps = (SteppedProgressManager)e2.Progress;
                reportProgress.Completed           = (int)(reportSteps.Progress * reportProgress.Total);
                int step = reportSteps.Steps.IndexOf(reportSteps.CurrentStep);

                UploadWorker.ReportProgress((int)(overallProgress.Progress * 100),
                                            step == 0 ?
                                            S._("Compressing Report {0}", report.Name) :
                                            S._("Uploading Report {0}", report.Name));

                if (UploadWorker.CancellationPending)
                {
                    throw new OperationCanceledException();
                }
            });
        }
Esempio n. 6
0
        /// <summary>
        /// Compresses the report, then uploads it to the server.
        /// </summary>
        /// <param name="progressChanged">The progress changed event handler that should
        /// be called for upload progress updates.</param>
        public void Submit(ProgressChangedEventHandler progressChanged)
        {
            SteppedProgressManager overallProgress = new SteppedProgressManager();

            Compress(overallProgress, progressChanged);

            using (FileStream dumpFile = new FileStream(ReportBaseName + ".tar.7z",
                                                        FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.DeleteOnClose))
            {
                List <PostDataField> fields = GetStackTraceField(Report.StackTrace);
                fields.Add(new PostDataFileField("crashReport", "Report.tar.7z", dumpFile));

                ProgressManager progress = new ProgressManager();
                overallProgress.Steps.Add(new SteppedProgressManagerStep(
                                              progress, 0.5f, "Uploading"));

                XmlDocument result = QueryServer("upload", delegate(long uploaded, long total)
                {
                    progress.Total     = total;
                    progress.Completed = uploaded;
                    progressChanged(this, new ProgressChangedEventArgs(overallProgress, null));
                }, fields.ToArray());

                //Parse the result document
                XmlNode node         = result.SelectSingleNode("/crashReport");
                string  reportStatus = node.Attributes.GetNamedItem("status").Value;
                if (reportStatus == "exists")
                {
                    string reportId = node.Attributes.GetNamedItem("id").Value;
                    Report.Status = BlackBoxReportStatus.Uploaded;
                    Report.ID     = Convert.ToInt32(reportId);
                }
            }
        }
 private void UploadWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     IList<BlackBoxReport> reports = (IList<BlackBoxReport>)e.Argument;
        SteppedProgressManager overallProgress = new SteppedProgressManager();
        for (int i = 0; i < reports.Count; ++i)
        {
     ProgressManager reportProgress = new ProgressManager();
     overallProgress.Steps.Add(new SteppedProgressManagerStep(reportProgress,
      1.0f / reports.Count));
     BlackBoxReportUploader uploader = new BlackBoxReportUploader(reports[i]);
     UploadWorker.ReportProgress((int)(overallProgress.Progress * 100),
      S._("Checking for status of report {0}...", reports[i].Name));
     if (!uploader.IsNew)
      continue;
     if (UploadWorker.CancellationPending)
      throw new OperationCanceledException();
     UploadWorker.ReportProgress((int)(overallProgress.Progress * 100),
      S._("Compressing Report {0}: {1:#0.00%}", reports[i].Name, 0));
     uploader.Submit(delegate(object from, EraserProgressChangedEventArgs e2)
      {
       reportProgress.Completed = (int)(e2.Progress.Progress * reportProgress.Total);
       SteppedProgressManager reportSteps = (SteppedProgressManager)e2.Progress;
       int step = reportSteps.Steps.IndexOf(reportSteps.CurrentStep);
       UploadWorker.ReportProgress((int)overallProgress.Progress,
        step == 0 ?
     S._("Compressing Report {0}: {1:#0.00%}",
      reports[i].Name, reportSteps.Progress) :
     S._("Uploading Report {0}: {1:#0.00%}",
      reports[i].Name, reportSteps.Progress));
       if (UploadWorker.CancellationPending)
        throw new OperationCanceledException();
      });
        }
 }
Esempio n. 8
0
 public SevenZipProgressCallback(BlackBoxReportUploader uploader,
                                 SteppedProgressManager progress, ProgressManager stepProgress,
                                 ProgressChangedEventHandler progressChanged)
 {
     Uploader           = uploader;
     Progress           = progress;
     StepProgress       = stepProgress;
     EventHandler       = progressChanged;
     LastProgressReport = DateTime.MinValue;
 }
Esempio n. 9
0
        private void CheckStatus(BlackBoxReport report, SteppedProgressManager overallProgress,
                                 ProgressManager reportProgress)
        {
            //Upload the report.
            UploadWorker.ReportProgress((int)(overallProgress.Progress * 100),
                                        S._("Checking for solution for {0}...", report.Name));

            BlackBoxReportUploader uploader = new BlackBoxReportUploader(report);

            report.Status = uploader.Status;
        }
Esempio n. 10
0
        public override void Execute()
        {
            Progress = new SteppedProgressManager();

            try
            {
                base.Execute();
            }
            finally
            {
                Progress = null;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Handles the download progress changed event.
        /// </summary>
        /// <param name="sender">The object triggering this event/</param>
        /// <param name="e">Event argument.</param>
        private void downloader_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                if (updateListDownloader.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                Invoke((EventHandler <ProgressChangedEventArgs>)downloader_ProgressChanged,
                       sender, e);
                return;
            }

            DownloadInfo           download        = (DownloadInfo)sender;
            DownloadUIInfo         downloadUIInfo  = DownloadItems[download];
            SteppedProgressManager overallProgress = (SteppedProgressManager)e.Progress;

            if (e.UserState is Exception)
            {
                downloadUIInfo.ListViewItem.ImageIndex       = 3;
                downloadUIInfo.ListViewItem.SubItems[1].Text = S._("Error");
                downloadUIInfo.ListViewItem.ToolTipText      = ((Exception)e.UserState).Message;
            }
            else
            {
                if (overallProgress.CurrentStep.Progress.Progress >= 1.0f)
                {
                    downloadUIInfo.ListViewItem.ImageIndex       = -1;
                    downloadUIInfo.ListViewItem.SubItems[1].Text = S._("Downloaded");
                }
                else
                {
                    downloadUIInfo.Downloaded = (long)
                                                (overallProgress.CurrentStep.Progress.Progress * download.FileSize);
                    downloadUIInfo.ListViewItem.ImageIndex       = 0;
                    downloadUIInfo.ListViewItem.SubItems[1].Text = FileSize.ToString(download.FileSize -
                                                                                     downloadUIInfo.Downloaded);
                }
            }

            downloadingItemLbl.Text    = S._("Downloading: {0}", download.Name);
            downloadingItemPb.Value    = (int)(overallProgress.CurrentStep.Progress.Progress * 100);
            downloadingOverallPb.Value = (int)(overallProgress.Progress * 100);
            downloadingOverallLbl.Text = S._("Overall progress: {0} left",
                                             FileSize.ToString(DownloadItems.Values.Sum(delegate(DownloadUIInfo item)
            {
                return(item.Download.FileSize - item.Downloaded);
            }
                                                                                        )));
        }
Esempio n. 12
0
        /// <summary>
        /// Executes the task in the context of the calling thread.
        /// </summary>
        public void Execute()
        {
            OnTaskStarted();
            Executing = true;
            Canceled  = false;
            Progress  = new SteppedProgressManager();

            try
            {
                //Run the task
                foreach (IErasureTarget target in Targets)
                {
                    try
                    {
                        Progress.Steps.Add(new ErasureTargetProgressManagerStep(
                                               target, Targets.Count));
                        target.Execute();
                    }
                    catch (FatalException)
                    {
                        throw;
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (NotSupportedException e)
                {
                    //This is thrown whenever we try to erase files on an unsupported
                    //filesystem.
                    Logger.Log(e.Message, LogLevel.Error);
                }
                catch (UnauthorizedAccessException e)
                {
                    //The OS denied us access to erasing the file.
                    Logger.Log(e.Message, LogLevel.Error);
                }
                catch (PathTooLongException e)
                {
                    //Until we have code to deal with paths using NT names, we can't
                    //do much about it.
                    Logger.Log(e.Message, LogLevel.Error);
                }
                catch (SharingViolationException)
                {
                }
            }
Esempio n. 13
0
        /// <summary>
        /// Wrapper around <see cref="FileSystemObjectErasureTarget.EraseStream"/>
        /// that will erase every stream in the provided file.
        /// </summary>
        /// <param name="info">The file to erase.</param>
        /// <param name="eraseProgress">The progress manager for the entire
        /// erasure of the file.</param>
        private void EraseFile(FileInfo info, SteppedProgressManager eraseProgress)
        {
            List <StreamInfo> streams = new List <StreamInfo>(info.GetADSes());

            streams.Add(new StreamInfo(info.FullName));
            long fileSize = streams.Sum(x => x.Length);

            foreach (StreamInfo stream in streams)
            {
                ProgressManager progress = new ProgressManager();
                eraseProgress.Steps.Add(new SteppedProgressManagerStep(progress,
                                                                       stream.Length / (float)fileSize,
                                                                       S._("Erasing incomplete destination file")));
                EraseStream(stream, progress);
            }
        }
        public override void Execute()
        {
            Progress = new SteppedProgressManager();

            try
            {
                base.Execute();

                //Empty the contents of the Recycle Bin
                EmptyRecycleBin();
            }
            finally
            {
                Progress = null;
            }
        }
Esempio n. 15
0
        private void CopyFile(FileInfo info)
        {
            ProgressManager copyProgress = new ProgressManager();
            int             totalPasses  = 1 + EffectiveMethod.Passes;

            Progress.Steps.Add(new SteppedProgressManagerStep(copyProgress, 1.0f / totalPasses,
                                                              S._("Copying source files to destination...")));

            try
            {
                //Make sure all necessary folders exist before the copy.
                Directory.CreateDirectory(Destination);

                //Then copy the file.
                string path = System.IO.Path.Combine(Destination, info.Name);
                info.CopyTo(path, delegate(long TotalFileSize, long TotalBytesTransferred)
                {
                    return(CopyProgress(copyProgress, info, TotalFileSize,
                                        TotalBytesTransferred));
                });
            }
            catch (OperationCanceledException)
            {
                //The copy was cancelled: Complete the copy part.
                copyProgress.MarkComplete();

                //We need to erase the partially copied copy of the file.
                SteppedProgressManager destroyProgress = new SteppedProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(destroyProgress, 0.5f,
                                                                  S._("Erasing incomplete destination file")));
                EraseFile(new FileInfo(Destination), destroyProgress);

                //Rethrow the exception.
                throw;
            }

            //Mark the copy as complete.
            copyProgress.MarkComplete();

            //Erase the source copy.
            SteppedProgressManager eraseProgress = new SteppedProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(eraseProgress,
                                                              (totalPasses - 1) / (float)totalPasses,
                                                              S._("Erasing source files...")));
            EraseFile(info, eraseProgress);
        }
Esempio n. 16
0
        public override void Execute()
        {
            Progress = new SteppedProgressManager();

            try
            {
                base.Execute();

                //Remove the contents of the folder, deleting the folder if it is empty
                //at the end of it.
                EraseFolder();
            }
            finally
            {
                Progress = null;
            }
        }
Esempio n. 17
0
 private void EraseUnusedSpace(Task task, UnusedSpaceTarget target)
 {
     if (!AdvApi.IsAdministrator())
        {
     if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
      Environment.OSVersion.Version >= new Version(6, 0))
     {
      throw new UnauthorizedAccessException(S._("The program does not have the " +
       "required permissions to erase the unused space on disk. Run the program " +
       "as an administrator and retry the operation."));
     }
     else
      throw new UnauthorizedAccessException(S._("The program does not have the " +
       "required permissions to erase the unused space on disk."));
        }
        if (SystemRestore.GetInstances().Count != 0)
        {
     task.Log.LastSessionEntries.Add(new LogEntry(S._("The drive {0} has System " +
      "Restore or Volume Shadow Copies enabled. This may allow copies of files " +
      "stored on the disk to be recovered and pose a security concern.",
      target.Drive), LogLevel.Warning));
        }
        if (VolumeInfo.FromMountpoint(target.Drive).HasQuota)
     task.Log.LastSessionEntries.Add(new LogEntry(S._("The drive {0} has disk quotas " +
      "active. This will prevent the complete erasure of unused space and may pose " +
      "a security concern.", target.Drive), LogLevel.Warning));
        ErasureMethod method = target.Method;
        DirectoryInfo info = new DirectoryInfo(target.Drive);
        VolumeInfo volInfo = VolumeInfo.FromMountpoint(target.Drive);
        FileSystem fsManager = FileSystemManager.Get(volInfo);
        SteppedProgressManager progress = new SteppedProgressManager();
        target.Progress = progress;
        task.Progress.Steps.Add(new SteppedProgressManager.Step(
     progress, 1.0f / task.Targets.Count));
        if (target.EraseClusterTips)
        {
     ProgressManager tipSearch = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(tipSearch,
      0.0f, S._("Searching for files' cluster tips...")));
     tipSearch.Total = 1;
     ClusterTipsSearchProgress searchProgress = delegate(string path)
      {
       if (currentTask.Canceled)
        throw new OperationCanceledException(S._("The task was cancelled."));
       task.OnProgressChanged(target,
        new ProgressChangedEventArgs(tipSearch,
     new TaskProgressChangedEventArgs(path, 0, 0)));
      };
     ProgressManager tipProgress = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(tipProgress, 0.1f,
      S._("Erasing cluster tips...")));
     ClusterTipsEraseProgress eraseProgress =
      delegate(int currentFile, int totalFiles, string currentFilePath)
      {
       tipSearch.Completed = tipSearch.Total;
       tipProgress.Total = totalFiles;
       tipProgress.Completed = currentFile;
       task.OnProgressChanged(target,
        new ProgressChangedEventArgs(tipProgress,
     new TaskProgressChangedEventArgs(currentFilePath, 0, 0)));
       if (currentTask.Canceled)
        throw new OperationCanceledException(S._("The task was cancelled."));
      };
     fsManager.EraseClusterTips(VolumeInfo.FromMountpoint(target.Drive),
      method, task.Log, searchProgress, eraseProgress);
        }
        info = info.CreateSubdirectory(Path.GetFileName(
     FileSystem.GenerateRandomFileName(info, 18)));
        try
        {
     if (Eraser.Util.File.IsCompressed(info.FullName))
      Eraser.Util.File.SetCompression(info.FullName, false);
     ProgressManager mainProgress = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(mainProgress,
      target.EraseClusterTips ? 0.8f : 0.9f, S._("Erasing unused space...")));
     while (volInfo.AvailableFreeSpace > 0)
     {
      string currFile = FileSystem.GenerateRandomFileName(info, 18);
      using (FileStream stream = new FileStream(currFile, FileMode.CreateNew,
       FileAccess.Write, FileShare.None, 8, FileOptions.WriteThrough))
      {
       mainProgress.Total = mainProgress.Completed + volInfo.AvailableFreeSpace;
       long streamLength = Math.Min(ErasureMethod.FreeSpaceFileUnit,
        mainProgress.Total);
       while (true)
        try
        {
     stream.SetLength(streamLength);
     break;
        }
        catch (IOException)
        {
     if (streamLength > volInfo.ClusterSize)
      streamLength -= volInfo.ClusterSize;
     else
      throw;
        }
       method.Erase(stream, long.MaxValue,
        PrngManager.GetInstance(ManagerLibrary.Settings.ActivePrng),
        delegate(long lastWritten, long totalData, int currentPass)
        {
     mainProgress.Completed += lastWritten;
     task.OnProgressChanged(target,
      new ProgressChangedEventArgs(mainProgress,
       new TaskProgressChangedEventArgs(target.Drive, currentPass, method.Passes)));
     if (currentTask.Canceled)
      throw new OperationCanceledException(S._("The task was cancelled."));
        }
       );
      }
     }
     mainProgress.Completed = mainProgress.Total;
     ProgressManager residentProgress = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(residentProgress,
      0.05f, S._("Old resident file system table files")));
     fsManager.EraseOldFileSystemResidentFiles(volInfo, info, method,
      delegate(int currentFile, int totalFiles)
      {
       residentProgress.Completed = currentFile;
       residentProgress.Total = totalFiles;
       task.OnProgressChanged(target,
        new ProgressChangedEventArgs(residentProgress,
     new TaskProgressChangedEventArgs(string.Empty, 0, 0)));
       if (currentTask.Canceled)
        throw new OperationCanceledException(S._("The task was cancelled."));
      }
     );
     residentProgress.Completed = residentProgress.Total = 1;
        }
        finally
        {
     ProgressManager tempFiles = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(tempFiles,
      0.0f, S._("Removing temporary files...")));
     task.OnProgressChanged(target, new ProgressChangedEventArgs(tempFiles,
      new TaskProgressChangedEventArgs(string.Empty, 0, 0)));
     fsManager.DeleteFolder(info);
     tempFiles.Completed = tempFiles.Total = 1;
        }
        ProgressManager structureProgress = new ProgressManager();
        progress.Steps.Add(new SteppedProgressManager.Step(structureProgress,
     0.05f, S._("Erasing unused directory structures...")));
        fsManager.EraseDirectoryStructures(volInfo,
     delegate(int currentFile, int totalFiles)
     {
      if (currentTask.Canceled)
       throw new OperationCanceledException(S._("The task was cancelled."));
      structureProgress.Total = totalFiles;
      structureProgress.Completed = currentFile;
      task.OnProgressChanged(target,
       new ProgressChangedEventArgs(structureProgress,
        new TaskProgressChangedEventArgs(string.Empty, 0, 0)));
     }
        );
        structureProgress.Completed = structureProgress.Total;
        target.Progress = null;
 }
Esempio n. 18
0
        private void UpdateProgress()
        {
            if (!task.Executing)
            {
                //The task is done! Bail out and let the completion handler reset the UI
                return;
            }

            //Get the name of the current erasure target to display the overall status
            SteppedProgressManager           taskProgress = task.Progress;
            ErasureTargetProgressManagerStep taskStep     =
                (ErasureTargetProgressManagerStep)taskProgress.CurrentStep;

            if (taskStep == null)
            {
                return;
            }
            else if (!string.IsNullOrEmpty(taskStep.Name))
            {
                status.Text = taskStep.Name;
            }
            else
            {
                status.Text = S._("Erasing...");
            }

            //The get the current step of the target to set the current item name
            SteppedProgressManagerStepBase targetStep =
                (SteppedProgressManagerStepBase)taskStep.Target.Progress.CurrentStep;

            if (targetStep == null)
            {
                return;
            }
            else if (!string.IsNullOrEmpty(targetStep.Name))
            {
                item.Text = WrapItemName(targetStep.Name);
            }

            //Determine if the tag information of the step's progress manager is an
            //object array or a string.
            ProgressManagerBase targetStepProgress = targetStep.Progress;

            {
                object tag = targetStepProgress.Tag;
                if (tag == null)
                {
                    if (string.IsNullOrEmpty(targetStep.Name))
                    {
                        item.Text = string.Empty;
                    }
                }
                else if (tag.GetType() == typeof(string))
                {
                    item.Text = (string)tag;
                }
                else if (tag.GetType() == typeof(int[]))
                {
                    pass.Text = S._("{0} out of {1}", ((int[])tag)[0], ((int[])tag)[1]);
                }
            }

            if (targetStepProgress.TimeLeft >= TimeSpan.Zero)
            {
                timeLeft.Text = S._("About {0} left", RoundToSeconds(targetStepProgress.TimeLeft));
            }
            else
            {
                timeLeft.Text = S._("Unknown");
            }

            if (!targetStepProgress.ProgressIndeterminate)
            {
                itemProgress.Style   = ProgressBarStyle.Continuous;
                itemProgress.Value   = (int)(targetStepProgress.Progress * 1000);
                itemProgressLbl.Text = targetStepProgress.Progress.ToString("#0%",
                                                                            CultureInfo.CurrentCulture);
            }
            else
            {
                itemProgress.Style   = ProgressBarStyle.Marquee;
                itemProgressLbl.Text = string.Empty;
            }

            if (!taskProgress.ProgressIndeterminate)
            {
                overallProgress.Style   = ProgressBarStyle.Continuous;
                overallProgress.Value   = (int)(taskProgress.Progress * 1000);
                overallProgressLbl.Text = S._("Total: {0,2:#0.00%}", taskProgress.Progress);
            }
            else
            {
                overallProgress.Style   = ProgressBarStyle.Marquee;
                overallProgressLbl.Text = S._("Total: Unknown");
            }
        }
Esempio n. 19
0
 private void downloader_DoWork(object sender, DoWorkEventArgs e)
 {
     List<DownloadInfo> downloads = (List<DownloadInfo>)e.Argument;
        SteppedProgressManager overallProgress = new SteppedProgressManager();
        long totalDownloadSize = downloads.Sum(delegate(DownloadInfo download)
     {
      return download.FileSize;
     });
        foreach (DownloadInfo download in downloads)
        {
     ProgressManagerBase downloadProgress = null;
     ProgressChangedEventHandler localHandler =
      delegate(object sender2, ProgressChangedEventArgs e2)
      {
       DownloadInfo downloadInfo = (DownloadInfo)sender2;
       if (downloadProgress == null)
       {
        downloadProgress = e2.Progress;
        overallProgress.Steps.Add(new SteppedProgressManagerStep(
     e2.Progress, download.FileSize / (float)totalDownloadSize));
       }
       downloader_ProgressChanged(sender2,
        new ProgressChangedEventArgs(overallProgress, e2.UserState));
      };
     download.Download(localHandler);
        }
        e.Result = e.Argument;
 }
Esempio n. 20
0
 private void EraseFilesystemObject(Task task, FileSystemObjectTarget target)
 {
     long dataTotal = 0;
        List<string> paths = target.GetPaths(out dataTotal);
        ErasureMethod method = target.Method;
        TaskEventArgs eventArgs = new TaskEventArgs(task);
        SteppedProgressManager progress = new SteppedProgressManager();
        target.Progress = progress;
        task.Progress.Steps.Add(new SteppedProgressManager.Step(progress, 1.0f / task.Targets.Count));
        for (int i = 0; i < paths.Count; ++i)
        {
     ProgressManager step = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(step,
      1.0f / paths.Count, S._("Erasing files...")));
     task.OnProgressChanged(target,
      new ProgressChangedEventArgs(step,
       new TaskProgressChangedEventArgs(paths[i], 0, method.Passes)));
     StreamInfo info = new StreamInfo(paths[i]);
     FileSystem fsManager = FileSystemManager.Get(
      VolumeInfo.FromMountpoint(info.DirectoryName));
     if (!info.Exists)
     {
      task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} was not erased " +
       "as the file does not exist.", paths[i]), LogLevel.Notice));
      continue;
     }
     bool isReadOnly = false;
     try
     {
      if (isReadOnly = info.IsReadOnly)
       info.IsReadOnly = false;
      if ((info.Attributes & FileAttributes.Compressed) != 0 ||
       (info.Attributes & FileAttributes.Encrypted) != 0 ||
       (info.Attributes & FileAttributes.SparseFile) != 0)
      {
       task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} could " +
        "not be erased because the file was either compressed, encrypted or " +
        "a sparse file.", info.FullName), LogLevel.Error));
      }
      fsManager.EraseFileSystemObject(info, method,
       delegate(long lastWritten, long totalData, int currentPass)
       {
        if (currentTask.Canceled)
     throw new OperationCanceledException(S._("The task was cancelled."));
        step.Completed += lastWritten;
        step.Total = totalData;
        task.OnProgressChanged(target,
     new ProgressChangedEventArgs(step,
      new TaskProgressChangedEventArgs(info.FullName, currentPass, method.Passes)));
       });
      FileInfo fileInfo = info.File;
      if (fileInfo != null)
       fsManager.DeleteFile(fileInfo);
      step.Completed = step.Total = 1;
     }
     catch (UnauthorizedAccessException)
     {
      task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} could not " +
       "be erased because the file's permissions prevent access to the file.",
       info.FullName), LogLevel.Error));
     }
     catch (FileLoadException)
     {
      if (!ManagerLibrary.Settings.ForceUnlockLockedFiles)
       throw;
      List<System.Diagnostics.Process> processes = new List<System.Diagnostics.Process>();
      foreach (OpenHandle handle in OpenHandle.Items)
       if (handle.Path == paths[i])
        processes.Add(System.Diagnostics.Process.GetProcessById(handle.ProcessId));
      StringBuilder processStr = new StringBuilder();
      foreach (System.Diagnostics.Process process in processes)
       processStr.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
        "{0}, ", process.MainModule.FileName);
      task.Log.LastSessionEntries.Add(new LogEntry(S._(
       "Could not force closure of file \"{0}\" (locked by {1})",
       paths[i], processStr.ToString().Remove(processStr.Length - 2)), LogLevel.Error));
     }
     finally
     {
      if (isReadOnly && info.Exists && !info.IsReadOnly)
       info.IsReadOnly = isReadOnly;
     }
        }
        if (target is FolderTarget)
        {
     ProgressManager step = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(step,
      0.0f, S._("Removing folders...")));
     FolderTarget fldr = (FolderTarget)target;
     FileSystem fsManager = FileSystemManager.Get(VolumeInfo.FromMountpoint(fldr.Path));
     Action<DirectoryInfo> eraseEmptySubFolders = null;
     eraseEmptySubFolders = delegate(DirectoryInfo info)
     {
       foreach (DirectoryInfo subDir in info.GetDirectories())
        eraseEmptySubFolders(subDir);
       task.OnProgressChanged(target,
        new ProgressChangedEventArgs(step,
     new TaskProgressChangedEventArgs(info.FullName, 0, 0)));
       FileSystemInfo[] files = info.GetFileSystemInfos();
       if (files.Length == 0)
        fsManager.DeleteFolder(info);
     };
     eraseEmptySubFolders(new DirectoryInfo(fldr.Path));
     if (fldr.DeleteIfEmpty)
     {
      DirectoryInfo info = new DirectoryInfo(fldr.Path);
      task.OnProgressChanged(target,
       new ProgressChangedEventArgs(step,
        new TaskProgressChangedEventArgs(info.FullName, 0, 0)));
      bool isVolumeRoot = info.Parent == null;
      foreach (VolumeInfo volume in VolumeInfo.Volumes)
       foreach (string mountPoint in volume.MountPoints)
        if (info.FullName == mountPoint)
     isVolumeRoot = true;
      if (!isVolumeRoot && info.Exists && info.GetFiles("*", SearchOption.AllDirectories).Length == 0)
       fsManager.DeleteFolder(info);
     }
        }
        if (target is RecycleBinTarget)
        {
     ProgressManager step = new ProgressManager();
     progress.Steps.Add(new SteppedProgressManager.Step(step,
      0.0f, S._("Emptying recycle bin...")));
     task.OnProgressChanged(target,
      new ProgressChangedEventArgs(step,
       new TaskProgressChangedEventArgs(string.Empty, 0, 0)));
     ShellApi.EmptyRecycleBin(EmptyRecycleBinOptions.NoConfirmation |
      EmptyRecycleBinOptions.NoProgressUI | EmptyRecycleBinOptions.NoSound);
        }
        target.Progress = null;
 }
Esempio n. 21
0
 private void UpdateProgress(SteppedProgressManager targetProgress, ProgressChangedEventArgs e)
 {
     TaskProgressChangedEventArgs e2 = (TaskProgressChangedEventArgs)e.UserState;
        status.Text = targetProgress.CurrentStep.Name;
        if (e2 != null)
        {
     item.Text = WrapItemName(e2.ItemName);
     pass.Text = e2.ItemTotalPasses != 0 ?
      S._("{0} out of {1}", e2.ItemPass, e2.ItemTotalPasses) :
      e2.ItemPass.ToString(CultureInfo.CurrentCulture);
        }
        if (targetProgress.TimeLeft >= TimeSpan.Zero)
     timeLeft.Text = S._("About {0} left", RoundToSeconds(targetProgress.TimeLeft));
        else
     timeLeft.Text = S._("Unknown");
        if (targetProgress.Progress >= 0.0f)
        {
     itemProgress.Style = ProgressBarStyle.Continuous;
     itemProgress.Value = (int)(targetProgress.Progress * 1000);
     itemProgressLbl.Text = targetProgress.Progress.ToString("#0%",
      CultureInfo.CurrentCulture);
        }
        else
        {
     itemProgress.Style = ProgressBarStyle.Marquee;
     itemProgressLbl.Text = string.Empty;
        }
        overallProgress.Value = (int)(task.Progress.Progress * 1000);
        overallProgressLbl.Text = S._("Total: {0,2:#0.00%}", task.Progress.Progress);
 }
Esempio n. 22
0
        private void CopyDirectory(DirectoryInfo info)
        {
            //Check the the destination is not a subfolder of the source.
            if (PathUtil.IsRootedAt(info, Destination))
            {
                Logger.Log(S._("The destination directory cannot be within the source directory."),
                           LogLevel.Error);
                return;
            }

            //We need to get the files from the list of streams
            List <StreamInfo> streams = GetPaths();
            List <FileInfo>   files   = new List <FileInfo>(
                streams.Distinct(new StreamInfoFileEqualityComparer()).
                Select(x => x.File));
            long totalSize = streams.Sum(x => x.Length);

            foreach (FileInfo file in files)
            {
                //Compute the total size of the file on the disk (including ADSes)
                List <StreamInfo> fileStreams = new List <StreamInfo>(file.GetADSes());
                fileStreams.Add(new StreamInfo(file.FullName));
                long fileSize = fileStreams.Sum(x => x.Length);

                SteppedProgressManager fileProgress = new SteppedProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(fileProgress,
                                                                  fileSize / (float)totalSize, S._("Securely moving files and folders...")));

                //Add the copying step to the file progress.
                ProgressManager copyProgress = new ProgressManager();
                int             totalPasses  = 1 + EffectiveMethod.Passes;
                fileProgress.Steps.Add(new SteppedProgressManagerStep(copyProgress,
                                                                      1f / totalPasses));

                try
                {
                    //Compute the path to the new directory.
                    DirectoryInfo sourceDirectory = file.Directory;
                    DirectoryInfo destDirectory   = new DirectoryInfo(
                        SourceToDestinationPath(file.DirectoryName));

                    //Make sure all necessary folders exist before the copy.
                    if (!destDirectory.Exists)
                    {
                        destDirectory.Create();
                    }

                    //Then copy the file.
                    file.CopyTo(System.IO.Path.Combine(destDirectory.FullName, file.Name),
                                delegate(long TotalFileSize, long TotalBytesTransferred)
                    {
                        return(CopyProgress(copyProgress, file, TotalFileSize,
                                            TotalBytesTransferred));
                    });
                }
                catch (OperationCanceledException)
                {
                    //The copy was cancelled: Complete the copy part.
                    copyProgress.MarkComplete();

                    //We need to erase the partially copied copy of the file.
                    SteppedProgressManager destroyProgress = new SteppedProgressManager();
                    Progress.Steps.Add(new SteppedProgressManagerStep(destroyProgress, 0.5f,
                                                                      S._("Erasing incomplete destination file")));
                    EraseFile(file, destroyProgress);

                    //Rethrow the exception.
                    throw;
                }

                //We copied the file over; erase the source file
                SteppedProgressManager eraseProgress = new SteppedProgressManager();
                fileProgress.Steps.Add(new SteppedProgressManagerStep(eraseProgress,
                                                                      (totalPasses - 1) / (float)totalPasses,
                                                                      S._("Erasing source files...")));
                EraseFile(file, eraseProgress);
            }

            //Then copy the timestamps from the source folders and delete the source.
            ProgressManager folderDeleteProgress = new ProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(folderDeleteProgress, 0.0f,
                                                              S._("Removing folders...")));

            Action <DirectoryInfo> CopyTimesAndDelete = null;

            CopyTimesAndDelete = delegate(DirectoryInfo subDirectory)
            {
                foreach (DirectoryInfo child in subDirectory.GetDirectories())
                {
                    CopyTimesAndDelete(child);
                }

                //Update progress.
                folderDeleteProgress.Tag = subDirectory.FullName;

                //Get the directory which we copied to and copy the file times to the
                //destination directory
                DirectoryInfo destDirectory = new DirectoryInfo(
                    SourceToDestinationPath(subDirectory.FullName));
                if (!destDirectory.Exists)
                {
                    destDirectory.Create();
                }
                destDirectory.CopyTimes(subDirectory);

                //Then delete the source directory.
                IFileSystem fsManager = Host.Instance.FileSystems[
                    VolumeInfo.FromMountPoint(Path)];
                fsManager.DeleteFolder(subDirectory, true);
            };
            CopyTimesAndDelete(info);
        }
Esempio n. 23
0
        public override void Execute()
        {
            //Check for sufficient privileges to run the erasure.
            if (!Security.IsAdministrator())
            {
                if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                    Environment.OSVersion.Version >= new Version(6, 0))
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the disk. Run the program as an administrator and retry the operation."),
                               LogLevel.Error);
                }
                else
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the disk."), LogLevel.Error);
                }

                return;
            }

            Progress = new SteppedProgressManager();
            ProgressManager stepProgress = new ProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(stepProgress, 1.0f,
                                                              ToString()));
            FileStream stream = null;

            try
            {
                //Overwrite the entire drive
                IErasureMethod method = EffectiveMethod;
                if (Volume != null)
                {
                    stepProgress.Total = Volume.TotalSize;
                    stream             = Volume.Open(FileAccess.ReadWrite, FileShare.ReadWrite);
                }
                else if (PhysicalDrive != null)
                {
                    stepProgress.Total = PhysicalDrive.Size;
                    PhysicalDrive.DeleteDriveLayout();
                    if (PhysicalDrive.Volumes.Count == 1)
                    {
                        //This could be a removable device where Windows sees an oversized floppy.
                        stream = PhysicalDrive.Volumes[0].Open(FileAccess.ReadWrite, FileShare.ReadWrite);
                    }
                    else if (PhysicalDrive.Volumes.Count > 0)
                    {
                        throw new InvalidOperationException(S._("The partition table on the drive " +
                                                                "could not be erased."));
                    }
                    else
                    {
                        stream = PhysicalDrive.Open(FileAccess.ReadWrite, FileShare.ReadWrite);
                    }
                }
                else
                {
                    throw new InvalidOperationException(S._("The Drive erasure target requires a " +
                                                            "volume or physical drive selected for erasure."));
                }

                //Calculate the size of the erasure
                stepProgress.Total = method.CalculateEraseDataSize(null, stepProgress.Total);

                //Then run the erase task
                method.Erase(stream, long.MaxValue, Host.Instance.Prngs.ActivePrng,
                             delegate(long lastWritten, long totalData, int currentPass)
                {
                    stepProgress.Completed += lastWritten;
                    stepProgress.Tag        = new int[] { currentPass, method.Passes };

                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }
                }
                             );
            }
            finally
            {
                Progress = null;
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
        public override void Execute()
        {
            //Check for sufficient privileges to run the unused space erasure.
            if (!Security.IsAdministrator())
            {
                if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                    Environment.OSVersion.Version >= new Version(6, 0))
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the unused space on disk. Run the program as an administrator and retry " +
                                   "the operation."), LogLevel.Error);
                }
                else
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the unused space on disk."), LogLevel.Error);
                }

                return;
            }

            //Check whether System Restore has any available checkpoints.
            if (SystemRestore.GetInstances().Count != 0)
            {
                Logger.Log(S._("This computer has had System Restore or Volume Shadow Copies " +
                               "enabled. This may allow copies of files stored on the disk to be recovered " +
                               "and pose a security concern.", Drive), LogLevel.Warning);
            }

            //If the user is under disk quotas, log a warning message
            if (VolumeInfo.FromMountPoint(Drive).HasQuota)
            {
                Logger.Log(S._("The drive {0} has disk quotas active. This will prevent the " +
                               "complete erasure of unused space and may pose a security concern.",
                               Drive), LogLevel.Warning);
            }

            //Get the erasure method if the user specified he wants the default.
            IErasureMethod method = EffectiveMethod;

            //Make a folder to dump our temporary files in
            DirectoryInfo info      = new DirectoryInfo(Drive);
            VolumeInfo    volInfo   = VolumeInfo.FromMountPoint(Drive);
            IFileSystem   fsManager = Host.Instance.FileSystems[volInfo];

            //Start sampling the speed of the task.
            Progress = new SteppedProgressManager();

            //Erase the cluster tips of every file on the drive.
            if (EraseClusterTips)
            {
                //Define the callback handlers
                ProgressManager tipSearch = new ProgressManager();
                tipSearch.MarkIndeterminate();
                Progress.Steps.Add(new SteppedProgressManagerStep(tipSearch,
                                                                  0.0f, S._("Searching for files' cluster tips...")));
                ClusterTipsSearchProgress searchProgress = delegate(string path)
                {
                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }

                    tipSearch.Tag = path;
                };

                ProgressManager tipProgress = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(tipProgress, 0.1f,
                                                                  S._("Erasing cluster tips...")));
                ClusterTipsEraseProgress eraseProgress =
                    delegate(int currentFile, int totalFiles, string currentFilePath)
                {
                    tipSearch.MarkComplete();
                    tipProgress.Total     = totalFiles;
                    tipProgress.Completed = currentFile;
                    tipProgress.Tag       = currentFilePath;

                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }
                };

                //Start counting statistics
                fsManager.EraseClusterTips(VolumeInfo.FromMountPoint(Drive),
                                           method, searchProgress, eraseProgress);
                tipProgress.MarkComplete();
            }

            bool lowDiskSpaceNotifications = Shell.LowDiskSpaceNotificationsEnabled;

            info = info.CreateSubdirectory(Path.GetFileName(
                                               FileSystemBase.GenerateRandomFileName(info, 18)));
            try
            {
                //Set the folder's compression flag off since we want to use as much
                //space as possible
                if (info.IsCompressed())
                {
                    info.Uncompress();
                }

                //Disable the low disk space notifications
                Shell.LowDiskSpaceNotificationsEnabled = false;

                //Fill the disk
                EraseUnusedSpace(volInfo, info, fsManager, method);

                //Erase old resident file system table files
                ProgressManager residentProgress = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(residentProgress,
                                                                  0.05f, S._("Old resident file system table files")));
                fsManager.EraseOldFileSystemResidentFiles(volInfo, info, method,
                                                          delegate(int currentFile, int totalFiles)
                {
                    residentProgress.Completed = currentFile;
                    residentProgress.Total     = totalFiles;

                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }
                }
                                                          );

                residentProgress.MarkComplete();
            }
            finally
            {
                //Remove the folder holding all our temporary files.
                ProgressManager tempFiles = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(tempFiles,
                                                                  0.0f, S._("Removing temporary files...")));

                fsManager.DeleteFolder(info, true);
                tempFiles.MarkComplete();

                //Reset the low disk space notifications
                Shell.LowDiskSpaceNotificationsEnabled = lowDiskSpaceNotifications;
            }

            //Then clean the old file system entries
            ProgressManager structureProgress = new ProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(structureProgress,
                                                              0.05f, S._("Erasing unused directory structures...")));
            fsManager.EraseDirectoryStructures(volInfo,
                                               delegate(int currentFile, int totalFiles)
            {
                if (Task.Canceled)
                {
                    throw new OperationCanceledException(S._("The task was cancelled."));
                }

                //Compute the progress
                structureProgress.Total     = totalFiles;
                structureProgress.Completed = currentFile;
            }
                                               );

            structureProgress.MarkComplete();
            Progress = null;
        }
Esempio n. 25
0
        /// <summary>
        /// Compresses the report for uploading.
        /// </summary>
        /// <param name="progress">The <see cref="ProgressManager"/> instance that the
        /// Upload function is using.</param>
        /// <param name="progressChanged">The progress changed event handler that should
        /// be called for upload progress updates.</param>
        private void Compress(SteppedProgressManager progress,
                              ProgressChangedEventHandler progressChanged)
        {
            using (FileStream archiveStream = new FileStream(ReportBaseName + ".tar",
                                                             FileMode.Create, FileAccess.Write))
            {
                //Add the report into a tar file
                TarArchive archive = TarArchive.CreateOutputTarArchive(archiveStream);
                foreach (FileInfo file in Report.Files)
                {
                    TarEntry entry = TarEntry.CreateEntryFromFile(file.FullName);
                    entry.Name = Path.GetFileName(entry.Name);
                    archive.WriteEntry(entry, false);
                }
                archive.Close();
            }

            ProgressManager step = new ProgressManager();

            progress.Steps.Add(new SteppedProgressManagerStep(step, 0.5f, "Compressing"));
            CoderPropID[] propIDs =
            {
                CoderPropID.DictionarySize,
                CoderPropID.PosStateBits,
                CoderPropID.LitContextBits,
                CoderPropID.LitPosBits,
                CoderPropID.Algorithm,
                CoderPropID.NumFastBytes,
                CoderPropID.MatchFinder,
                CoderPropID.EndMarker
            };
            object[] properties =
            {
                (Int32)(1 << 24),                                               //Dictionary Size
                (Int32)2,                                                       //PosState Bits
                (Int32)0,                                                       //LitContext Bits
                (Int32)2,                                                       //LitPos Bits
                (Int32)2,                                                       //Algorithm
                (Int32)128,                                                     //Fast Bytes
                "bt4",                                                          //Match Finger
                true                                                            //Write end-of-stream
            };

            SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
            encoder.SetCoderProperties(propIDs, properties);

            using (FileStream sevenZipFile = new FileStream(ReportBaseName + ".tar.7z",
                                                            FileMode.Create))
                using (FileStream tarStream = new FileStream(ReportBaseName + ".tar",
                                                             FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.DeleteOnClose))
                {
                    encoder.WriteCoderProperties(sevenZipFile);
                    Int64 fileSize = -1;
                    for (int i = 0; i < 8; i++)
                    {
                        sevenZipFile.WriteByte((Byte)(fileSize >> (8 * i)));
                    }

                    step.Total = tarStream.Length;
                    ICodeProgress callback = progressChanged == null ? null :
                                             new SevenZipProgressCallback(this, progress, step, progressChanged);
                    encoder.Code(tarStream, sevenZipFile, -1, -1, callback);
                }
        }
Esempio n. 26
0
 public void Submit(ProgressChangedEventHandler progressChanged)
 {
     SteppedProgressManager overallProgress = new SteppedProgressManager();
        Compress(overallProgress, progressChanged);
        using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz",
     FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.DeleteOnClose))
        using (Stream logFile = Report.DebugLog)
        {
     PostDataBuilder builder = new PostDataBuilder();
     builder.AddPart(new PostDataField("action", "upload"));
     builder.AddPart(new PostDataFileField("crashReport", "Report.tbz", bzipFile));
     AddStackTraceToRequest(Report.StackTrace, builder);
     WebRequest reportRequest = HttpWebRequest.Create(BlackBoxServer);
     reportRequest.ContentType = builder.ContentType;
     reportRequest.Method = "POST";
     reportRequest.Timeout = int.MaxValue;
     using (Stream formStream = builder.Stream)
     {
      ProgressManager progress = new ProgressManager();
      overallProgress.Steps.Add(new SteppedProgressManagerStep(
       progress, 0.5f, "Uploading"));
      reportRequest.ContentLength = formStream.Length;
      using (Stream requestStream = reportRequest.GetRequestStream())
      {
       int lastRead = 0;
       byte[] buffer = new byte[32768];
       while ((lastRead = formStream.Read(buffer, 0, buffer.Length)) != 0)
       {
        requestStream.Write(buffer, 0, lastRead);
        progress.Completed = formStream.Position;
        progress.Total = formStream.Length;
        progressChanged(this, new ProgressChangedEventArgs(overallProgress, null));
       }
      }
     }
     try
     {
      reportRequest.GetResponse();
      Report.Submitted = true;
     }
     catch (WebException e)
     {
      using (Stream responseStream = e.Response.GetResponseStream())
      {
       try
       {
        XmlReader reader = XmlReader.Create(responseStream);
        reader.ReadToFollowing("error");
        throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture,
     "The server encountered a problem while processing the request: {0}",
     reader.ReadString()));
       }
       catch (XmlException)
       {
       }
      }
      throw new InvalidDataException(((HttpWebResponse)e.Response).StatusDescription);
     }
        }
 }
Esempio n. 27
0
      private void Compress(SteppedProgressManager progress,
 ProgressChangedEventHandler progressChanged)
      {
          using (FileStream archiveStream = new FileStream(ReportBaseName + ".tar",
           FileMode.Create, FileAccess.Write))
             {
          TarArchive archive = TarArchive.CreateOutputTarArchive(archiveStream);
          foreach (FileInfo file in Report.Files)
          {
           TarEntry entry = TarEntry.CreateEntryFromFile(file.FullName);
           entry.Name = Path.GetFileName(entry.Name);
           archive.WriteEntry(entry, false);
          }
          archive.Close();
             }
             ProgressManager step = new ProgressManager();
             progress.Steps.Add(new SteppedProgressManagerStep(step, 0.5f, "Compressing"));
             using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz",
          FileMode.Create))
             using (FileStream tarStream = new FileStream(ReportBaseName + ".tar",
          FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.DeleteOnClose))
             using (BZip2OutputStream bzipStream = new BZip2OutputStream(bzipFile, 262144))
             {
          int lastRead = 0;
          byte[] buffer = new byte[524288];
          while ((lastRead = tarStream.Read(buffer, 0, buffer.Length)) != 0)
          {
           bzipStream.Write(buffer, 0, lastRead);
           step.Completed = tarStream.Position;
           step.Total = tarStream.Length;
           if (progressChanged != null)
            progressChanged(this, new ProgressChangedEventArgs(progress, null));
          }
             }
      }