Пример #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;
        }
Пример #2
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);
                }
            }
        }
Пример #3
0
 public SevenZipProgressCallback(BlackBoxReportUploader uploader,
                                 SteppedProgressManager progress, ProgressManager stepProgress,
                                 ProgressChangedEventHandler progressChanged)
 {
     Uploader           = uploader;
     Progress           = progress;
     StepProgress       = stepProgress;
     EventHandler       = progressChanged;
     LastProgressReport = DateTime.MinValue;
 }
Пример #4
0
        public static IList <DownloadInfo> GetDownloads(ProgressChangedEventHandler handler)
        {
            WebRequest.DefaultCachePolicy = new HttpRequestCachePolicy(
                HttpRequestCacheLevel.Revalidate);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                new Uri("https://eraser.heidi.ie/scripts/updates?action=listupdates&version=" +
                        BuildInfo.AssemblyFileVersion));

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = response.GetResponseStream())
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        ProgressManager progress = new ProgressManager();
                        if (response.ContentLength == -1)
                        {
                            progress.MarkIndeterminate();
                        }
                        else
                        {
                            progress.Total = response.ContentLength;
                        }

                        //Download the response
                        int    lastRead = 0;
                        byte[] buffer   = new byte[16384];
                        while ((lastRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memoryStream.Write(buffer, 0, lastRead);
                            if (!progress.ProgressIndeterminate)
                            {
                                progress.Completed = memoryStream.Position;
                            }

                            if (handler != null)
                            {
                                handler(null, new ProgressChangedEventArgs(progress,
                                                                           S._("{0} of {1} downloaded", FileSize.ToString(progress.Completed),
                                                                               FileSize.ToString(progress.Total))));
                            }
                        }

                        //Parse it.
                        memoryStream.Position = 0;
                        return(ParseDownloadList(memoryStream).AsReadOnly());
                    }
        }
Пример #5
0
        /// <summary>
        /// Downloads the file to disk, storing the path into the DownloadedFile field.
        /// </summary>
        public void Download(ProgressChangedEventHandler handler)
        {
            if (DownloadedFile != null && DownloadedFile.Length > 0)
            {
                throw new InvalidOperationException("The Download method cannot be called " +
                                                    "before the Download method has been called.");
            }

            //Create a folder to hold all our updates.
            lock (TempPathLock)
            {
                if (TempPath == null)
                {
                    TempPath = new DirectoryInfo(Path.GetTempPath());
                    TempPath = TempPath.CreateSubdirectory("eraser" + Environment.TickCount.ToString(
                                                               CultureInfo.InvariantCulture));
                }
            }

            //Create the progress manager for this download.
            ProgressManager progress = new ProgressManager();

            try
            {
                Uri downloadLink = Link;
                ContentDisposition contentDisposition = null;
                for (int redirects = 0; redirects < 20; ++redirects)
                {
                    //Request the download.
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadLink);
                    request.AllowAutoRedirect = false;
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        //Check for a suggested filename. Store this until we get the final URI.
                        foreach (string header in response.Headers.AllKeys)
                        {
                            if (header.ToUpperInvariant() == "CONTENT-DISPOSITION")
                            {
                                contentDisposition = new ContentDisposition(response.Headers[header]);
                            }
                        }

                        //Handle 3xx series response codes.
                        if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
                        {
                            //Redirect.
                            bool locationHeader = false;
                            foreach (string header in response.Headers.AllKeys)
                            {
                                if (header.ToUpperInvariant() == "LOCATION")
                                {
                                    locationHeader = true;
                                    downloadLink   = new Uri(response.Headers[header]);
                                    break;
                                }
                            }

                            if (!locationHeader)
                            {
                                throw new WebException("A redirect response was received but no redirection" +
                                                       "URI was provided.");
                            }

                            continue;
                        }

                        //Do the progress calculations
                        progress.Total = response.ContentLength;

                        //Create the file name.
                        DownloadedFile = new FileInfo(Path.Combine(
                                                          TempPath.FullName, string.Format(CultureInfo.InvariantCulture,
                                                                                           "{0:00}-{1}", ++DownloadFileIndex, contentDisposition == null ?
                                                                                           Path.GetFileName(downloadLink.GetComponents(UriComponents.Path, UriFormat.Unescaped)) :
                                                                                           contentDisposition.FileName)));

                        using (Stream responseStream = response.GetResponseStream())
                            using (FileStream fileStream = DownloadedFile.OpenWrite())
                            {
                                //Copy the information into the file stream
                                int    lastRead = 0;
                                byte[] buffer   = new byte[16384];
                                while ((lastRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    fileStream.Write(buffer, 0, lastRead);

                                    //Compute progress
                                    progress.Completed = fileStream.Position;

                                    //Call the progress handler
                                    if (handler != null)
                                    {
                                        handler(this, new ProgressChangedEventArgs(progress, null));
                                    }
                                }
                            }

                        //Let the event handler know the download is complete.
                        progress.MarkComplete();
                        if (handler != null)
                        {
                            handler(this, new ProgressChangedEventArgs(progress, null));
                        }
                        return;
                    }

                    throw new WebException("The server is not redirecting properly.");
                }
            }
            catch (Exception e)
            {
                if (handler != null)
                {
                    handler(this, new ProgressChangedEventArgs(progress, e));
                }
            }
        }
Пример #6
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);
                }
        }