Пример #1
0
        private void RenderField()
        {
            var update = new DisplayUpdate
            {
                FieldSize    = new System.Windows.Size(SimOpt.SimOpts.FieldWidth, SimOpt.SimOpts.FieldHeight),
                RobotUpdates = _robotsManager.Robots.Select(r => new RobotUpdate
                {
                    Position = r.Position,
                    Radius   = r.GetRadius(SimOpt.SimOpts.FixedBotRadii),
                    Color    = r.Color
                }).ToList().AsReadOnly(),
                TieUpdates = _robotsManager.Robots.SelectMany(r => r.Ties.Where(t => !t.BackTie).Select(t => new TieUpdate
                {
                    Color      = t.Color ?? r.Color,
                    StartPoint = r.OffsetPosition,
                    EndPoint   = t.OtherBot.OffsetPosition,
                    Width      = Math.Max(10, t.Last > 0 ? r.GetRadius(SimOpt.SimOpts.FixedBotRadii) / 20 : r.GetRadius(SimOpt.SimOpts.FixedBotRadii) / 40),
                })).ToList().AsReadOnly(),
                ShotUpdates = _shotsManager.Shots.Select(r => new ShotUpdate
                {
                    Position = r.Position,
                    Color    = r.Color
                }).ToList().AsReadOnly()
            };

            UpdateAvailable?.Invoke(this, new UpdateAvailableArgs {
                Update = update
            });
        }
Пример #2
0
        internal Tuple <Version, string, string> GetUpdates()
        {
            Tuple <Version, string, string> res = null;

            SetWebSettings();

            using (var webClient = new WebClient())
            {
                var data = webClient.DownloadData(m_ServerUrl);

                res = GetUpdateInfoIfAvailable(data);

                if (res != null)
                {
                    UpdateAvailable?.Invoke(res.Item1, res.Item2, res.Item3);

                    return(res);
                }
                else
                {
                    UpdatesCheckCompleted?.Invoke();
                }
            }

            return(res);
        }
Пример #3
0
        public void CheckForUpdatesNew(bool forceShowForm)
        {
            try
            {
                long verCurrent;
                long verNew;

                // get the latest version as according to the release

                // get the user's version
                Assembly a = Assembly.GetEntryAssembly();
                if (a == null)
                {
                    logger.Error("Could not get current version");
                    return;
                }

                AssemblyName an = a.GetName();

                //verNew = verInfo.versions.ServerVersionAbs;

                verNew     = AutoUpdatesHelper.ConvertToAbsoluteVersion(AutoUpdatesHelper.GetLatestVersionNumber(ServerSettings.Instance.UpdateChannel));
                verCurrent = an.Version.Revision * 100 + an.Version.Build * 100 * 100 + an.Version.Minor * 100 * 100 * 100 + an.Version.Major * 100 * 100 * 100 * 100;

                if (forceShowForm || verNew > verCurrent)
                {
                    UpdateAvailable?.Invoke(this, new UpdateEventArgs(verNew, verCurrent, forceShowForm));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
            }
        }
Пример #4
0
        /// <summary>
        /// Checks if an update is available
        /// </summary>
        /// <returns>The latest or current version</returns>
        public async Task <Version> CheckForUpdatesAsync()
        {
            State = UpdaterState.CheckingForUpdates;

            int updateFiles = Directory.GetFiles(downloadPath).Length;

            if (File.Exists(versionFilePath) && updateFiles > 0)
            {
                string versionTxt = await File.ReadAllTextAsync(versionFilePath);

                latestVersion = Version.ConvertToVersion(versionTxt);

                if (latestVersion > currentVersion)
                {
                    if (File.Exists(changelogFilePath))
                    {
                        UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, true, File.ReadAllText(changelogFilePath)));
                    }
                    else
                    {
                        UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, true));
                    }

                    State = UpdaterState.Idle;
                    return(latestVersion);
                }
            }
            else
            {
                try
                {
                    var releases = await gitHubClient.Repository.Release.GetAll(GitHubUsername, GitHubRepositoryName);

                    Release release = releases.FirstOrDefault(x => Version.ConvertToVersion(x.TagName.Replace("v", "")) > currentVersion);

                    if (release is null)
                    {
                        return(currentVersion);
                    }

                    latestRelease = release;
                    latestVersion = Version.ConvertToVersion(latestRelease.TagName.Replace("v", ""));
                    changelog     = latestRelease.Body;
                    UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, false, latestRelease.Body));
                    State = UpdaterState.Idle;
                    return(latestVersion);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            State = UpdaterState.Idle;
            return(currentVersion);
        }
Пример #5
0
        public void CheckVersion()
        {
            WebClient wc = new WebClient();

            wc.Proxy                    = null;
            wc.OpenReadCompleted       += (sender, args) => Connected(this, Empty);
            wc.DownloadProgressChanged += (sender, args) => DownloadProgressChanged(this, args);
            wc.DownloadStringCompleted += (sender, args) => {
                if (args.Cancelled || args.Error != null)
                {
                    UpdateCheckFailed?.Invoke(this, Empty);
                }
                else
                {
                    try {
                        XmlDocument xd = new XmlDocument();
                        xd.LoadXml(args.Result);
                        var    versionNode  = xd["version"];
                        var    version      = Version.Parse(versionNode["version_string"].InnerText);
                        var    releaseDate  = DateTime.ParseExact(versionNode["release_date"].InnerText.Trim(), "yyyy'-'M'-'d", null);
                        string releaseNotes = versionNode["release_notes"].InnerText;
                        string url          = versionNode["url"].InnerText;

                        var myVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
                        if (version > Version.Parse(myVersion.FileVersion))
                        {
                            UpdateAvailable?.Invoke(this, new UpdateAvailableArgs {
                                DownloadUrl  = url,
                                ReleaseDate  = releaseDate,
                                ReleaseNotes = releaseNotes,
                                Version      = version,
                            });
                        }
                        else
                        {
                            AlreadyLatest?.Invoke(this, Empty);
                        }
                    }
                    catch {
                        UpdateCheckFailed?.Invoke(this, Empty);
                    }
                }
            };
            // trigger the download..
            wc.DownloadStringAsync(new Uri(UpdateCheckHost + UpdateCheckPage));
        }
Пример #6
0
        public bool CheckForUpdates()
        {
            HttpWebRequest req = WebRequest.CreateHttp(_updateUrl);

            req.UserAgent   = "TR2RandoTracker";
            req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            using (WebResponse response = req.GetResponse())
                using (Stream receiveStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(receiveStream))
                    {
                        Dictionary <string, object> releaseInfo = JsonConvert.DeserializeObject <Dictionary <string, object> >(reader.ReadToEnd());
                        string currentVersion = ((App)Application.Current).TaggedVersion;
                        if (!releaseInfo.ContainsKey("tag_name"))
                        {
                            throw new IOException("Invalid response from GitHub - missing tag_name field.");
                        }

                        string latestVersion = releaseInfo["tag_name"].ToString();
                        if (latestVersion.Equals(currentVersion))
                        {
                            return(false);
                        }

                        LatestUpdate = new Update
                        {
                            CurrentVersion = currentVersion,
                            NewVersion     = latestVersion,
                            ReleaseDate    = DateTime.Parse(releaseInfo["published_at"].ToString()),
                            UpdateBody     = releaseInfo["body"].ToString(),
                            UpdateURL      = releaseInfo["html_url"].ToString()
                        };

                        UpdateAvailable?.Invoke(this, new UpdateEventArgs(LatestUpdate));

                        return(true);
                    }
        }
Пример #7
0
        public void CheckForUpdates()
        {
            var serializer = new XmlSerializer(typeof(ReleaseManifest));

            while (DoCheck)
            {
                try
                {
                    var request  = WebRequest.Create(UpdateUri);
                    var response = request.GetResponse();
                    if (response.ContentLength > 0)
                    {
                        using (TextReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            Manifest = (ReleaseManifest)serializer.Deserialize(reader);

                            var manifestVersion = new Version(Manifest.Version);
                            var runningVersion  = Assembly.GetEntryAssembly().GetName().Version;

                            if (manifestVersion.CompareTo(runningVersion) > 0)
                            {
                                Logger.Info("Manifest version {0} is greater than current application version {1}", manifestVersion, runningVersion);
                                DoCheck = false; // stop thread once UpdateAvailable notification is complete
                                UpdateAvailable?.Invoke(this);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorException($"unable to fetch path {UpdateUri}", ex);
                }
                if (DoCheck)
                {
                    Thread.Sleep(CheckInterval);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Gets the the repository, then checks if there is a new version available.
        /// </summary>
        /// <returns>True if there is a new version</returns>
        ///  <exception cref="NullReferenceException">Thrown when the Repository is null</exception>
        ///  <exception cref="FormatException">Thrown when the version was in a invalid format</exception>
        public bool CheckForUpdate()
        {
            GetRepository();

            if (repository == null)
            {
                throw new NullReferenceException("Could not retrieve Repository");
            }

            State = UpdaterState.CheckingForUpdate;

            Version currentVersion = Version.ConvertToVersion(Assembly.GetEntryAssembly().GetName().Version.ToString());
            Version newestVersion  = Version.ConvertToVersion(repository.TagName);

            if (currentVersion < newestVersion)
            {
                UpdateAvailable?.Invoke(this, new VersionEventArgs(newestVersion, currentVersion));
                State = UpdaterState.Idle;
                return(true);
            }

            State = UpdaterState.Idle;
            return(false);
        }
Пример #9
0
 private void OnUpdateAvailable(object sender, UpdateAvailableArgs e)
 {
     UpdateAvailable?.Invoke(sender, e);
 }
Пример #10
0
 protected virtual void OnUpdateAvailable(EventArgs e) => UpdateAvailable?.Invoke(this, e);
Пример #11
0
 protected virtual void OnUpdateAvailable(UpdateAvailableArgs e)
 {
     UpdateAvailable?.Invoke(this, e);
 }
Пример #12
0
    // Private Functions
    // --------------------------------------------------------------------------

    // Checks if a new update is available based on the data from GitHub Release RSS
    void CheckNewUpdate()
    {
        // Only run new update check if new content is available
        if (!new_content)
        {
            return;
        }
        else
        {
            new_content = false; // Reset variable
        }
        // Find all version number tags
        MatchCollection versionMatches = Regex.Matches(rss_content, @"(?<=tag\/)v?(.+?)(?=""/)");

        // Semantic version number
        var gitHubVersion = new Version("0.0.0");

        // Find the newest version tag
        foreach (Match match in versionMatches)
        {
            // Extract individual semantic versioning numbers
            MatchCollection semnums = Regex.Matches(match.Value, @"\d+");

            // Version to compare to the latest version
            string semver  = semnums[0].Value + '.' + semnums[1].Value + '.' + semnums[2].Value;
            var    version = new Version(semver);

            // Compare to find the latest version on github
            var _result = gitHubVersion.CompareTo(version);

            if (_result < 0)
            {
                gitHubVersion = version;
            }
        }

        // Compare the version from GitHub to the installed version
        var result = gitHubVersion.CompareTo(current_version);

        // Ask to update if newer release exists
        if (result > 0)
        {
            debug.LogInfo("There is a new release on GitHub!");

            // Trigger 'Update available' event to event handler
            UpdateAvailable?.Invoke(gitHubVersion);

            // Set global variable to true for update available
            update_available = true;
        }

        else if (result < 0)
        {
            // Hopefully shouldn't reach this point (it doesn't make sense)
            debug.LogInfo("For some reason, your release is newer than the latest on GitHub.");

            update_available = false;
        }

        else
        {
            debug.LogInfo("You have the newest release installed!");

            update_available = false;
        }
    }
Пример #13
0
        private void InitializePatcher()
        {
            if (m_patcher != null)
            {
                return;
            }

            m_patcher = SPTUtils.CreatePatcher(RootPath, VersionInfoURL).CheckForMultipleRunningInstances(CheckForMultipleRunningInstances).
                        UseRepairPatch(UseRepairPatch).UseIncrementalPatch(UseIncrementalPatch).UseInstallerPatch(UseInstallerPatch).
                        VerifyFilesOnServer(VerifyFilesOnServer).SilentMode(SilentMode).LogProgress(LogProgress).LogToFile(LogToFile);

            if (!string.IsNullOrEmpty(VersionInfoRSA))
            {
                m_patcher.UseVersionInfoVerifier(( ref string xml ) => XMLSigner.VerifyXMLContents(xml, VersionInfoRSA));
            }

            if (!string.IsNullOrEmpty(PatchInfoRSA))
            {
                m_patcher.UsePatchInfoVerifier(( ref string xml ) => XMLSigner.VerifyXMLContents(xml, PatchInfoRSA));
            }

            PatcherListener listener = new PatcherListener();

            listener.OnStart += () =>
            {
                if (m_patcher.Operation == PatchOperation.CheckingForUpdates)
                {
                    CheckForUpdatesStarted.Invoke();
                }
                else if (m_patcher.Operation == PatchOperation.Patching || m_patcher.Operation == PatchOperation.SelfPatching)
                {
                    PatchStarted.Invoke();
                }
            };
            listener.OnLogReceived += (log) =>
            {
                LogReceived.Invoke(log);

                if (LogToConsole)
                {
                    Debug.Log(log);
                }
            };
            listener.OnProgressChanged += (progress) =>
            {
                CurrentProgressPercentageChanged.Invoke(progress.Percentage);
                CurrentProgressTextChanged.Invoke(progress.ProgressInfo);
            };
            listener.OnOverallProgressChanged += (progress) =>
            {
                OverallProgressPercentageChanged.Invoke(progress.Percentage);
                OverallProgressTextChanged.Invoke(progress.ProgressInfo);
            };
            listener.OnPatchStageChanged  += PatchStageChanged.Invoke;
            listener.OnPatchMethodChanged += PatchMethodChanged.Invoke;
            listener.OnVersionInfoFetched += (versionInfo) =>
            {
                for (int i = 0; i < AdditionalIgnoredPaths.Length; i++)
                {
                    if (!string.IsNullOrEmpty(AdditionalIgnoredPaths[i]))
                    {
                        versionInfo.AddIgnoredPath(AdditionalIgnoredPaths[i]);
                    }
                }

                VersionInfoFetched.Invoke(versionInfo);
            };
            listener.OnVersionFetched += (currentVersion, newVersion) =>
            {
                CurrentVersionDetermined.Invoke(currentVersion);
                NewVersionDetermined.Invoke(newVersion);
            };
            listener.OnFinish += () =>
            {
                if (m_patcher.Operation == PatchOperation.CheckingForUpdates)
                {
                    if (m_patcher.Result == PatchResult.AlreadyUpToDate)
                    {
                        AppIsUpToDate.Invoke();
                    }
                    else if (m_patcher.Result == PatchResult.Success)
                    {
                        UpdateAvailable.Invoke();
                    }
                    else
                    {
                        CheckForUpdatesFailed.Invoke(m_patcher.FailDetails);

                        if (LogToConsole)
                        {
                            Debug.LogError(m_patcher.FailDetails);
                        }
                    }
                }
                else if (m_patcher.Operation == PatchOperation.Patching || m_patcher.Operation == PatchOperation.SelfPatching)
                {
                    if (m_patcher.Result == PatchResult.AlreadyUpToDate)
                    {
                        AppIsUpToDate.Invoke();
                    }
                    else if (m_patcher.Result == PatchResult.Success)
                    {
                        PatchSuccessful.Invoke();

                        if (m_patcher.Operation == PatchOperation.Patching)
                        {
                            CurrentVersionDetermined.Invoke(m_patcher.NewVersion);
                        }
                    }
                    else
                    {
                        PatchFailed.Invoke(m_patcher.FailDetails);

                        if (LogToConsole)
                        {
                            Debug.LogError(m_patcher.FailDetails);
                        }
                    }
                }
                else
                {
                    if (m_patcher.Result == PatchResult.AlreadyUpToDate)
                    {
                        AppIsUpToDate.Invoke();
                    }
                    else if (m_patcher.Result == PatchResult.Failed)
                    {
                        SelfPatchingFailed.Invoke(m_patcher.FailDetails);

                        if (LogToConsole)
                        {
                            Debug.LogError(m_patcher.FailDetails);
                        }
                    }
                }
            };

            m_patcher.SetListener(listener);
        }
Пример #14
0
 /// <summary>
 /// Dispatches the <see cref="UpdateAvailable"/> event to notify listeners that an update is available.
 /// </summary>
 /// <param name="version">A <see cref="ProgramVersion"/> representing the new version.</param>
 private void NotifyUpdate(ProgramVersion version)
 {
     UpdateAvailable?.Invoke(this, new UpdateAvailableEventArgs(version));
 }
Пример #15
0
        private void CheckForUpdateAsync(object state)
        {
            try
            {
                if (!_manualCheck & (_updateCheckedAt.AddMilliseconds(_updateCheckInterval) > DateTime.UtcNow))
                {
                    return;
                }

                using (WebClientEx wC = new WebClientEx())
                {
                    wC.Proxy   = _proxy;
                    wC.Timeout = 30000;

                    byte[] response = wC.DownloadData(_updateCheckUri);

                    using (BinaryReader bR = new BinaryReader(new MemoryStream(response, false)))
                    {
                        if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "MU") //format
                        {
                            throw new InvalidDataException("Mesh update info format is invalid.");
                        }

                        switch (bR.ReadByte()) //version
                        {
                        case 1:
                            _updateVersion = bR.ReadShortString();
                            _displayText   = bR.ReadShortString();
                            _downloadLink  = bR.ReadShortString();
                            break;

                        default:
                            throw new InvalidDataException("Mesh update info version not supported.");
                        }

                        if (IsUpdateAvailable(_currentVersion, _updateVersion))
                        {
                            _syncCxt.Send(delegate(object state2)
                            {
                                UpdateAvailable?.Invoke(this, EventArgs.Empty);
                            }, null);
                        }
                        else if (_manualCheck)
                        {
                            _syncCxt.Send(delegate(object state2)
                            {
                                NoUpdateAvailable?.Invoke(this, EventArgs.Empty);
                            }, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (_manualCheck)
                {
                    _syncCxt.Send(delegate(object state2)
                    {
                        UpdateCheckFailed?.Invoke(this, ex);
                    }, null);
                }
            }
            finally
            {
                _manualCheck     = false;
                _updateCheckedAt = DateTime.UtcNow;
            }
        }
 protected virtual void OnRaiseUpdateAvailable(UpdateAvailableEventArgs e)
 {
     UpdateAvailable?.Invoke(this, e);
 }