void getInfAboutServer() { string ping = ""; bool update = true; while (true) { this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart) delegate() { update = PlayButton.IsEnabled; }); if (update == false) { System.Threading.Thread.Sleep(60000); continue;//если игра запущена, то незачем обновлять данные } ping = new Ping().Send("185.125.231.50").RoundtripTime.ToString(); if (ping == "0")//если пинг ноль, то данные не были получены по причине отсутствия подключения к интернету (раньше после такого был прописан код на закрытие клиента, но отсутствие интеренета может быть временным) { System.Threading.Thread.Sleep(60000); continue;//если игра запущена, то незачем обновлять данные } WebClientWithTimeout client = new WebClientWithTimeout(); var stringToUri = new Uri(serverIP + "/GetServerInformation"); client.DownloadStringAsync(stringToUri); client.DownloadStringCompleted += (sender2, e2) => { var json = JsonConvert.DeserializeObject <GetServerInformation>(e2.Result); this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart) delegate() { PingInf.Content = ping + "ms"; OnlineInf.Content = string.Format("{0}/{1}", json.onlineNumber, json.maxOnlinePlayers); }); SiteLink = json.homePageUrl; VKLink = "https://vk.com/worldevolved"; DiscordLink = json.discordUrl; }; System.Threading.Thread.Sleep(60000); } }
#pragma warning disable S1541 // Methods and properties should not be too complex public string ExecuteRequest(int timeoutMilliseconds, string method, string url, string data, List <Tuple <string, string> > headers, Action <string> asyncCallback) #pragma warning restore S1541 // Methods and properties should not be too complex { using (var webClient = new WebClientWithTimeout(timeoutMilliseconds)) { webClient.Credentials = CredentialCache.DefaultCredentials; if (headers != null) { foreach (var header in headers) { webClient.Headers.Add(header.Item1, header.Item2); } } var uri = new Uri(url.Contains("http://") || url.Contains("https://") ? url : "http://" + url); switch (method) { case "GET": if (asyncCallback == null) { return(webClient.DownloadString(uri)); } webClient.DownloadStringCompleted += (sender, args) => asyncCallback?.Invoke(args.Result); webClient.DownloadStringAsync(uri, null); break; case "POST": if (asyncCallback == null) { return(webClient.UploadString(uri, data)); } webClient.UploadStringCompleted += (sender, args) => asyncCallback?.Invoke(args.Result); webClient.UploadStringAsync(uri, data); break; default: return(string.Empty); } } return(string.Empty); }
private void UpdateTimeZone() { if (TimeZoneOffsetSeconds == -1111) { TimeZoneOffsetSeconds = (int)(Longitude * 24 / 360) * 3600; #if UNITY_EDITOR if ((DateTime.UtcNow - lastTimeZoneCheck).TotalSeconds > 10.0) { lastTimeZoneCheck = DateTime.UtcNow; WebClientWithTimeout c = new WebClientWithTimeout(); c.Timeout = 3000; TimeSpan unixTimeSpan = new DateTime(Year, Month, Day, 1, 1, 1, DateTimeKind.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); string url = "http://api.timezonedb.com/v2/get-time-zone?by=position&lat=" + Latitude + "&lng=" + Longitude + "&time=" + (long)unixTimeSpan.TotalSeconds + "&key=1H9B390ZKKPX"; try { c.DownloadStringCompleted += (o, e) => { string xml = e.Result; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(xml, @"\<gmtOffset\>(?<gmtOffset>.*?)\</gmtOffset\>"); if (m.Success) { TimeZoneOffsetSeconds = int.Parse(m.Groups["gmtOffset"].Value); WeatherMakerScript.Instance.QueueOnMainThread(() => { SerializationHelper.SetDirty(this); }); } }; c.DownloadStringAsync(new System.Uri(url)); } catch { // eat exceptions } } #endif } }
public void checkAvailability() { text.Text = "Launcher Status - Checking..."; description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); status.Image = Properties.Resources.ac_unknown; text.ForeColor = Color.FromArgb(0x848484); try { WebClientWithTimeout update_data = new WebClientWithTimeout(); update_data.CancelAsync(); update_data.DownloadStringAsync(new Uri(Self.mainserver + "/update.php?version=" + Application.ProductVersion)); update_data.DownloadStringCompleted += (sender, e) => { if (description.InvokeRequired == true) { description.Invoke(new Action(delegate() { description.Visible = true; })); } else { description.Visible = true; } if (e.Cancelled) { text.Text = "Launcher Status - Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Event cancelled."; } else if (e.Error != null) { text.Text = "Launcher Status"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); } else { UpdateCheckResponse updater = JsonConvert.DeserializeObject <UpdateCheckResponse>(e.Result); try { if (updater.Code == 0) { if (updater.Payload.UpdateExists == false) { if (updater.Payload.LatestVersion.CompareTo(updater.Payload.ClientVersion) >= 0) { text.Text = "Launcher Status - Updated"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); } else { text.Text = "Launcher Status - Prerelease"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; } description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); } else { text.Text = "Launcher Status - Available"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; description.Text = "New Version : " + updater.Payload.LatestVersion; var settingFile = new IniFile("Settings.ini"); if (settingFile.Read("IgnoreUpdateVersion") != updater.Payload.LatestVersion) { var dia = new TaskDialog { Caption = "Update", InstructionText = "An update is available!", DetailsExpanded = true, Icon = TaskDialogStandardIcon.Warning, DetailsCollapsedLabel = "Show Changelog", Text = "An update is available. Do you want to download it?\nYour version: " + Application.ProductVersion + "\nUpdated version: " + updater.Payload.LatestVersion, DetailsExpandedText = new WebClientWithTimeout().DownloadString(Self.mainserver + "/launcher/changelog"), ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter }; var update = new TaskDialogCommandLink("update", "Yes", "Launcher will be updated to " + updater.Payload.LatestVersion + "."); var cancel = new TaskDialogCommandLink("cancel", "No", "Launcher will ask you to update on the next launch."); var skipupdate = new TaskDialogCommandLink("skipupdate", "Ignore", "This update will be skipped. A new prompt will apear as soon as a newer update is available."); update.UseElevationIcon = true; skipupdate.Click += (sender3, e3) => { settingFile.Write("IgnoreUpdateVersion", updater.Payload.LatestVersion); dia.Close(); }; cancel.Click += (sender3, e3) => { dia.Close(); }; update.Click += (sender3, e3) => { if (File.Exists("GameLauncherUpdater.exe")) { Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString()); } else { Process.Start(@"https://github.com/worldunitedgg/GameLauncher_NFSW/releases/latest"); } dia.Close(); }; dia.Controls.Add(update); dia.Controls.Add(cancel); dia.Controls.Add(skipupdate); dia.Show(); } } } else { text.Text = "Launcher Status - GitHub Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); } } catch (Exception) { if (text.InvokeRequired == true) //checks skip, because we only need to know if we can access ui from actual thread { text.Invoke(new Action(delegate() { text.Text = "Launcher Status - Backend Error"; text.ForeColor = Color.FromArgb(254, 0, 0); })); status.Invoke(new Action(delegate() { status.Image = Properties.Resources.ac_error; })); description.Invoke(new Action(delegate() { description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); })); } else { text.Text = "Launcher Status - Backend Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); } } } }; } catch { text.Text = "Launcher Status - Internal Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7); } }
public void checkAvailability() { text.Text = "Launcher Status - Checking..."; description.Text = "Version : v" + Application.ProductVersion; status.Image = Properties.Resources.ac_unknown; text.ForeColor = Color.FromArgb(0x848484); try { WebClientWithTimeout update_data = new WebClientWithTimeout(); update_data.CancelAsync(); update_data.DownloadStringAsync(new Uri(Self.mainserver + "/update.php?version=" + Application.ProductVersion)); update_data.DownloadStringCompleted += (sender, e) => { if (description.InvokeRequired == true) { description.Invoke(new Action(delegate() { description.Visible = true; })); } else { description.Visible = true; } if (e.Cancelled) { text.Text = "Launcher Status - Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Event cancelled."; } else if (e.Error != null) { text.Text = "Launcher Status"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); description.Text = "Version : v" + Application.ProductVersion; } else { UpdateCheckResponse updater = JsonConvert.DeserializeObject <UpdateCheckResponse>(e.Result); try { if (updater.Code == 0) { if (updater.Payload.UpdateExists == false) { if (updater.Payload.LatestVersion.CompareTo(updater.Payload.ClientVersion) >= 0) { text.Text = "Launcher Status - Updated"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); } else { text.Text = "Launcher Status - Prerelease"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; } description.Text = "Version : v" + Application.ProductVersion; } else { text.Text = "Launcher Status - Available"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; description.Text = "New Version : " + updater.Payload.LatestVersion; Application.DoEvents(); Thread.Sleep(3000); DialogResult updateConfirm = new UpdatePopup(updater).ShowDialog(); if (updateConfirm == DialogResult.OK) { progress.Text = "DOWNLOADING GAMELAUNCHERUPDATER.EXE"; new WebClientWithTimeout().DownloadFile(new Uri(Self.fileserver + "/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe"); Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString()); //Let's fetch new downloader /*Properties.Settings.Default.IsRestarting = false; * Properties.Settings.Default.Save(); * * WebClientWithTimeout updateDownload = new WebClientWithTimeout(); * updateDownload.DownloadFileAsync(new Uri(updater.Payload.Update.DownloadUrl), "update.sbrw"); * updateDownload.DownloadProgressChanged += (x, y) => { * progress.Text = "DOWNLOADING UPDATE: " + y.ProgressPercentage + "%"; * }; * * updateDownload.DownloadFileCompleted += (x, y) => { * progress.Text = "READY!"; * * if (File.Exists("Update.exe")) { * Process.Start(@"Update.exe"); * } else { * Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest"); * } * * Process.GetProcessById(Process.GetCurrentProcess().Id).Kill(); * };*/ } ; } } else { text.Text = "Launcher Status - GitHub Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } } catch (Exception ex) { MessageBox.Show(ex.Message); if (text.InvokeRequired == true) //checks skip, because we only need to know if we can access ui from actual thread { text.Invoke(new Action(delegate() { text.Text = "Launcher Status - Backend Error"; text.ForeColor = Color.FromArgb(254, 0, 0); })); status.Invoke(new Action(delegate() { status.Image = Properties.Resources.ac_error; })); description.Invoke(new Action(delegate() { description.Text = "Version : v" + Application.ProductVersion; })); } else { text.Text = "Launcher Status - Backend Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } } } }; } catch { text.Text = "Launcher Status - Internal Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } }
public void BeginUpdate() { _webClient = new WebClientWithTimeout(); _webClient.DownloadStringCompleted += _DownloadStringCompletedHandler; _webClient.DownloadStringAsync(_updateInfoUri); }
internal static void CheckForUpdate(object sender, EventArgs e) { try { var client = new WebClientWithTimeout(); var uri = new Uri(Self.mainserver + "/launcher/update?version=" + Application.ProductVersion); client.CancelAsync(); client.DownloadStringAsync(uri); client.DownloadStringCompleted += (sender2, e2) => { try { var json = JsonConvert.DeserializeObject <UpdateCheckResponse>(e2.Result); if (json.Code != 0) { MessageBox.Show("Launchpad update service returned an error: " + json.Code); return; } if (json.Payload.UpdateExists) { var settingFile = new IniFile("Settings.ini"); if (settingFile.Read("IgnoreUpdateVersion") != json.Payload.LatestVersion) { var dia = new TaskDialog { Caption = "Update", InstructionText = "An update is available!", DetailsExpanded = true, Icon = TaskDialogStandardIcon.Information, DetailsCollapsedLabel = "Show Changelog", Text = "An update is available. Do you want to download it?\nYour version: " + Application.ProductVersion + "\nUpdated version: " + json.Payload.LatestVersion, DetailsExpandedText = new WebClientWithTimeout().DownloadString(Self.mainserver + "/launcher/changelog"), ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter }; var update = new TaskDialogCommandLink("update", "Yes", "Launcher will be updated to " + json.Payload.LatestVersion + "."); var cancel = new TaskDialogCommandLink("cancel", "No", "Launcher will ask you to update on the next launch."); var skipupdate = new TaskDialogCommandLink("skipupdate", "Ignore", "This update will be skipped. A new prompt will apear as soon as a newer update is available."); update.UseElevationIcon = true; skipupdate.Click += (sender3, e3) => { settingFile.Write("IgnoreUpdateVersion", json.Payload.LatestVersion); dia.Close(); }; cancel.Click += (sender3, e3) => { dia.Close(); }; update.Click += (sender3, e3) => { if (File.Exists("GameLauncherUpdater.exe")) { Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString()); } else { Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest"); } dia.Close(); }; dia.Controls.Add(update); dia.Controls.Add(cancel); dia.Controls.Add(skipupdate); dia.Show(); //new UpdatePopup(json.github_build).Show(); } } else { try { if (((Form)sender).Name == "mainScreen") { } } catch { MessageBox.Show("Your launcher is up-to-date"); } } } catch { try { if (((Form)sender).Name == "mainScreen") { } } catch { MessageBox.Show("Failed to check for update!"); } } }; } catch { MessageBox.Show("Failed to check for update!"); } }
// TODO: factor out the guts of this and the default timout method above with a private method taking a WebClient object public string ExecuteRequest(int timeoutMilliseconds, string method, string url, string data, List<Tuple<string, string>> headers = null, Action<string> asyncCallback = null) { using (var webClient = new WebClientWithTimeout(timeoutMilliseconds)) { webClient.Credentials = CredentialCache.DefaultCredentials; if (headers != null) { foreach (var header in headers) { webClient.Headers.Add(header.Item1, header.Item2); } } var uri = new Uri(url.Contains("http://") || url.Contains("https://") ? url : "http://" + url); switch (method) { case "GET": if (asyncCallback == null) { return webClient.DownloadString(uri); } webClient.DownloadStringCompleted += (sender, args) => asyncCallback(args.Result); webClient.DownloadStringAsync(uri, null); break; case "POST": if (asyncCallback == null) { return webClient.UploadString(uri, data); } webClient.UploadStringCompleted += (sender, args) => asyncCallback(args.Result); webClient.UploadStringAsync(uri, data); break; } } return string.Empty; }