private async Task doDownload(DownloadFile file, int retry)
        {
            try
            {
                WebDownload downloader = new WebDownload();
                downloader.FileDownloadProgressChanged += Downloader_FileDownloadProgressChanged;

                await downloader.DownloadFileAsync(file).ConfigureAwait(false);

                if (file.AfterDownload != null)
                {
                    foreach (var item in file.AfterDownload)
                    {
                        await item.Invoke().ConfigureAwait(false);
                    }
                }

                Interlocked.Increment(ref progressedFiles);
                pChangeFile?.Report(
                    new DownloadFileChangedEventArgs(file.Type, true, file.Name, totalFiles, progressedFiles));
            }
            catch (Exception ex)
            {
                if (retry <= 0)
                {
                    return;
                }

                Debug.WriteLine(ex);
                retry--;

                await doDownload(file, retry).ConfigureAwait(false);
            }
        }
Exemple #2
0
        public async Task DownloadFiles(DownloadFile[] files,
                                        IProgress <DownloadFileChangedEventArgs>?fileProgress,
                                        IProgress <ProgressChangedEventArgs>?downloadProgress)
        {
            if (files.Length == 0)
            {
                return;
            }

            pChangeProgress = downloadProgress;

            WebDownload downloader = new WebDownload();

            downloader.FileDownloadProgressChanged += Downloader_FileDownloadProgressChanged;

            fileProgress?.Report(
                new DownloadFileChangedEventArgs(files[0].Type, true, null, files.Length, 0));

            for (int i = 0; i < files.Length; i++)
            {
                DownloadFile file = files[i];

                try
                {
                    var directoryPath = Path.GetDirectoryName(file.Path);
                    if (!string.IsNullOrEmpty(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    await downloader.DownloadFileAsync(file).ConfigureAwait(false);

                    if (file.AfterDownload != null)
                    {
                        foreach (var item in file.AfterDownload)
                        {
                            await item().ConfigureAwait(false);
                        }
                    }

                    fileProgress?.Report(
                        new DownloadFileChangedEventArgs(file.Type, true, file.Name, files.Length, i));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());

                    if (!IgnoreInvalidFiles)
                    {
                        throw new MDownloadFileException(ex.Message, ex, files[i]);
                    }
                }
            }
        }
 private void BtnDownload(string path, string savepath)
 {
     using (WebDownload wc = new WebDownload())
     {
         wc.DownloadProgressChanged += wc_DownloadProgressChanged;
         wc.DownloadFileCompleted   += (object sender, AsyncCompletedEventArgs e) => { if (savepath.Contains(".264"))
                                                                                       {
                                                                                           File.Move(savepath, savepath + ".h264");
                                                                                       }
         };
         wc.DownloadFileAsync(
             // Param1 = Link of file
             new System.Uri(path),
             // Param2 = Path to save
             savepath
             );
     }
 }
Exemple #4
0
 private void button1_Click(object sender, EventArgs e)
 {
     panel2.Visible = true;
     using (WebDownload wc = new WebDownload())
     {
         wc.DownloadProgressChanged += wc_DownloadProgressChanged;
         wc.DownloadFileCompleted   += (object senders, AsyncCompletedEventArgs es) =>
         {
             MessageBox.Show("Успешно загружено. Сейчас начнется установка");
             Process.Start("UpdateDownloading.exe");
             Application.Exit();
         };
         wc.DownloadFileAsync(
             // Param1 = Link of file
             new System.Uri(NetworkUpdate.URLServer + ver.URLDownload),
             // Param2 = Path to save
             "UpdateDownloading.exe"
             );
         Console.WriteLine(Downloading.GetHTML(NetworkUpdate.URLServer + NetworkUpdate.URLConfirm));
     }
 }
Exemple #5
0
        private async Task <bool> doDownload(DownloadFile file, int failedCount = 0)
        {
            try
            {
                if (failedCount > 2)
                {
                    return(false);
                }

                var downloader = new WebDownload();
                var dn         = downloader.DownloadFileAsync(file.Url, file.Path);

                var ev = Task.Run(() =>
                {
                    fireDownloadFileChangedEvent(file.Type, file.Name, total, progressed);
                });

                Interlocked.Increment(ref progressed);
                await Task.WhenAll(dn, ev);

                semaphore.Release();
                return(true);
            }
            catch (Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine(ex);
                failedCount++;

                var result = await doDownload(file, failedCount);

                if (!result)
                {
                    semaphore.Release();
                }
                return(result);
            }
        }
Exemple #6
0
        void DoWork()
        {
            //This code is fine. Fine I say.
            try
            {
                //find latest installed version
                SetStatus("Checking latest local version");
                SetDesc("");

                bool previousVersionAvailable = false;
                bool failed = false;

                var workdir = GeneralHelper.PathCombineWithCodeBasePath(null);
                var dirInfo = new DirectoryInfo(workdir);
                var existingWaDirs = dirInfo.GetDirectories();
                Version localLatestVersion = null;
                foreach (var dir in existingWaDirs)
                {
                    Match match = Regex.Match(dir.Name, @"WurmAssistant_(\d+)_(\d+)_(\d+)_(\d+)", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        var thisVersion = new Version(
                            int.Parse(match.Groups[1].Value),
                            int.Parse(match.Groups[2].Value),
                            int.Parse(match.Groups[3].Value),
                            int.Parse(match.Groups[4].Value));
                        if (localLatestVersion == null || thisVersion > localLatestVersion)
                        {
                            localLatestVersion = thisVersion;
                        }
                    }
                }

                if (localLatestVersion == null)
                {
                    SetDesc("No installed Wurm Assistant found, attempting to download latest...");
                }
                else
                {
                    previousVersionAvailable = true;
                }

                //check for new assistant version, timeout should be ~20 sec
                SetStatus("Checking for new Wurm Assistant version");

                const int maxRetries = 3;
                int retries = maxRetries;
                HttpResponseMessage response = null;

                while (retries != 0)
                {
                    var client = new HttpClient
                    {
                        BaseAddress = new Uri(BasePath),
                        Timeout = GetTimeout(maxRetries - retries + 1)
                    };
                    try
                    {
                        response = client.GetAsync(ControllerPath).Result;
                        if (!response.IsSuccessStatusCode)
                        {
                            retries--;
                            SetDesc("Failed contacting remote server: " + response.StatusCode + " => " +
                                    response.ReasonPhrase);
                            AllowRunningPrevious();
                        }
                        else
                        {
                            AllowRunningPrevious(false);
                            break;
                        }
                    }
                    catch (AggregateException agExc)
                    {
                        retries--;
                        string error = "Failed contacting remote server: " + string.Join(", ", agExc.InnerExceptions.Select(x => x.Message));
                        SetDesc(error);
                        LogException(agExc);
                        AllowRunningPrevious();
                    }

                    if (retries != 0)
                    {
                        SetDesc(string.Format("Retrying... ({0} of {1})", maxRetries - retries, maxRetries - 1), true);
                    }
                }

                if (response == null)
                {
                    SetFailure("Update failed", allowPreviousVersion: previousVersionAvailable);
                    return;
                }

                var obj = response.Content.ReadAsStringAsync().Result;
                var array = JsonConvert.DeserializeObject<string[]>(obj);

                //var array = new[] {"WurmAssistant_2_0_81_0.zip"};

                if (array.Length == 0)
                {
                    SetFailure("Update failed, no WA version on download server.", allowPreviousVersion: true);
                    return;
                }

                var remoteLatestVersion = new Version();
                string remoteFileName = null;
                foreach (var fileString in array)
                {
                    Match match = Regex.Match(fileString, @"WurmAssistant_(\d+)_(\d+)_(\d+)_(\d+)", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        var thisVersion = new Version(
                            int.Parse(match.Groups[1].Value),
                            int.Parse(match.Groups[2].Value),
                            int.Parse(match.Groups[3].Value),
                            int.Parse(match.Groups[4].Value));
                        if (thisVersion > remoteLatestVersion)
                        {
                            remoteLatestVersion = thisVersion;
                            remoteFileName = fileString;
                        }
                    }
                }

                if (localLatestVersion == null || remoteLatestVersion > localLatestVersion)
                {
                    //update
                    SetStatus("Downloading new Wurm Assistant version (" + remoteLatestVersion + ")");
                    SetProgressBarToBlocks();

                    const int maxTries = 3;
                    int currentTry = 1;
                    string downloadPath = GeneralHelper.PathCombineWithCodeBasePath(remoteFileName);

                    while (currentTry <= maxTries)
                    {
                        try
                        {
                            using (var webclient = new WebDownload((int)(GetTimeout(currentTry).TotalMilliseconds)))
                            {
                                var tcs = new TaskCompletionSource<bool>();
                                webclient.DownloadProgressChanged += (sender, args) =>
                                    SetProgressBar(args.BytesReceived, args.TotalBytesToReceive);
                                webclient.DownloadFileCompleted += (sender, args) =>
                                    tcs.SetResult(true);
                                webclient.DownloadFileAsync(
                                    new Uri(BasePath + ControllerPath + string.Format(RequestTemplate, remoteFileName)),
                                    downloadPath);
                                tcs.Task.Wait();
                                AllowRunningPrevious(false);
                            }
                            break;
                        }
                        catch (Exception ex)
                        {
                            SetDesc("Error while downloading new version: " + ex.Message);
                            currentTry++;
                            if (currentTry <= maxTries)
                            {
                                SetDesc("\r\n" + string.Format("Retrying... ({0} of {1})", currentTry - 1, maxTries - 1), true);
                                AllowRunningPrevious();
                            }
                            else
                            {
                                SetFailure("Download failed", allowPreviousVersion: previousVersionAvailable);
                                failed = true;
                                var fileinfo = new FileInfo(downloadPath);
                                if (fileinfo.Exists)
                                {
                                    try
                                    {
                                        fileinfo.Delete();
                                    }
                                    catch (Exception ex2)
                                    {
                                        SetDesc("failed to clean the partially downloaded file: " + downloadPath +
                                                "\r\n" + ex2.Message);
                                        LogException(ex2);
                                    }
                                }
                                break;
                            }
                        }
                    }
                    //extract
                    if (!failed)
                    {
                        SetStatus("Extracting new Wurm Assistant version");
                        try
                        {

                            var tempExtractDir = new DirectoryInfo(GeneralHelper.PathCombineWithCodeBasePath("temp"));

                            //clean up any past failed updates
                            if (tempExtractDir.Exists)
                            {
                                Thread.Sleep(100);
                                tempExtractDir.Delete(true);
                            }
                            Thread.Sleep(200);
                            tempExtractDir.Create();
                            Thread.Sleep(200);
                            using (var extractor = new SevenZipExtractor(downloadPath))
                            {
                                extractor.ExtractArchive(tempExtractDir.FullName);
                            }


                            var waDirName = Path.GetFileNameWithoutExtension(downloadPath);
                            var newAssistantDir = new DirectoryInfo(Path.Combine(tempExtractDir.FullName, waDirName));
                            var destinationPath = GeneralHelper.PathCombineWithCodeBasePath(waDirName);
                            const int maxMoveTries = 100;
                            int currentMoveTry = 0;
                            Thread.Sleep(500);
                            while (true)
                            {
                                currentMoveTry++;
                                try
                                {
                                    newAssistantDir.MoveTo(destinationPath);
                                    AllowRunningPrevious(false);
                                    break;
                                }
                                catch (IOException)
                                {
                                    if (currentMoveTry > maxMoveTries)
                                    {
                                        throw;
                                    }
                                    else if (currentMoveTry == 20)
                                    {
                                        AllowRunningPrevious();
                                    }
                                    else
                                    {
                                        SetDesc("IOException while moving new WA dir, retrying... (" + currentMoveTry + ")");
                                    }
                                }
                                Thread.Sleep(200);
                            }

                            //cleanup
                            var downloadedZip = new FileInfo(downloadPath);
                            if (downloadedZip.Exists)
                            {
                                try
                                {
                                    downloadedZip.Delete();
                                }
                                catch (Exception ex2)
                                {
                                    SetDesc("failed to clean the partially downloaded file: " + downloadPath +
                                            "\r\n" + ex2.Message, true);
                                }
                            }
                            try
                            {
                                tempExtractDir.Delete(true);
                            }
                            catch (Exception ex3)
                            {
                                SetDesc("failed to clean temp dir: " + tempExtractDir.FullName +
                                        "\r\n" + ex3.Message, true);
                                LogException(ex3);
                            }

                            //clean old versions
                            foreach (var dir in existingWaDirs)
                            {
                                try
                                {
                                    dir.Delete(true);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogDiag("error while deleting old WA dir", this, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            SetFailure("Extracting failed", "Error while trying to extract archive: " + ex.Message +
                                "\r\n\r\nTry to run launcher again " +
                                (previousVersionAvailable ? " or start previous version" : ""), previousVersionAvailable);
                            failed = true;
                            LogException(ex);
                        }
                    }
                }

                if (!failed) RunLatestVersion();
            }
            catch (AggregateException agExc)
            {
                string error = "Unexpected errors while running launcher: " + string.Join(",", agExc.InnerExceptions.Select(x => x.Message));
                SetFailure("Launching failed", error);
                LogException(agExc);
            }
            catch (Exception exception)
            {
                SetFailure("Launching failed", "Unexpected error while running launcher: " + exception.Message);
                LogException(exception);
            }
        }