public void GetResourceID_ShouldReturnEmptyGuid() { //------------Setup for test-------------------------- var serverInformation = new GetServerInformation(); //------------Execute Test--------------------------- var resId = serverInformation.GetResourceID(new Dictionary <string, StringBuilder>()); //------------Assert Results------------------------- Assert.AreEqual(Guid.Empty, resId); }
public void GetAuthorizationContextForService_ShouldReturnContext() { //------------Setup for test-------------------------- var serverInformation = new GetServerInformation(); //------------Execute Test--------------------------- var resId = serverInformation.GetAuthorizationContextForService(); //------------Assert Results------------------------- Assert.AreEqual(AuthorizationContext.Any, resId); }
public void GetServerInformation_Execute_NullValuesParameter_ErrorResult() { //------------Setup for test-------------------------- var getInformation = new GetServerInformation(); var serializer = new Dev2JsonSerializer(); //------------Execute Test--------------------------- var jsonResult = getInformation.Execute(null, null); var result = serializer.Deserialize <Dictionary <string, string> >(jsonResult); //------------Assert Results------------------------- Assert.IsNotNull(result); }
public void GetServerInformation_HandlesType_ExpectName() { //------------Setup for test-------------------------- var getInformation = new GetServerInformation(); //------------Execute Test--------------------------- //------------Assert Results------------------------- Assert.AreEqual("GetServerInformation", getInformation.HandlesType()); }
public SelectServer() { IsSelectServerOpen = true; InitializeComponent(); SetVisuals(); this.Closing += (x, y) => { ID = 1; ServerListBook.Clear(); ServersToPing.Clear(); ServerName = null; ServerJsonData = null; CustomServersOnly = false; GC.Collect(); }; }
private void OkButton_Click(object sender, EventArgs e) { if (!File.Exists("servers.json")) { File.Create("servers.json"); } bool success = true; Error.Visible = false; this.Refresh(); String wellFormattedURL = ""; if (IsNullOrEmpty(ServerAddress.Text)) { DrawErrorAroundTextBox(ServerAddress); success = false; } if (IsNullOrEmpty(ServerName.Text)) { DrawErrorAroundTextBox(ServerName); success = false; } bool result = Uri.TryCreate(ServerAddress.Text, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); if (!result) { DrawErrorAroundTextBox(ServerAddress); success = false; } else { wellFormattedURL = uriResult.ToString(); } CancelBTN.Enabled = false; OkBTN.Enabled = false; ServerAddress.Enabled = false; ServerName.Enabled = false; try { var client = new WebClient(); Uri StringToUri = new Uri(wellFormattedURL + "/GetServerInformation"); var serverLoginResponse = client.DownloadString(StringToUri); GetServerInformation json = JsonConvert.DeserializeObject <GetServerInformation>(serverLoginResponse); if (IsNullOrEmpty(json.ServerName)) { DrawErrorAroundTextBox(ServerAddress); success = false; } } catch { DrawErrorAroundTextBox(ServerAddress); success = false; } CancelBTN.Enabled = true; OkBTN.Enabled = true; ServerAddress.Enabled = true; ServerName.Enabled = true; if (success == true) { try { StreamReader sr = new StreamReader("servers.json"); String oldcontent = sr.ReadToEnd(); sr.Close(); if (IsNullOrWhiteSpace(oldcontent)) { oldcontent = "[]"; } var servers = JsonConvert.DeserializeObject <List <ServerInfo> >(oldcontent); servers.Add(new ServerInfo { Name = ServerName.Text, IpAddress = wellFormattedURL, IsSpecial = false, Id = SHA.HashPassword(uriResult.Host) }); File.WriteAllText("servers.json", JsonConvert.SerializeObject(servers)); MessageBox.Show(null, "New server will be added on next start of launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(null, "Failed to add new server. " + ex.Message, "GameLauncher", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } CancelButton_Click(sender, e); } else { Error.Visible = true; } }
public SelectServer() { InitializeComponent(); SetVisuals(); Version.Text = "Version: v" + Application.ProductVersion; //And one for keeping data about server, IP tbh ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 210; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 100; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Online"); ServerListRenderer.Columns[3].Width = 75; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Registered"); ServerListRenderer.Columns[4].Width = 85; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 60; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Center; foreach (var substring in ServerListUpdater.NoCategoryList) { try { servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); data.Add(ID, substring); ID++; } catch { } } Thread newList = new Thread(() => { Thread.Sleep(200); this.BeginInvoke((MethodInvoker) delegate { while (servers.Count != 0) { string QueueContent = servers.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; string servername = QueueContent2[2]; try { WebClient getdata = new WebClient(); GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl)); if (content == null) { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; } else { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(content.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = content.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = content.numberOfRegistered.ToString(); //PING if (!DetectLinux.LinuxDetected()) { Ping pingSender = new Ping(); Uri StringToUri = new Uri(serverurl); pingSender.SendAsync(StringToUri.Host, 1000, new byte[1], new PingOptions(64, true), new AutoResetEvent(false)); pingSender.PingCompleted += (sender3, e3) => { PingReply reply = e3.Reply; if (reply.Status == IPStatus.Success && servername != "Offline Built-In Server") { ServerListRenderer.Items[serverid].SubItems[5].Text = reply.RoundtripTime + "ms"; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } }; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A"; } } } catch { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } if (servers.Count == 0) { Loading.Text = ""; } Application.DoEvents(); } }); }) { IsBackground = true }; newList.Start(); ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { SelectedGameServerToRemember(); }); }
public SelectServer(String windowName = "") { InitializeComponent(); if (windowName != "") { this.Text = windowName; } //And one for keeping data about server, IP tbh Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>(); ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[0].Width = 285; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[1].Width = 80; ServerListRenderer.Columns.Add("Players Online"); ServerListRenderer.Columns[2].Width = 80; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Registered Players"); ServerListRenderer.Columns[3].Width = 100; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right; //Actually accept JSON instead of old format// List <ServerInfo> serverInfos = new List <ServerInfo>(); foreach (var serverListURL in Self.serverlisturl) { try { var wc = new WebClientWithTimeout(); var response = wc.DownloadString(serverListURL); try { serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response)); } catch (Exception error) { Log.Error("Error occurred while deserializing server list from [" + serverListURL + "]: " + error.Message); } } catch (Exception error) { Log.Error("Error occurred while loading server list from [" + serverListURL + "]: " + error.Message); } } List <ServerInfo> newFinalItems = new List <ServerInfo>(); foreach (ServerInfo xServ in serverInfos) { if (newFinalItems.FindIndex(i => string.Equals(i.Name, xServ.Name)) == -1) { newFinalItems.Add(xServ); } } foreach (var substring in newFinalItems) { try { servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { "", "", "", "", "" } )); data.Add(ID, substring); ID++; } catch { } } Thread newList = new Thread(() => { Thread.Sleep(200); this.BeginInvoke((MethodInvoker) delegate { while (servers.Count != 0) { string QueueContent = servers.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; string servername = QueueContent2[2]; try { WebClientWithTimeout getdata = new WebClientWithTimeout(); getdata.Timeout(1000); GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl)); if (content == null) { ServerListRenderer.Items[serverid].SubItems[0].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; } else { ServerListRenderer.Items[serverid].SubItems[0].Text = servername; ServerListRenderer.Items[serverid].SubItems[1].Text = Self.CountryName(content.country.ToString()); ServerListRenderer.Items[serverid].SubItems[2].Text = content.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[3].Text = content.numberOfRegistered.ToString(); } } catch { ServerListRenderer.Items[serverid].SubItems[0].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; } if (servers.Count == 0) { loading.Text = ""; } Application.DoEvents(); } }); }); newList.IsBackground = true; newList.Start(); ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (ServerListRenderer.SelectedItems.Count == 1) { rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo); MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1]; this.Close(); } }); }
public SelectServer() { InitializeComponent(); //And one for keeping data about server, IP tbh Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>(); ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add("ID"); ServerListRenderer.Columns[0].Width = 25; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 320; ServerListRenderer.Columns.Add("Players Online"); ServerListRenderer.Columns[2].Width = 80; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Registered Players"); ServerListRenderer.Columns[3].Width = 100; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right; //Actually accept JSON instead of old format// List <ServerInfo> serverInfos = new List <ServerInfo>(); foreach (var serverListURL in Self.serverlisturl) { try { var wc = new WebClientWithTimeout(); var response = wc.DownloadString(serverListURL); try { serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response)); } catch (Exception error) { //throw new Exception("Error occurred while deserializing server list from [" + serverListURL + "]: " + error.Message, error); } } catch (Exception error) { //throw new Exception("Error occurred while loading server list from [" + serverListURL + "]: " + error.Message, error); } } foreach (var substring in serverInfos) { try { GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(new WebClientWithTimeout().DownloadString(substring.IpAddress + "/GetServerInformation")); Console.Write(content); if (content != null) { ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, content.onlineNumber.ToString(), content.numberOfRegistered.ToString(), } )); data.Add(ID, substring); } rememberServerInformationID.Add(ID, content); ID++; } catch { } } ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (ServerListRenderer.SelectedItems.Count == 1) { rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo); MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1]; this.Close(); } }); }
private void okButton_Click(object sender, EventArgs e) { bool success = true; error.Visible = false; this.Refresh(); String wellFormattedURL = ""; if (String.IsNullOrEmpty(serverAddress.Text)) { drawErrorAroundTextBox(serverAddress); success = false; } if (String.IsNullOrEmpty(serverName.Text)) { drawErrorAroundTextBox(serverName); success = false; } Uri uriResult; bool result = Uri.TryCreate(serverAddress.Text, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); if (!result) { drawErrorAroundTextBox(serverAddress); success = false; } else { Uri parsedServerAddress = new Uri(serverAddress.Text); string[] splitted = parsedServerAddress.AbsolutePath.Split('/'); if (splitted.Length == 3 || splitted.Length == 4) { if (String.IsNullOrEmpty(splitted[1])) { splitted[1] = "soapbox-race-core"; } if (String.IsNullOrEmpty(splitted[2])) { splitted[2] = "Engine.svc"; } if (parsedServerAddress.Port == 80) { wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + "/" + splitted[1] + "/" + splitted[2]; } else { wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + ":" + parsedServerAddress.Port + "/" + splitted[1] + "/" + splitted[2]; } } else { if (parsedServerAddress.Port == 80) { wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + "/soapbox-race-core/Engine.svc"; } else { wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + ":" + parsedServerAddress.Port + "/soapbox-race-core/Engine.svc"; } } } cancelButton.Enabled = false; okButton.Enabled = false; serverAddress.Enabled = false; serverName.Enabled = false; try { var client = new WebClientWithTimeout(); Uri StringToUri = new Uri(wellFormattedURL + "/GetServerInformation"); String serverLoginResponse = client.DownloadString(StringToUri); GetServerInformation json = JsonConvert.DeserializeObject <GetServerInformation>(serverLoginResponse); if (String.IsNullOrEmpty(json.serverName)) { drawErrorAroundTextBox(serverAddress); success = false; } } catch { drawErrorAroundTextBox(serverAddress); success = false; } cancelButton.Enabled = true; okButton.Enabled = true; serverAddress.Enabled = true; serverName.Enabled = true; if (success == true) { try { StreamReader sr = new StreamReader("servers.txt"); String oldcontent = sr.ReadToEnd(); sr.Close(); String addString = serverName.Text + ";" + wellFormattedURL + "\r\n"; File.WriteAllText("servers.txt", oldcontent + addString); MessageBox.Show(null, "New server will be added on next start of launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(null, "Failed to add new server. " + ex.Message, "GameLauncher", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } cancelButton_Click(sender, e); } else { error.Visible = true; } }
private void SetVisuals() { /*******************************/ /* Set Font / * /*******************************/ FontFamily DejaVuSans = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf"); FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf"); var MainFontSize = 9f * 96f / CreateGraphics().DpiY; if (UnixOS.Detected()) { MainFontSize = 9f; } Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); ServerListRenderer.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); Loading.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); BtnAddServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnRemoveServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnSelectServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnClose.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); Version.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); /********************************/ /* Set Theme Colors & Images / * /********************************/ ForeColor = Theming.WinFormTextForeColor; BackColor = Theming.WinFormTBGForeColor; Loading.ForeColor = Theming.WinFormWarningTextForeColor; Version.ForeColor = Theming.WinFormTextForeColor; ServerListRenderer.ForeColor = Theming.WinFormSecondaryTextForeColor; BtnAddServer.ForeColor = Theming.BlueForeColorButton; BtnAddServer.BackColor = Theming.BlueBackColorButton; BtnAddServer.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnAddServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; BtnRemoveServer.ForeColor = CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnRemoveServer.BackColor = CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnRemoveServer.FlatAppearance.BorderColor = CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnRemoveServer.FlatAppearance.MouseOverBackColor = CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnSelectServer.ForeColor = !CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnSelectServer.BackColor = !CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnSelectServer.FlatAppearance.BorderColor = !CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnSelectServer.FlatAppearance.MouseOverBackColor = !CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnClose.ForeColor = Theming.BlueForeColorButton; BtnClose.BackColor = Theming.BlueBackColorButton; BtnClose.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnClose.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; /********************************/ /* Functions / * /********************************/ Name = (CustomServersOnly ? "Saved Custom Servers" : "Please Select a Server") + " - SBRW Launcher"; ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (!CustomServersOnly) { SelectedGameServerToRemember(); } }); BtnSelectServer.Click += new EventHandler(BtnSelectServer_Click); BtnRemoveServer.Click += new EventHandler(BtnRemoveServer_Click); Version.Text = "Version: v" + Application.ProductVersion; /* And one for keeping data about server, IP tbh */ ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 210; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 100; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Online"); ServerListRenderer.Columns[3].Width = 75; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Registered"); ServerListRenderer.Columns[4].Width = 85; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 60; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Center; foreach (ServerList substring in CustomServersOnly ? ServerListUpdater.NoCategoryList_CSO : ServerListUpdater.NoCategoryList) { try { ServersToPing.Enqueue(ID + "_|||_" + substring.IPAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); ServerListBook.Add(ID, substring); ID++; } catch { } } Shown += (x, y) => { Application.OpenForms[this.Name].Activate(); this.BringToFront(); new Thread(() => { while (ServersToPing.Count != 0) { string QueueContent = ServersToPing.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; ServerName = QueueContent2[2]; string ServerJson = null; try { try { Uri URLCall = new Uri(serverurl); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerJson = Client.DownloadString(serverurl); } catch { } finally { if (Client != null) { Client.Dispose(); } } } catch { } if (string.IsNullOrWhiteSpace(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } else if (!IsJSONValid.ValidJson(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[3].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[4].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[5].Text = "-?-"; }, this); } else { ServerJsonData = JsonConvert.DeserializeObject <GetServerInformation>(ServerJson); ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = (!string.IsNullOrWhiteSpace(ServerJsonData.serverName)) ? ServerJsonData.serverName : ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(ServerJsonData.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = ServerJsonData.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = ServerJsonData.numberOfRegistered.ToString(); }, this); Ping CheckMate = null; try { Uri StringToUri = new Uri(serverurl); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; CheckMate = new Ping(); CheckMate.PingCompleted += (sender3, e3) => { if (e3.Reply != null) { if (e3.Reply.Status == IPStatus.Success && ServerName != "Offline Built-In Server") { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = e3.Reply.RoundtripTime + "ms"; }, this); } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "!?"; }, this); } } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A"; }, this); } ((AutoResetEvent)e3.UserState).Set(); }; CheckMate.SendAsync(StringToUri.Host, 5000, new byte[1], new PingOptions(30, true), new AutoResetEvent(false)); } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "?"; }, this); } finally { if (CheckMate != null) { CheckMate.Dispose(); } } } } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } finally { if (ServerJson != null) { ServerJson = null; } if (ServerJsonData != null) { ServerJsonData = null; } if (ServerName != null) { ServerName = null; } GC.Collect(); } Application.DoEvents(); } Loading.SafeInvokeAction(() => { Loading.Text = string.Empty; }, this); }).Start(); }; }
private void OkButton_Click(object sender, EventArgs e) { try { if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)))) { File.Move( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)), Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))); } else if (!File.Exists( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)))) { try { File.WriteAllText( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)), "[]"); } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } } } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } Error.Visible = false; this.Refresh(); if (IsNullOrWhiteSpace(ServerAddress.Text) || IsNullOrWhiteSpace(Strings.Encode(ServerName.Text))) { if (IsNullOrWhiteSpace(ServerAddress.Text)) { Error.Text = "Fix Empty IP"; DrawErrorAroundTextBox(ServerAddress); } else { Error.Text = "Fix Empty Name"; DrawErrorAroundTextBox(ServerName); } Error.Visible = true; return; } if (Error.Visible) { Error.Visible = false; } bool CorrectFormat = Uri.TryCreate(ServerAddress.Text, UriKind.Absolute, out Uri Result) && (Result.Scheme == Uri.UriSchemeHttp || Result.Scheme == Uri.UriSchemeHttps); string FormattedURL; if (!CorrectFormat) { DrawErrorAroundTextBox(ServerAddress); return; } else { FormattedURL = Result.ToString(); } ButtonControls(false); try { string ServerInfomationJSON = Empty; try { Uri StringToUri = new Uri(FormattedURL + "/GetServerInformation"); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerInfomationJSON = Client.DownloadString(StringToUri); } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (IsNullOrWhiteSpace(ServerInfomationJSON)) { ButtonControls(true); return; } else if (!IsJSONValid.ValidJson(ServerInfomationJSON)) { Error.Text = "Unstable Connection"; DrawErrorAroundTextBox(ServerAddress); Error.Visible = true; ButtonControls(true); ServerInfomationJSON = null; return; } else { GetServerInformation ServerInformationData = null; try { ServerInformationData = JsonConvert.DeserializeObject <GetServerInformation>(ServerInfomationJSON); } catch (Exception Error) { string LogMessage = "Add Server Get Information Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (ServerInformationData == null) { ButtonControls(true); ServerInfomationJSON = null; return; } else { string ServerID = Empty; Uri newModNetUri = new Uri(FormattedURL + "/Modding/GetModInfo"); ServicePointManager.FindServicePoint(newModNetUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { GetModInfo ServerGetInfo = JsonConvert.DeserializeObject <GetModInfo>(Client.DownloadString(newModNetUri)); ServerID = IsNullOrWhiteSpace(ServerGetInfo.serverID) ? Result.Host : ServerGetInfo.serverID; } catch (Exception Error) { LogToFileAddons.OpenLog("Add Server", null, Error, null, true); ServerID = Result.Host; } finally { if (Client != null) { Client.Dispose(); } } try { StreamReader sr = new StreamReader(Locations.LauncherCustomServers); String oldcontent = sr.ReadToEnd(); sr.Close(); if (IsNullOrWhiteSpace(oldcontent)) { oldcontent = "[]"; } var Servers = JsonConvert.DeserializeObject <List <ServerList> >(oldcontent); Servers.Add(new ServerList { Name = Strings.Encode(ServerName.Text), IPAddress = FormattedURL, IsSpecial = false, ID = ServerID, Category = IsNullOrWhiteSpace(Strings.Encode(ServerCategory.Text)) ? "Custom" : Strings.Encode(ServerCategory.Text) }); File.WriteAllText(Locations.LauncherCustomServers, JsonConvert.SerializeObject(Servers)); MessageBox.Show(null, "The New server will be added on the next start of the Launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception Error) { string LogMessage = "Failed to Add New Server:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); ButtonControls(true); return; } finally { if (ServerID != null) { ServerID = null; } if (ServerInfomationJSON != null) { ServerInfomationJSON = null; } } CancelButton_Click(sender, e); } } } catch { DrawErrorAroundTextBox(ServerAddress); ButtonControls(true); } }
public SelectServer(String windowName = "") { InitializeComponent(); if (windowName != "") { this.Text = windowName; } //And one for keeping data about server, IP tbh Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>(); ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 220; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 80; ServerListRenderer.Columns.Add("Players Online"); ServerListRenderer.Columns[3].Width = 80; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Registered Players"); ServerListRenderer.Columns[4].Width = 100; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 55; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Right; //Actually accept JSON instead of old format// List <ServerInfo> serverInfos = new List <ServerInfo>(); //foreach (var serverListURL in Self.serverlisturl) { try { var wc = new WebClientWithTimeout(); var response = wc.DownloadString(Self.serverlisturl[0]); try { serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response)); } catch (Exception error) { Log.Error("Error occurred while deserializing server list from [" + Self.serverlisturl[0] + "]: " + error.Message); } } catch (Exception error) { Log.Error("Error occurred while loading server list from [" + Self.serverlisturl[0] + "]: " + error.Message); } //} if (File.Exists("servers.json")) { var fileItems = JsonConvert.DeserializeObject <List <ServerInfo> >(File.ReadAllText("servers.json")); if (fileItems.Count > 0) { fileItems.Select(si => { si.DistributionUrl = ""; si.DiscordPresenceKey = ""; si.Id = SHA.HashPassword($"{si.Name}:{si.Id}:{si.IpAddress}"); si.IsSpecial = false; si.Category = "CUSTOM"; return(si); }).ToList().ForEach(si => serverInfos.Add(si)); } } List <ServerInfo> newFinalItems = new List <ServerInfo>(); foreach (ServerInfo xServ in serverInfos) { if (newFinalItems.FindIndex(i => string.Equals(i.Name, xServ.Name)) == -1) { newFinalItems.Add(xServ); } } foreach (var substring in newFinalItems) { try { servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); data.Add(ID, substring); ID++; } catch { } } Thread newList = new Thread(() => { Thread.Sleep(200); this.BeginInvoke((MethodInvoker) delegate { while (servers.Count != 0) { string QueueContent = servers.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; string servername = QueueContent2[2]; try { WebClientWithTimeout getdata = new WebClientWithTimeout(); getdata.Timeout(1000); GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl)); if (content == null) { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; } else { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = Self.CountryName(content.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = content.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = content.numberOfRegistered.ToString(); //PING if (!DetectLinux.LinuxDetected()) { Ping pingSender = new Ping(); Uri StringToUri = new Uri(serverurl); pingSender.SendAsync(StringToUri.Host, 1000, new byte[1], new PingOptions(64, true), new AutoResetEvent(false)); pingSender.PingCompleted += (sender3, e3) => { PingReply reply = e3.Reply; if (reply.Status == IPStatus.Success && servername != "Offline Built-In Server") { ServerListRenderer.Items[serverid].SubItems[5].Text = reply.RoundtripTime + "ms"; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } }; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } } } catch { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[4].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } if (servers.Count == 0) { loading.Text = ""; } Application.DoEvents(); } }); }); newList.IsBackground = true; newList.Start(); ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (ServerListRenderer.SelectedItems.Count == 1) { rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo); MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1]; this.Close(); } }); }