Exemple #1
0
        internal UpsparkleUpdater()
        {
            var dllpath = string.Empty;

            var resourceName = string.Empty;
            var assembly     = Assembly.GetExecutingAssembly();

            if (IntPtr.Size == 4)
            {
                // 32-bit
                resourceName = $"{typeof(IUpsparkleUpdater).Namespace}.x86.{libraryName}";
                dllpath      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "x86");
            }
            else
            {
                // 64-bit
                resourceName = $"{typeof(IUpsparkleUpdater).Namespace}.x64.{libraryName}";
                dllpath      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "x64");
            }

            Utilites.LoadUnmanagedLibrary(Path.Combine(dllpath, libraryName));

            //Utilites.LoadUnmanagedLibraryFromResource(assembly, resourceName, libraryName);

            SetErrorCallback(() => Error?.Invoke(this, new EventArgs()));
            SetCanShutdownCallback(() => CanShutdown?.Invoke(this, new EventArgs()));
            SetShutdownRequestCallback(() => ShutdownRequest?.Invoke(this, new EventArgs()));
            SetDidFindUpdateCallback(() => DidFindUpdate?.Invoke(this, new EventArgs()));
            SetDidNotFindUpdateCallback(() => DidNotFindUpdate?.Invoke(this, new EventArgs()));
            SetUpdateCancelledCallback(() => UpdateCancelled?.Invoke(this, new EventArgs()));
        }
        private void BtnCancel_LeftClick(object sender, EventArgs e)
        {
            CUpdater.TerminateUpdate = true;

            if (IsTaskbarSupported())
            {
                tbp.SetState(WindowManager.GetWindowHandle(), TaskbarProgress.TaskbarStates.NoProgress);
            }

            UpdateCancelled?.Invoke(this, EventArgs.Empty);
        }
        private void CloseWindow()
        {
            isStartingForceUpdate = false;

            if (IsTaskbarSupported())
            {
                tbp.SetState(WindowManager.GetWindowHandle(), TaskbarProgress.TaskbarStates.NoProgress);
            }

            UpdateCancelled?.Invoke(this, EventArgs.Empty);
        }
        public void InitUpdateData()
        {
            this.calcelationTokenSource = new CancellationTokenSource();
            // Do nothing if updating currently
            if (IsCurrentlyUpdating)
            {
                return;
            }

            // Set state
            IsCurrentlyUpdating  = true;
            IsCurrentlyCanceling = false;

            //Create background task
            Task <LeagueInfo> t = new Task <LeagueInfo>((stateObj) =>
            {
                var castedToken      = (CancellationToken)stateObj;
                const int maxPerPage = 200;
                LeagueInfo lf        = new LeagueInfo();
                //Get header data
                HttpResponseMessage response = client.GetAsync(getFormatterUrl(0, maxPerPage)).Result;
                if (response.IsSuccessStatusCode)
                {
                    string jsonRawData = response.Content.ReadAsStringAsync().Result;
                    lf = JsonConvert.DeserializeObject <LeagueInfo>(jsonRawData);
                }
                else
                {
                    //Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    throw new Exception();
                }
                // Get remaining data
                for (int i = 200; i < lf.ladder.total; i += 200)
                {
                    if (castedToken.IsCancellationRequested)
                    {
                        response.Dispose();
                        castedToken.ThrowIfCancellationRequested();
                    }
                    //Sleep if explicitly requested.
                    Thread.Sleep(PagingDelay);

                    /*//Add implicit delay every 5 pages to prevent some errors that sometimes occure due to too many requests.
                     * if (i > 0 && (Math.IEEERemainder(i/200, 5) == 0))
                     * {
                     *  Console.WriteLine("Implicit Delay.");
                     *  Thread.Sleep(3000);
                     * }*/

                    //Report progress trough event
                    UpdateProgressReport?.Invoke(i * 100 / lf.ladder.total);

                    // Get page data
                    response = client.GetAsync(getFormatterUrl(i, maxPerPage)).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string respon     = response.Content.ReadAsStringAsync().Result;
                        LeagueInfo lfTemp = JsonConvert.DeserializeObject <LeagueInfo>(respon);
                        //append Entires (characters) to lf variable which holds all data.
                        lf.ladder.entries.AddRange(lfTemp.ladder.entries);
                    }
                    else
                    {
                        //Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                        throw new Exception();
                    }
                }
                return(lf);
            }, calcelationTokenSource.Token, calcelationTokenSource.Token);

            //Start task in the background
            t.Start();

            // Execute after completion of the task
            t.ContinueWith((task) => {
                IsCurrentlyUpdating  = false;
                IsCurrentlyCanceling = false;
                if (task.IsCanceled)
                {
                    UpdateCancelled?.Invoke();
                }
                else if (!task.IsFaulted)
                {
                    Lf = task.Result;
                    CompletedSuccessfully?.Invoke();
                }
                else
                {
                    CompletionFailed?.Invoke();
                }
            });
        }
        private void PerformUpdateInternal()
        {
            UpdaterLogger.Log("Performing update.");

            CreateTemporaryDirectory();

            UpdateMirror updateMirror = updateMirrors[lastUpdateMirrorId];

            char dsc = Path.DirectorySeparatorChar;

            string buildPath         = localBuildInfo.BuildPath;
            string downloadDirectory = buildPath + TEMPORARY_UPDATER_DIRECTORY + dsc;

            List <RemoteFileInfo> filesToDownload = GatherFilesToDownload(buildPath, downloadDirectory);

            CleanUpDownloadDirectory(filesToDownload, downloadDirectory);

            UpdaterLogger.Log("Creating downloader.");

            UpdateDownloader downloader = new UpdateDownloader();

            downloader.DownloadProgress += Downloader_DownloadProgress;
            UpdateDownloadResult result = downloader.DownloadUpdates(buildPath, downloadDirectory, filesToDownload, updateMirror);

            downloader.DownloadProgress -= Downloader_DownloadProgress;

            lock (locker)
            {
                updateInProgress = false;
            }

            switch (result.UpdateDownloadResultState)
            {
            case UpdateDownloadResultType.CANCELLED:
                UpdateCancelled?.Invoke(this, EventArgs.Empty);
                return;

            case UpdateDownloadResultType.COMPLETED:
                // If a new second-stage updater was downloaded, update it
                // first before launching it

                string originalSecondStageUpdaterPath = localBuildInfo.BuildPath + SecondStageUpdaterPath;

                string updatedSecondStageUpdaterPath = localBuildInfo.BuildPath +
                                                       TEMPORARY_UPDATER_DIRECTORY + dsc +
                                                       SecondStageUpdaterPath;

                if (File.Exists(updatedSecondStageUpdaterPath))
                {
                    File.Delete(originalSecondStageUpdaterPath);
                    File.Move(updatedSecondStageUpdaterPath, originalSecondStageUpdaterPath);
                }

                // Also update the second-stage updater's config file

                string originalSecondStageConfigPath = Path.GetDirectoryName(originalSecondStageUpdaterPath)
                                                       + dsc + SECOND_STAGE_UPDATER_CONFIGURATION_FILE;

                string updatedSecondStageConfigPath = Path.GetDirectoryName(updatedSecondStageUpdaterPath)
                                                      + dsc + SECOND_STAGE_UPDATER_CONFIGURATION_FILE;

                if (File.Exists(updatedSecondStageConfigPath))
                {
                    File.Delete(originalSecondStageConfigPath);
                    File.Move(updatedSecondStageConfigPath, originalSecondStageConfigPath);
                }

                // Generate local build information file
                LocalBuildInfo newBuildInfo = LocalBuildInfoFromRemoteBuildInfo();
                newBuildInfo.Write(localBuildInfo.BuildPath + TEMPORARY_UPDATER_DIRECTORY + dsc + LOCAL_BUILD_INFO_FILE);

                Process.Start(originalSecondStageUpdaterPath);

                // No null checking necessary here, it's actually better to
                // crash the application in case this is not subscribed to
                DownloadCompleted.Invoke(this, EventArgs.Empty);
                return;

            case UpdateDownloadResultType.FAILED:
                UpdateFailed?.Invoke(this, new UpdateFailureEventArgs(result.ErrorDescription));
                return;
            }
        }
 /// <summary>
 /// 引发 <see cref="UpdateCancelled" /> 事件
 /// </summary>
 internal virtual void OnUpdateCancelled()
 {
     CleanTemp();
     UpdateCancelled?.Invoke(this, EventArgs.Empty);
 }