diff --git a/Giants.DataContract/Contracts/VersionInfo.cs b/Giants.DataContract/Contracts/V1/GiantsVersion.cs similarity index 76% rename from Giants.DataContract/Contracts/VersionInfo.cs rename to Giants.DataContract/Contracts/V1/GiantsVersion.cs index 7edbd57..6f63807 100644 --- a/Giants.DataContract/Contracts/VersionInfo.cs +++ b/Giants.DataContract/Contracts/V1/GiantsVersion.cs @@ -3,7 +3,7 @@ using System; using System.ComponentModel.DataAnnotations; - public class VersionInfo + public class GiantsVersion { [Required] public int Build { get; set; } @@ -19,7 +19,7 @@ public override bool Equals(object obj) { - return obj is VersionInfo info && + return obj is GiantsVersion info && Build == info.Build && Major == info.Major && Minor == info.Minor && @@ -30,5 +30,10 @@ { return HashCode.Combine(Build, Major, Minor, Revision); } + + public Version ToVersion() + { + return new Version(this.Major, this.Minor, this.Build, this.Revision); + } } } diff --git a/Giants.DataContract/Contracts/PlayerInfo.cs b/Giants.DataContract/Contracts/V1/PlayerInfo.cs similarity index 100% rename from Giants.DataContract/Contracts/PlayerInfo.cs rename to Giants.DataContract/Contracts/V1/PlayerInfo.cs diff --git a/Giants.DataContract/Contracts/ServerInfo.cs b/Giants.DataContract/Contracts/V1/ServerInfo.cs similarity index 94% rename from Giants.DataContract/Contracts/ServerInfo.cs rename to Giants.DataContract/Contracts/V1/ServerInfo.cs index 171be41..796aa18 100644 --- a/Giants.DataContract/Contracts/ServerInfo.cs +++ b/Giants.DataContract/Contracts/V1/ServerInfo.cs @@ -12,7 +12,7 @@ public string GameName { get; set; } [Required] - public VersionInfo Version { get; set; } + public GiantsVersion Version { get; set; } [Required] [StringLength(100)] @@ -55,7 +55,7 @@ { return obj is ServerInfo info && GameName == info.GameName && - EqualityComparer.Default.Equals(Version, info.Version) && + EqualityComparer.Default.Equals(Version, info.Version) && SessionName == info.SessionName && Port == info.Port && MapName == info.MapName && diff --git a/Giants.DataContract/Contracts/ServerInfoWithHostAddress.cs b/Giants.DataContract/Contracts/V1/ServerInfoWithHostAddress.cs similarity index 100% rename from Giants.DataContract/Contracts/ServerInfoWithHostAddress.cs rename to Giants.DataContract/Contracts/V1/ServerInfoWithHostAddress.cs diff --git a/Giants.DataContract/Contracts/V1/VersionInfo.cs b/Giants.DataContract/Contracts/V1/VersionInfo.cs new file mode 100644 index 0000000..6446024 --- /dev/null +++ b/Giants.DataContract/Contracts/V1/VersionInfo.cs @@ -0,0 +1,20 @@ +namespace Giants.DataContract +{ + using System; + using System.ComponentModel.DataAnnotations; + + public class VersionInfo + { + [Required] + public string GameName { get; set; } + + [Required] + public GiantsVersion GameVersion { get; set; } + + [Required] + public GiantsVersion LauncherVersion { get; set; } + + [Required] + public Uri PatchUri { get; set; } + } +} diff --git a/Giants.Launcher/Extensions.cs b/Giants.Launcher/Extensions.cs index faf990b..c1770ec 100644 --- a/Giants.Launcher/Extensions.cs +++ b/Giants.Launcher/Extensions.cs @@ -1,12 +1,9 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using Microsoft.Win32; namespace Giants.Launcher { - public static class RegistryExtensions + public static class RegistryExtensions { // Extension to Registry.GetValue() that returns the default value if the returned object does not // match the type specified. diff --git a/Giants.Launcher/GameSettings.cs b/Giants.Launcher/GameSettings.cs index 69f4ece..8f1cc5d 100644 --- a/Giants.Launcher/GameSettings.cs +++ b/Giants.Launcher/GameSettings.cs @@ -1,28 +1,27 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Windows.Forms; using System.IO; +using System.Linq; +using System.Windows.Forms; using Microsoft.Win32; namespace Giants.Launcher { - static class GameSettings + static class GameSettings { // Constants private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants"; private const int OPTIONS_VERSION = 3; - private static readonly Dictionary _Settings = new Dictionary(); + private static readonly Dictionary Settings = new Dictionary(); // List of renderers compatible with the user's system. static public List CompatibleRenderers; public static object Get(string settingName) { - if (_Settings.ContainsKey(settingName)) - return _Settings[settingName]; + if (Settings.ContainsKey(settingName)) + return Settings[settingName]; else return 0; @@ -30,23 +29,23 @@ namespace Giants.Launcher public static void Modify(string settingName, object settingValue) { - _Settings[settingName] = settingValue; + Settings[settingName] = settingValue; } public static void SetDefaults(string gamePath) { // Set default settings: - _Settings["Renderer"] = "gg_dx7r.dll"; - _Settings["Antialiasing"] = 0; - _Settings["AnisotropicFiltering"] = 0; - _Settings["VideoWidth"] = 640; - _Settings["VideoHeight"] = 480; - _Settings["VideoDepth"] = 32; - _Settings["Windowed"] = 0; - _Settings["BorderlessWindow"] = 0; - _Settings["VerticalSync"] = 1; - _Settings["TripleBuffering"] = 1; - _Settings["NoAutoUpdate"] = 0; + Settings["Renderer"] = "gg_dx7r.dll"; + Settings["Antialiasing"] = 0; + Settings["AnisotropicFiltering"] = 0; + Settings["VideoWidth"] = 640; + Settings["VideoHeight"] = 480; + Settings["VideoDepth"] = 32; + Settings["Windowed"] = 0; + Settings["BorderlessWindow"] = 0; + Settings["VerticalSync"] = 1; + Settings["TripleBuffering"] = 1; + Settings["NoAutoUpdate"] = 0; // Get a list of renderers compatible with the user's system if (CompatibleRenderers == null) @@ -61,11 +60,11 @@ namespace Giants.Launcher // Select the highest priority renderer if (CompatibleRenderers.Count > 0) - _Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath); + Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath); // Set the current desktop resolution, leaving bit depth at the default 32: - _Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width; - _Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height; + Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width; + Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height; } public static void Load(string gamePath) @@ -76,18 +75,18 @@ namespace Giants.Launcher { try { - _Settings["Renderer"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Renderer", _Settings["Renderer"], typeof(string)); + Settings["Renderer"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], typeof(string)); //System.Diagnostics.Debug.Assert(_Settings["Renderer"] is string); - _Settings["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", _Settings["Antialiasing"], typeof(int)); - _Settings["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", _Settings["AnisotropicFiltering"], typeof(int)); - _Settings["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", _Settings["VideoWidth"], typeof(int)); - _Settings["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", _Settings["VideoHeight"], typeof(int)); - _Settings["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", _Settings["VideoDepth"], typeof(int)); - _Settings["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", _Settings["Windowed"], typeof(int)); - _Settings["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", _Settings["BorderlessWindow"], typeof(int)); - _Settings["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", _Settings["VerticalSync"], typeof(int)); - _Settings["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", _Settings["TripleBuffering"], typeof(int)); - _Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", _Settings["NoAutoUpdate"], typeof(int)); + Settings["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], typeof(int)); + Settings["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], typeof(int)); + Settings["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], typeof(int)); + Settings["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], typeof(int)); + Settings["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], typeof(int)); + Settings["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], typeof(int)); + Settings["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], typeof(int)); + Settings["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], typeof(int)); + Settings["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], typeof(int)); + Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int)); } catch (Exception ex) { @@ -101,17 +100,17 @@ namespace Giants.Launcher try { Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "Renderer", _Settings["Renderer"], RegistryValueKind.String); - Registry.SetValue(REGISTRY_KEY, "Antialiasing", _Settings["Antialiasing"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", _Settings["AnisotropicFiltering"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "VideoWidth", _Settings["VideoWidth"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "VideoHeight", _Settings["VideoHeight"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "VideoDepth", _Settings["VideoDepth"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "Windowed", _Settings["Windowed"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", _Settings["BorderlessWindow"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "VerticalSync", _Settings["VerticalSync"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "TripleBuffering", _Settings["TripleBuffering"], RegistryValueKind.DWord); - Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", _Settings["NoAutoUpdate"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String); + Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord); + Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord); } catch (Exception ex) { diff --git a/Giants.Launcher/Giants.Launcher.csproj b/Giants.Launcher/Giants.Launcher.csproj index a988472..b1d176f 100644 --- a/Giants.Launcher/Giants.Launcher.csproj +++ b/Giants.Launcher/Giants.Launcher.csproj @@ -72,7 +72,7 @@ - + Component @@ -95,6 +95,9 @@ + + + LauncherForm.cs Giants.Launcher @@ -114,7 +117,7 @@ True - + diff --git a/Giants.Launcher/ImageButton.cs b/Giants.Launcher/ImageButton.cs index cd34949..3245a11 100644 --- a/Giants.Launcher/ImageButton.cs +++ b/Giants.Launcher/ImageButton.cs @@ -17,17 +17,17 @@ namespace Giants.Launcher { get { - return m_DialogResult; + return this.m_DialogResult; } set { - m_DialogResult = value; + this.m_DialogResult = value; } } public void NotifyDefault(bool value) { - isDefault = value; + this.isDefault = value; } public void PerformClick() @@ -44,8 +44,8 @@ namespace Giants.Launcher [Description("Image to show when the button is hovered over.")] public Image HoverImage { - get { return m_HoverImage; } - set { m_HoverImage = value; if (hover) Image = value; } + get { return this.m_HoverImage; } + set { this.m_HoverImage = value; if (this.hover) this.Image = value; } } #endregion #region DownImage @@ -55,8 +55,8 @@ namespace Giants.Launcher [Description("Image to show when the button is depressed.")] public Image DownImage { - get { return m_DownImage; } - set { m_DownImage = value; if (down) Image = value; } + get { return this.m_DownImage; } + set { this.m_DownImage = value; if (this.down) this.Image = value; } } #endregion #region NormalImage @@ -66,8 +66,8 @@ namespace Giants.Launcher [Description("Image to show when the button is not in any other state.")] public Image NormalImage { - get { return m_NormalImage; } - set { m_NormalImage = value; if (!(hover || down)) Image = value; } + get { return this.m_NormalImage; } + set { this.m_NormalImage = value; if (!(this.hover || this.down)) this.Image = value; } } #endregion @@ -155,60 +155,60 @@ namespace Giants.Launcher #region Events protected override void OnMouseMove(MouseEventArgs e) { - hover = true; - if (down) + this.hover = true; + if (this.down) { - if ((m_DownImage != null) && (Image != m_DownImage)) - Image = m_DownImage; + if ((this.m_DownImage != null) && (this.Image != this.m_DownImage)) + this.Image = this.m_DownImage; } else - if (m_HoverImage != null) - Image = m_HoverImage; + if (this.m_HoverImage != null) + this.Image = this.m_HoverImage; else - Image = m_NormalImage; + this.Image = this.m_NormalImage; base.OnMouseMove(e); } protected override void OnMouseLeave(EventArgs e) { - hover = false; - Image = m_NormalImage; + this.hover = false; + this.Image = this.m_NormalImage; base.OnMouseLeave(e); } protected override void OnMouseDown(MouseEventArgs e) { base.Focus(); - OnMouseUp(null); - down = true; - if (m_DownImage != null) - Image = m_DownImage; + this.OnMouseUp(null); + this.down = true; + if (this.m_DownImage != null) + this.Image = this.m_DownImage; base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { - down = false; - if (hover) + this.down = false; + if (this.hover) { - if (m_HoverImage != null) - Image = m_HoverImage; + if (this.m_HoverImage != null) + this.Image = this.m_HoverImage; } else - Image = m_NormalImage; + this.Image = this.m_NormalImage; base.OnMouseUp(e); } protected override void OnLostFocus(EventArgs e) { - OnMouseUp(null); + this.OnMouseUp(null); base.OnLostFocus(e); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); - if ((!string.IsNullOrEmpty(Text)) && (pe != null) && (base.Font != null)) + if ((!string.IsNullOrEmpty(this.Text)) && (pe != null) && (base.Font != null)) { SolidBrush drawBrush = new SolidBrush(base.ForeColor); SizeF drawStringSize = pe.Graphics.MeasureString(base.Text, base.Font); @@ -223,7 +223,7 @@ namespace Giants.Launcher protected override void OnTextChanged(EventArgs e) { - Refresh(); + this.Refresh(); base.OnTextChanged(e); } #endregion diff --git a/Giants.Launcher/LauncherForm.cs b/Giants.Launcher/LauncherForm.cs index 39af83a..e1eaa84 100644 --- a/Giants.Launcher/LauncherForm.cs +++ b/Giants.Launcher/LauncherForm.cs @@ -24,7 +24,7 @@ namespace Giants.Launcher public LauncherForm() { - InitializeComponent(); + this.InitializeComponent(); // Set window title this.Text = GAME_NAME; @@ -40,31 +40,31 @@ namespace Giants.Launcher GameSettings.Save(); foreach (string c in Environment.GetCommandLineArgs()) - _commandLine = _commandLine + c + " "; + this._commandLine = this._commandLine + c + " "; - string commandLine = string.Format("{0} -launcher", _commandLine.Trim()); + string commandLine = string.Format("{0} -launcher", this._commandLine.Trim()); try { Process gameProcess = new Process(); gameProcess.StartInfo.Arguments = commandLine; - gameProcess.StartInfo.FileName = _gamePath; - gameProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(_gamePath); + gameProcess.StartInfo.FileName = this._gamePath; + gameProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(this._gamePath); gameProcess.Start(); Application.Exit(); } catch(Exception ex) { - MessageBox.Show(string.Format("Failed to launch game process at: {0}. {1}", _gamePath, ex.Message), + MessageBox.Show(string.Format("Failed to launch game process at: {0}. {1}", this._gamePath, ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnOptions_Click(object sender, EventArgs e) { - OptionsForm form = new OptionsForm(GAME_NAME + " Options", _gamePath); + OptionsForm form = new OptionsForm(GAME_NAME + " Options", this._gamePath); //form.MdiParent = this; form.ShowDialog(); @@ -74,14 +74,14 @@ namespace Giants.Launcher { // Find the game executable, first looking for it relative to our current directory and then // using the registry path if that fails. - _gamePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + GAME_PATH; - if (!File.Exists(_gamePath)) + this._gamePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + GAME_PATH; + if (!File.Exists(this._gamePath)) { - _gamePath = (string)Registry.GetValue(REGISTRY_KEY, REGISTRY_VALUE, null); - if (_gamePath != null) - _gamePath = Path.Combine(_gamePath, GAME_PATH); + this._gamePath = (string)Registry.GetValue(REGISTRY_KEY, REGISTRY_VALUE, null); + if (this._gamePath != null) + this._gamePath = Path.Combine(this._gamePath, GAME_PATH); - if (_gamePath == null || !File.Exists(_gamePath)) + if (this._gamePath == null || !File.Exists(this._gamePath)) { string message = string.Format(Resources.AppNotFound, GAME_NAME); MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -94,7 +94,7 @@ namespace Giants.Launcher try { - FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(_gamePath); + FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(this._gamePath); gameVersion = new Version(fvi.FileVersion.Replace(',', '.')); } finally @@ -108,13 +108,13 @@ namespace Giants.Launcher } // Read game settings from registry - GameSettings.Load(_gamePath); + GameSettings.Load(this._gamePath); if ((int)GameSettings.Get("NoAutoUpdate") == 0) { - // Check for updates - _Updater = new Updater(new Uri(UPDATE_URL), gameVersion); - _Updater.DownloadUpdateInfo(LauncherForm_DownloadCompletedCallback, LauncherForm_DownloadProgressCallback); + // Check for updates + this._Updater = new Updater(new Uri(UPDATE_URL), gameVersion); + this._Updater.DownloadUpdateInfo(this.LauncherForm_DownloadCompletedCallback, this.LauncherForm_DownloadProgressCallback); } } @@ -124,16 +124,16 @@ namespace Giants.Launcher if (e.Button == MouseButtons.Left) { NativeMethods.ReleaseCapture(); - NativeMethods.SendMessage(Handle, NativeMethods.WM_NCLBUTTONDOWN, NativeMethods.HT_CAPTION, 0); + NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCLBUTTONDOWN, NativeMethods.HT_CAPTION, 0); } } private void LauncherForm_Shown(object sender, EventArgs e) { - btnOptions.Visible = true; - btnPlay.Visible = true; - btnExit.Visible = true; + this.btnOptions.Visible = true; + this.btnPlay.Visible = true; + this.btnExit.Visible = true; // Play intro sound SoundPlayer player = new SoundPlayer(Resources.LauncherStart); @@ -145,9 +145,9 @@ namespace Giants.Launcher if (e.Cancelled) return; - updateProgressBar.Value = 0; - updateProgressBar.Visible = false; - txtProgress.Visible = false; + this.updateProgressBar.Value = 0; + this.updateProgressBar.Visible = false; + this.txtProgress.Visible = false; if (e.Error != null) { @@ -187,13 +187,13 @@ namespace Giants.Launcher private void LauncherForm_DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) { - updateProgressBar.Visible = true; - updateProgressBar.Value = e.ProgressPercentage; + this.updateProgressBar.Visible = true; + this.updateProgressBar.Value = e.ProgressPercentage; UpdateInfo info = (UpdateInfo)e.UserState; - txtProgress.Visible = true; - txtProgress.Text = string.Format(Resources.DownloadProgress, e.ProgressPercentage, (info.FileSize / 1024) / 1024); + this.txtProgress.Visible = true; + this.txtProgress.Text = string.Format(Resources.DownloadProgress, e.ProgressPercentage, (info.FileSize / 1024) / 1024); } } } diff --git a/Giants.Launcher/Native/RendererInterop.cs b/Giants.Launcher/Native/RendererInterop.cs index fd02899..1319440 100644 --- a/Giants.Launcher/Native/RendererInterop.cs +++ b/Giants.Launcher/Native/RendererInterop.cs @@ -104,17 +104,17 @@ namespace Giants.Launcher public Capabilities(string filePath, ref RendererInterop.GFXCapabilityInfo gfxCaps) { - FilePath = filePath; - FileName = Path.GetFileName(filePath); - MaxAnisotropy = gfxCaps.maxAnisotropy; - Flags = (RendererFlag)gfxCaps.flags; - Priority = gfxCaps.priority; - Name = gfxCaps.rendererName; + this.FilePath = filePath; + this.FileName = Path.GetFileName(filePath); + this.MaxAnisotropy = gfxCaps.maxAnisotropy; + this.Flags = (RendererFlag)gfxCaps.flags; + this.Priority = gfxCaps.priority; + this.Name = gfxCaps.rendererName; } public override string ToString() { - return string.Format("{0} ({1})", Name, Path.GetFileName(FilePath)); + return string.Format("{0} ({1})", this.Name, Path.GetFileName(this.FilePath)); } public int CompareTo(object obj) diff --git a/Giants.Launcher/OptionsForm.cs b/Giants.Launcher/OptionsForm.cs index f3c769b..fe9aa9a 100644 --- a/Giants.Launcher/OptionsForm.cs +++ b/Giants.Launcher/OptionsForm.cs @@ -11,7 +11,7 @@ namespace Giants.Launcher public OptionsForm(string title, string gamePath) { - InitializeComponent(); + this.InitializeComponent(); this.Text = title; this.gamePath = gamePath; @@ -19,40 +19,40 @@ namespace Giants.Launcher private void OptionsForm_Load(object sender, EventArgs e) { - PopulateResolution(); - SetOptions(); + this.PopulateResolution(); + this.SetOptions(); } private void SetOptions() { - cmbRenderer.Items.Clear(); - cmbRenderer.Items.AddRange(GameSettings.CompatibleRenderers.ToArray()); + this.cmbRenderer.Items.Clear(); + this.cmbRenderer.Items.AddRange(GameSettings.CompatibleRenderers.ToArray()); RendererInterop.Capabilities renderer = GameSettings.CompatibleRenderers.Find(r => StringComparer.OrdinalIgnoreCase.Compare(Path.GetFileName(r.FilePath), GameSettings.Get("Renderer")) == 0); if (renderer != null) - cmbRenderer.SelectedItem = renderer; + this.cmbRenderer.SelectedItem = renderer; else { renderer = GameSettings.CompatibleRenderers.Find(r => r.Name == "DirectX 7"); - cmbRenderer.SelectedItem = renderer; + this.cmbRenderer.SelectedItem = renderer; } - var Resolutions = (List)cmbResolution.DataSource; - cmbResolution.SelectedItem = Resolutions.Find(r => r.Width == (int)GameSettings.Get("VideoWidth") && r.Height == (int)GameSettings.Get("VideoHeight")); - if (cmbResolution.SelectedItem == null) - cmbResolution.SelectedIndex = 0; + var Resolutions = (List)this.cmbResolution.DataSource; + this.cmbResolution.SelectedItem = Resolutions.Find(r => r.Width == (int)GameSettings.Get("VideoWidth") && r.Height == (int)GameSettings.Get("VideoHeight")); + if (this.cmbResolution.SelectedItem == null) + this.cmbResolution.SelectedIndex = 0; - var AntialiasingOptions = (List>)cmbAntialiasing.DataSource; - cmbAntialiasing.SelectedItem = AntialiasingOptions.Find(o => o.Value == (int)GameSettings.Get("Antialiasing")); - if (cmbAntialiasing.SelectedItem == null) - cmbAntialiasing.SelectedIndex = 0; + var AntialiasingOptions = (List>)this.cmbAntialiasing.DataSource; + this.cmbAntialiasing.SelectedItem = AntialiasingOptions.Find(o => o.Value == (int)GameSettings.Get("Antialiasing")); + if (this.cmbAntialiasing.SelectedItem == null) + this.cmbAntialiasing.SelectedIndex = 0; - var AnisotropyOptions = (List>)cmbAnisotropy.DataSource; - cmbAnisotropy.SelectedItem = AnisotropyOptions.Find(o => o.Value == (int)GameSettings.Get("AnisotropicFiltering")); - if (cmbAnisotropy.SelectedItem == null) - cmbAnisotropy.SelectedIndex = 0; + var AnisotropyOptions = (List>)this.cmbAnisotropy.DataSource; + this.cmbAnisotropy.SelectedItem = AnisotropyOptions.Find(o => o.Value == (int)GameSettings.Get("AnisotropicFiltering")); + if (this.cmbAnisotropy.SelectedItem == null) + this.cmbAnisotropy.SelectedIndex = 0; - chkUpdates.Checked = ((int)GameSettings.Get("NoAutoUpdate") == 1 ? false : true); + this.chkUpdates.Checked = ((int)GameSettings.Get("NoAutoUpdate") == 1 ? false : true); } private void PopulateAntialiasing() @@ -61,7 +61,7 @@ namespace Giants.Launcher AntialiasingOptions.Add(new KeyValuePair("None (Best performance)", 0)); - var renderer = (RendererInterop.Capabilities)cmbRenderer.SelectedItem; + var renderer = (RendererInterop.Capabilities)this.cmbRenderer.SelectedItem; if (renderer != null) { if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.MSAA2x) == RendererInterop.Capabilities.RendererFlag.MSAA2x) @@ -76,20 +76,20 @@ namespace Giants.Launcher // Try to keep current selection when repopulating int? currentValue = null; - if (cmbAntialiasing.SelectedValue != null) + if (this.cmbAntialiasing.SelectedValue != null) { - currentValue = (int)cmbAntialiasing.SelectedValue; + currentValue = (int)this.cmbAntialiasing.SelectedValue; } - cmbAntialiasing.DataSource = AntialiasingOptions; - cmbAntialiasing.DisplayMember = "Key"; - cmbAntialiasing.ValueMember = "Value"; + this.cmbAntialiasing.DataSource = AntialiasingOptions; + this.cmbAntialiasing.DisplayMember = "Key"; + this.cmbAntialiasing.ValueMember = "Value"; if (currentValue != null) - cmbAntialiasing.SelectedValue = currentValue; + this.cmbAntialiasing.SelectedValue = currentValue; - if (cmbAntialiasing.SelectedValue == null) - cmbAntialiasing.SelectedIndex = 0; + if (this.cmbAntialiasing.SelectedValue == null) + this.cmbAntialiasing.SelectedIndex = 0; } private bool IsPowerOfTwo(int x) @@ -103,12 +103,12 @@ namespace Giants.Launcher AnisotropyOptions.Add(new KeyValuePair("None (Best performance)", 0)); - var renderer = (RendererInterop.Capabilities)cmbRenderer.SelectedItem; + var renderer = (RendererInterop.Capabilities)this.cmbRenderer.SelectedItem; if (renderer != null) { for (int i = 2; i <= renderer.MaxAnisotropy; i++) { - if (!IsPowerOfTwo(i)) continue; + if (!this.IsPowerOfTwo(i)) continue; AnisotropyOptions.Add(new KeyValuePair(String.Format("{0} Samples", i), i)); } @@ -116,20 +116,20 @@ namespace Giants.Launcher // Try to keep current selection when repopulating int? currentValue = null; - if (cmbAnisotropy.SelectedValue != null) + if (this.cmbAnisotropy.SelectedValue != null) { - currentValue = (int)cmbAnisotropy.SelectedValue; + currentValue = (int)this.cmbAnisotropy.SelectedValue; } - cmbAnisotropy.DataSource = AnisotropyOptions; - cmbAnisotropy.DisplayMember = "Key"; - cmbAnisotropy.ValueMember = "Value"; + this.cmbAnisotropy.DataSource = AnisotropyOptions; + this.cmbAnisotropy.DisplayMember = "Key"; + this.cmbAnisotropy.ValueMember = "Value"; if (currentValue != null) - cmbAnisotropy.SelectedValue = currentValue; + this.cmbAnisotropy.SelectedValue = currentValue; - if (cmbAnisotropy.SelectedValue == null) - cmbAnisotropy.SelectedIndex = 0; + if (this.cmbAnisotropy.SelectedValue == null) + this.cmbAnisotropy.SelectedIndex = 0; } private void PopulateResolution() @@ -149,75 +149,75 @@ namespace Giants.Launcher } resolutions.Sort(); - cmbResolution.DataSource = resolutions; + this.cmbResolution.DataSource = resolutions; } private void cmbRenderer_SelectedIndexChanged(object sender, EventArgs e) { - PopulateAntialiasing(); - PopulateAnisotropy(); + this.PopulateAntialiasing(); + this.PopulateAnisotropy(); bool windowed = ((int)GameSettings.Get("Windowed") == 1 ? true : false); if (windowed) { bool borderless = (int)GameSettings.Get("BorderlessWindow") == 1 ? true : false; if (borderless) - cmbMode.SelectedIndex = 2; + this.cmbMode.SelectedIndex = 2; else - cmbMode.SelectedIndex = 1; + this.cmbMode.SelectedIndex = 1; } else - cmbMode.SelectedIndex = 0; + this.cmbMode.SelectedIndex = 0; - var renderer = (RendererInterop.Capabilities)cmbRenderer.SelectedItem; + var renderer = (RendererInterop.Capabilities)this.cmbRenderer.SelectedItem; if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.VSync) != RendererInterop.Capabilities.RendererFlag.VSync) { - chkVSync.Checked = false; - chkVSync.Enabled = false; + this.chkVSync.Checked = false; + this.chkVSync.Enabled = false; } else { - chkVSync.Checked = ((int)GameSettings.Get("VerticalSync") == 1 ? true : false); - chkVSync.Enabled = true; + this.chkVSync.Checked = ((int)GameSettings.Get("VerticalSync") == 1 ? true : false); + this.chkVSync.Enabled = true; } if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.TripleBuffer) != RendererInterop.Capabilities.RendererFlag.TripleBuffer) { - chkTripleBuffering.Checked = false; - chkTripleBuffering.Enabled = false; + this.chkTripleBuffering.Checked = false; + this.chkTripleBuffering.Enabled = false; } else { - chkTripleBuffering.Checked = ((int)GameSettings.Get("TripleBuffering") == 1 ? true : false); - chkTripleBuffering.Enabled = true; + this.chkTripleBuffering.Checked = ((int)GameSettings.Get("TripleBuffering") == 1 ? true : false); + this.chkTripleBuffering.Enabled = true; } } private void btnOK_Click(object sender, EventArgs e) { - var renderer = cmbRenderer.SelectedItem as RendererInterop.Capabilities; + var renderer = this.cmbRenderer.SelectedItem as RendererInterop.Capabilities; if (renderer != null) { GameSettings.Modify("Renderer", renderer.FileName); } - var resolution = (ScreenResolution)cmbResolution.SelectedItem; + var resolution = (ScreenResolution)this.cmbResolution.SelectedItem; if (resolution != null) { GameSettings.Modify("VideoWidth", resolution.Width); GameSettings.Modify("VideoHeight", resolution.Height); } - GameSettings.Modify("Antialiasing", cmbAntialiasing.SelectedValue); - GameSettings.Modify("AnisotropicFiltering", cmbAnisotropy.SelectedValue); - bool windowed = ((WindowType)cmbMode.SelectedIndex == WindowType.Windowed || (WindowType)cmbMode.SelectedIndex == WindowType.Borderless); + GameSettings.Modify("Antialiasing", this.cmbAntialiasing.SelectedValue); + GameSettings.Modify("AnisotropicFiltering", this.cmbAnisotropy.SelectedValue); + bool windowed = ((WindowType)this.cmbMode.SelectedIndex == WindowType.Windowed || (WindowType)this.cmbMode.SelectedIndex == WindowType.Borderless); GameSettings.Modify("Windowed", (windowed == true ? 1 : 0)); - bool borderless = (WindowType)cmbMode.SelectedIndex == WindowType.Borderless; + bool borderless = (WindowType)this.cmbMode.SelectedIndex == WindowType.Borderless; GameSettings.Modify("BorderlessWindow", borderless == true ? 1 : 0); - GameSettings.Modify("VerticalSync", (chkVSync.Checked == true ? 1 : 0)); - GameSettings.Modify("TripleBuffering", (chkTripleBuffering.Checked == true ? 1 : 0)); - GameSettings.Modify("NoAutoUpdate", (chkUpdates.Checked == false ? 1 : 0)); + GameSettings.Modify("VerticalSync", (this.chkVSync.Checked == true ? 1 : 0)); + GameSettings.Modify("TripleBuffering", (this.chkTripleBuffering.Checked == true ? 1 : 0)); + GameSettings.Modify("NoAutoUpdate", (this.chkUpdates.Checked == false ? 1 : 0)); GameSettings.Save(); @@ -227,13 +227,13 @@ namespace Giants.Launcher private void btnCancel_Click(object sender, EventArgs e) { this.Close(); - GameSettings.Load(gamePath); + GameSettings.Load(this.gamePath); } private void btnResetDefaults_Click(object sender, EventArgs e) { - GameSettings.SetDefaults(gamePath); - SetOptions(); + GameSettings.SetDefaults(this.gamePath); + this.SetOptions(); } } } diff --git a/Giants.Launcher/Common.cs b/Giants.Launcher/ScreenResolution.cs similarity index 66% rename from Giants.Launcher/Common.cs rename to Giants.Launcher/ScreenResolution.cs index 50b31c3..eae2de6 100644 --- a/Giants.Launcher/Common.cs +++ b/Giants.Launcher/ScreenResolution.cs @@ -1,19 +1,16 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Giants.Launcher { - class ScreenResolution : IComparable + class ScreenResolution : IComparable { public int Width { get; set; } public int Height { get; set; } public ScreenResolution(int width, int height) { - Width = width; - Height = height; + this.Width = width; + this.Height = height; } public int CompareTo(object obj) @@ -34,15 +31,8 @@ namespace Giants.Launcher public override string ToString() { - return string.Format("{0}x{1}", Width, Height); + return string.Format("{0}x{1}", this.Width, this.Height); } } - - public enum WindowType - { - Fullscreen = 0, - Windowed = 1, - Borderless = 2, - } } diff --git a/Giants.Launcher/Updater/UpdateInfo.cs b/Giants.Launcher/Updater/UpdateInfo.cs new file mode 100644 index 0000000..9b90304 --- /dev/null +++ b/Giants.Launcher/Updater/UpdateInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.IO; + +namespace Giants.Launcher +{ + public class UpdateInfo + { + public Version VersionFrom { get; set; } + public Version VersionTo { get; set; } + public Uri DownloadUri + { + get + { + return this.downloadUri; + } + set + { + this.downloadUri = value; + this.FileName = Path.GetFileName(value.AbsoluteUri); + } + } + public int FileSize { get; set; } + public string FileName { get; set; } + public UpdateType UpdateType { get; set; } + + private Uri downloadUri; + } +} diff --git a/Giants.Launcher/Updater/UpdateType.cs b/Giants.Launcher/Updater/UpdateType.cs new file mode 100644 index 0000000..2dcaa98 --- /dev/null +++ b/Giants.Launcher/Updater/UpdateType.cs @@ -0,0 +1,8 @@ +namespace Giants.Launcher +{ + public enum UpdateType + { + Launcher, + Game, + } +} diff --git a/Giants.Launcher/Updater.cs b/Giants.Launcher/Updater/Updater.cs similarity index 81% rename from Giants.Launcher/Updater.cs rename to Giants.Launcher/Updater/Updater.cs index 679858a..eb13965 100644 --- a/Giants.Launcher/Updater.cs +++ b/Giants.Launcher/Updater/Updater.cs @@ -8,35 +8,6 @@ using System.Xml.Linq; namespace Giants.Launcher { - public enum UpdateType - { - Launcher, - Game, - } - - public class UpdateInfo - { - public Version VersionFrom { get; set; } - public Version VersionTo { get; set; } - public Uri DownloadUri - { - get - { - return _downloadUri; - } - set - { - _downloadUri = value; - FileName = Path.GetFileName(value.AbsoluteUri); - } - } - public int FileSize { get; set; } - public string FileName { get; set; } - public UpdateType UpdateType { get; set; } - - private Uri _downloadUri; - } - public class Updater { private readonly Uri updateUri; @@ -53,14 +24,14 @@ namespace Giants.Launcher { WebClient client = new WebClient(); - // Keep track of our progress callbacks - updateCompletedCallback = downloadCompleteCallback; - updateProgressCallback = downloadProgressCallback; + // Keep track of our progress callbacks + this.updateCompletedCallback = downloadCompleteCallback; + this.updateProgressCallback = downloadProgressCallback; // Download update info XML client.Proxy = null; - client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCallback); - client.DownloadDataAsync(updateUri); + client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadDataCallback); + client.DownloadDataAsync(this.updateUri); } private int GetHttpFileSize(Uri uri) @@ -109,7 +80,7 @@ namespace Giants.Launcher if (File.Exists(path)) File.Delete(path); - info.FileSize = GetHttpFileSize(info.DownloadUri); + info.FileSize = this.GetHttpFileSize(info.DownloadUri); if (info.FileSize == -1) { string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server."); @@ -124,8 +95,8 @@ namespace Giants.Launcher Proxy = null }; client.DownloadFileAsync(info.DownloadUri, path, info); - client.DownloadFileCompleted += updateCompletedCallback; - client.DownloadProgressChanged += updateProgressCallback; + client.DownloadFileCompleted += this.updateCompletedCallback; + client.DownloadProgressChanged += this.updateProgressCallback; } private void StartLauncherUpdate(XElement root) @@ -151,7 +122,7 @@ namespace Giants.Launcher if (File.Exists(path)) File.Delete(path); - info.FileSize = GetHttpFileSize(info.DownloadUri); + info.FileSize = this.GetHttpFileSize(info.DownloadUri); if (info.FileSize == -1) { string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server."); @@ -165,8 +136,8 @@ namespace Giants.Launcher Proxy = null }; client.DownloadFileAsync(info.DownloadUri, path, info); - client.DownloadFileCompleted += updateCompletedCallback; - client.DownloadProgressChanged += updateProgressCallback; + client.DownloadFileCompleted += this.updateCompletedCallback; + client.DownloadProgressChanged += this.updateProgressCallback; } private void DownloadDataCallback(Object sender, DownloadDataCompletedEventArgs e) @@ -186,11 +157,11 @@ namespace Giants.Launcher Version ourVersion = new Version(Application.ProductVersion); if (launcherVersion > ourVersion) { - StartLauncherUpdate(root); + this.StartLauncherUpdate(root); return; } - else if (gameVersion > appVersion) - StartGameUpdate(root, appVersion); + else if (gameVersion > this.appVersion) + this.StartGameUpdate(root, this.appVersion); } } diff --git a/Giants.Launcher/WindowType.cs b/Giants.Launcher/WindowType.cs new file mode 100644 index 0000000..520a004 --- /dev/null +++ b/Giants.Launcher/WindowType.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Giants.Launcher +{ + public enum WindowType + { + Fullscreen = 0, + Windowed = 1, + Borderless = 2, + } +} diff --git a/Giants.Services/Core/CacheKeys.cs b/Giants.Services/Core/CacheKeys.cs index a9d5a37..1b7832b 100644 --- a/Giants.Services/Core/CacheKeys.cs +++ b/Giants.Services/Core/CacheKeys.cs @@ -7,5 +7,6 @@ public static class CacheKeys { public const string ServerInfo = nameof(ServerInfo); + public const string VersionInfo = nameof(VersionInfo); } } diff --git a/Giants.Services/Core/Entities/IIdentifiable.cs b/Giants.Services/Core/Entities/IIdentifiable.cs index 13268d2..393b6cb 100644 --- a/Giants.Services/Core/Entities/IIdentifiable.cs +++ b/Giants.Services/Core/Entities/IIdentifiable.cs @@ -1,4 +1,4 @@ -namespace Giants.Services.Core.Entities +namespace Giants.Services { public interface IIdentifiable { diff --git a/Giants.Services/Core/Entities/ServerInfo.cs b/Giants.Services/Core/Entities/ServerInfo.cs index 6821545..08e2d92 100644 --- a/Giants.Services/Core/Entities/ServerInfo.cs +++ b/Giants.Services/Core/Entities/ServerInfo.cs @@ -1,33 +1,32 @@ namespace Giants.Services { using System; - using Giants.Services.Core.Entities; public class ServerInfo : DataContract.ServerInfo, IIdentifiable { - public string id => HostIpAddress; + public string id => this.HostIpAddress; + + public string DocumentType => nameof(ServerInfo); public string HostIpAddress { get; set; } public DateTime LastHeartbeat { get; set; } - public string DocumentType => nameof(ServerInfo); - public override bool Equals(object obj) { return obj is ServerInfo info && base.Equals(obj) && - HostIpAddress == info.HostIpAddress && - DocumentType == info.DocumentType; + this.HostIpAddress == info.HostIpAddress && + this.DocumentType == info.DocumentType; } public override int GetHashCode() { HashCode hash = new HashCode(); hash.Add(base.GetHashCode()); - hash.Add(id); - hash.Add(HostIpAddress); - hash.Add(DocumentType); + hash.Add(this.id); + hash.Add(this.HostIpAddress); + hash.Add(this.DocumentType); return hash.ToHashCode(); } } diff --git a/Giants.Services/Core/Entities/VersionInfo.cs b/Giants.Services/Core/Entities/VersionInfo.cs new file mode 100644 index 0000000..da2a378 --- /dev/null +++ b/Giants.Services/Core/Entities/VersionInfo.cs @@ -0,0 +1,13 @@ +using System; + +namespace Giants.Services +{ + public class VersionInfo : DataContract.VersionInfo, IIdentifiable + { + public string id => GenerateId(this.GameName); + + public string DocumentType => nameof(VersionInfo); + + public static string GenerateId(string gameName) => $"{nameof(VersionInfo)}-{gameName}"; + } +} diff --git a/Giants.Services/Core/ServicesModule.cs b/Giants.Services/Core/ServicesModule.cs index 7cfdc52..906221d 100644 --- a/Giants.Services/Core/ServicesModule.cs +++ b/Giants.Services/Core/ServicesModule.cs @@ -1,6 +1,7 @@ namespace Giants.Services { using Giants.Services.Core; + using Giants.Services.Store; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -13,6 +14,8 @@ services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); diff --git a/Giants.Services/Mapper/Mapper.cs b/Giants.Services/Mapper/Mapper.cs index 846f3a1..da35346 100644 --- a/Giants.Services/Mapper/Mapper.cs +++ b/Giants.Services/Mapper/Mapper.cs @@ -20,6 +20,7 @@ cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap(); + cfg.CreateMap(); }); Instance = new AutoMapper.Mapper(config); diff --git a/Giants.Services/Services/IUpdaterService.cs b/Giants.Services/Services/IUpdaterService.cs index 0903b45..d52fbce 100644 --- a/Giants.Services/Services/IUpdaterService.cs +++ b/Giants.Services/Services/IUpdaterService.cs @@ -1,10 +1,9 @@ namespace Giants.Services { - using System; - using System.Collections.Generic; - using System.Text; + using System.Threading.Tasks; public interface IUpdaterService { + Task GetVersionInfo(string gameName); } } diff --git a/Giants.Services/Services/InitializerService.cs b/Giants.Services/Services/InitializerService.cs index f774b19..d5a8914 100644 --- a/Giants.Services/Services/InitializerService.cs +++ b/Giants.Services/Services/InitializerService.cs @@ -6,16 +6,22 @@ public class InitializerService : IHostedService { + private readonly IUpdaterStore updaterStore; private readonly IServerRegistryStore serverRegistryStore; - public InitializerService(IServerRegistryStore serverRegistryStore) + public InitializerService( + IUpdaterStore updaterStore, + IServerRegistryStore serverRegistryStore) { + // TODO: Pick these up from reflection and auto initialize + this.updaterStore = updaterStore; this.serverRegistryStore = serverRegistryStore; } public async Task StartAsync(CancellationToken cancellationToken) { await this.serverRegistryStore.Initialize(); + await this.updaterStore.Initialize(); } public Task StopAsync(CancellationToken cancellationToken) diff --git a/Giants.Services/Services/ServerRegistryCleanupService.cs b/Giants.Services/Services/ServerRegistryCleanupService.cs index 997d7c7..cf7551c 100644 --- a/Giants.Services/Services/ServerRegistryCleanupService.cs +++ b/Giants.Services/Services/ServerRegistryCleanupService.cs @@ -36,7 +36,7 @@ public Task StartAsync(CancellationToken cancellationToken) { - this.timer = new Timer(TimerCallback, null, TimeSpan.Zero, this.cleanupInterval); + this.timer = new Timer(this.TimerCallback, null, TimeSpan.Zero, this.cleanupInterval); return Task.CompletedTask; } @@ -68,7 +68,7 @@ if (expiredServers.Any()) { - logger.LogInformation("Cleaning up {Count} servers.", expiredServers.Count); + this.logger.LogInformation("Cleaning up {Count} servers.", expiredServers.Count); await this.serverRegistryStore.DeleteServers(expiredServers); } diff --git a/Giants.Services/Services/ServerRegistryService.cs b/Giants.Services/Services/ServerRegistryService.cs index 5fa99bb..90f7d55 100644 --- a/Giants.Services/Services/ServerRegistryService.cs +++ b/Giants.Services/Services/ServerRegistryService.cs @@ -49,7 +49,7 @@ } // Check cache before we write to store - ConcurrentDictionary allServerInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, PopulateCache); + ConcurrentDictionary allServerInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, this.PopulateCache); if (allServerInfo.ContainsKey(serverInfo.HostIpAddress)) { @@ -80,7 +80,7 @@ public async Task> GetAllServers() { - ConcurrentDictionary serverInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, PopulateCache); + ConcurrentDictionary serverInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, this.PopulateCache); return serverInfo.Values; } diff --git a/Giants.Services/Services/UpdaterService.cs b/Giants.Services/Services/UpdaterService.cs index cee3a19..f9689b1 100644 --- a/Giants.Services/Services/UpdaterService.cs +++ b/Giants.Services/Services/UpdaterService.cs @@ -1,10 +1,8 @@ -namespace Giants.Services -{ - using System; - using System.Collections.Generic; - using System.Text; +using System.Threading.Tasks; - public class UpdaterService +namespace Giants.Services +{ + public class UpdaterService : IUpdaterService { private readonly IUpdaterStore updaterStore; @@ -12,5 +10,12 @@ { this.updaterStore = updaterStore; } + + public async Task GetVersionInfo(string gameName) + { + ArgumentUtility.CheckStringForNullOrEmpty(gameName, nameof(gameName)); + + return await this.updaterStore.GetVersionInfo(gameName); + } } } diff --git a/Giants.Services/Store/CosmosDbClient.cs b/Giants.Services/Store/CosmosDbClient.cs index 79f8087..7a340d6 100644 --- a/Giants.Services/Store/CosmosDbClient.cs +++ b/Giants.Services/Store/CosmosDbClient.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; - using Giants.Services.Core.Entities; using Microsoft.Azure.Cosmos; using Microsoft.Azure.Cosmos.Linq; @@ -129,11 +128,12 @@ public async Task Initialize(string partitionKeyPath = null) { + // TODO: Use static shared cosmos client this.client = new CosmosClient( this.connectionString, this.authKeyOrResourceToken); - var databaseResponse = await this.client.CreateDatabaseIfNotExistsAsync(databaseId); + var databaseResponse = await this.client.CreateDatabaseIfNotExistsAsync(this.databaseId); var containerResponse = await databaseResponse.Database.CreateContainerIfNotExistsAsync(new ContainerProperties() { Id = containerId, diff --git a/Giants.Services/Store/CosmosDbUpdaterStore.cs b/Giants.Services/Store/CosmosDbUpdaterStore.cs new file mode 100644 index 0000000..8c8d5e9 --- /dev/null +++ b/Giants.Services/Store/CosmosDbUpdaterStore.cs @@ -0,0 +1,58 @@ +namespace Giants.Services.Store +{ + using System; + using System.Threading.Tasks; + using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.Logging; + + public class CosmosDbUpdaterStore : IUpdaterStore + { + private readonly ILogger logger; + private readonly IMemoryCache memoryCache; + private readonly IConfiguration configuration; + private CosmosDbClient client; + + public CosmosDbUpdaterStore( + ILogger logger, + IMemoryCache memoryCache, + IConfiguration configuration) + { + this.logger = logger; + this.memoryCache = memoryCache; + this.configuration = configuration; + } + + public async Task GetVersionInfo(string gameName) + { + VersionInfo versionInfo = await this.memoryCache.GetOrCreateAsync( + key: GetCacheKey(gameName), + factory: async (entry) => + { + entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); + + return await this.client.GetItemById( + VersionInfo.GenerateId(gameName), + nameof(VersionInfo)); + }); + + return versionInfo; + } + + public async Task Initialize() + { + this.client = new CosmosDbClient( + connectionString: this.configuration["CosmosDbEndpoint"], + authKeyOrResourceToken: this.configuration["CosmosDbKey"], + databaseId: this.configuration["DatabaseId"], + containerId: this.configuration["ContainerId"]); + + await this.client.Initialize(); + } + + private static string GetCacheKey(string gameName) + { + return $"{CacheKeys.VersionInfo}-{gameName}"; + } + } +} diff --git a/Giants.Services/Store/FileUpdaterStore.cs b/Giants.Services/Store/FileUpdaterStore.cs index 4557c10..acc9284 100644 --- a/Giants.Services/Store/FileUpdaterStore.cs +++ b/Giants.Services/Store/FileUpdaterStore.cs @@ -1,10 +1,18 @@ namespace Giants.Services { using System; - using System.Collections.Generic; - using System.Text; + using System.Threading.Tasks; public class FileUpdaterStore : IUpdaterStore { + public Task GetVersionInfo(string gameName) + { + throw new NotImplementedException(); + } + + public Task Initialize() + { + throw new NotImplementedException(); + } } } diff --git a/Giants.Services/Store/IUpdaterStore.cs b/Giants.Services/Store/IUpdaterStore.cs index 8446d24..c87bfcf 100644 --- a/Giants.Services/Store/IUpdaterStore.cs +++ b/Giants.Services/Store/IUpdaterStore.cs @@ -1,10 +1,11 @@ namespace Giants.Services { - using System; - using System.Collections.Generic; - using System.Text; + using System.Threading.Tasks; public interface IUpdaterStore { + Task GetVersionInfo(string gameName); + + Task Initialize(); } } diff --git a/Giants.Services/Store/InMemoryServerRegistryStore.cs b/Giants.Services/Store/InMemoryServerRegistryStore.cs index b1f079b..a052f3c 100644 --- a/Giants.Services/Store/InMemoryServerRegistryStore.cs +++ b/Giants.Services/Store/InMemoryServerRegistryStore.cs @@ -14,9 +14,9 @@ public Task GetServerInfo(string ipAddress) { - if (servers.ContainsKey(ipAddress)) + if (this.servers.ContainsKey(ipAddress)) { - return Task.FromResult(servers[ipAddress]); + return Task.FromResult(this.servers[ipAddress]); } return Task.FromResult((ServerInfo)null); diff --git a/Giants.WebApi/Controllers/VersionController.cs b/Giants.WebApi/Controllers/VersionController.cs new file mode 100644 index 0000000..5da66d9 --- /dev/null +++ b/Giants.WebApi/Controllers/VersionController.cs @@ -0,0 +1,32 @@ +using System.Threading.Tasks; +using AutoMapper; +using Giants.DataContract; +using Giants.Services; +using Microsoft.AspNetCore.Mvc; + +namespace Giants.WebApi.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class VersionController : ControllerBase + { + private readonly IMapper mapper; + private readonly IUpdaterService updaterService; + + public VersionController( + IMapper mapper, + IUpdaterService updaterService) + { + this.mapper = mapper; + this.updaterService = updaterService; + } + + [HttpGet] + public async Task GetVersionInfo(string gameName) + { + Services.VersionInfo versionInfo = await this.updaterService.GetVersionInfo(gameName); + + return mapper.Map(versionInfo); + } + } +}