1
0
mirror of https://github.com/ncblakely/GiantsTools synced 2024-11-22 06:05:38 +01:00

Minor refactoring. Add Updater service.

This commit is contained in:
Nick Blakely 2020-08-10 00:22:33 -07:00
parent 7af4abb543
commit 998f06b238
34 changed files with 436 additions and 276 deletions

View File

@ -3,7 +3,7 @@
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
public class VersionInfo public class GiantsVersion
{ {
[Required] [Required]
public int Build { get; set; } public int Build { get; set; }
@ -19,7 +19,7 @@
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return obj is VersionInfo info && return obj is GiantsVersion info &&
Build == info.Build && Build == info.Build &&
Major == info.Major && Major == info.Major &&
Minor == info.Minor && Minor == info.Minor &&
@ -30,5 +30,10 @@
{ {
return HashCode.Combine(Build, Major, Minor, Revision); return HashCode.Combine(Build, Major, Minor, Revision);
} }
public Version ToVersion()
{
return new Version(this.Major, this.Minor, this.Build, this.Revision);
}
} }
} }

View File

@ -12,7 +12,7 @@
public string GameName { get; set; } public string GameName { get; set; }
[Required] [Required]
public VersionInfo Version { get; set; } public GiantsVersion Version { get; set; }
[Required] [Required]
[StringLength(100)] [StringLength(100)]
@ -55,7 +55,7 @@
{ {
return obj is ServerInfo info && return obj is ServerInfo info &&
GameName == info.GameName && GameName == info.GameName &&
EqualityComparer<VersionInfo>.Default.Equals(Version, info.Version) && EqualityComparer<GiantsVersion>.Default.Equals(Version, info.Version) &&
SessionName == info.SessionName && SessionName == info.SessionName &&
Port == info.Port && Port == info.Port &&
MapName == info.MapName && MapName == info.MapName &&

View File

@ -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; }
}
}

View File

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32; using Microsoft.Win32;
namespace Giants.Launcher namespace Giants.Launcher

View File

@ -1,9 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO; using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32; using Microsoft.Win32;
namespace Giants.Launcher namespace Giants.Launcher
@ -14,15 +13,15 @@ namespace Giants.Launcher
private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants"; private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants";
private const int OPTIONS_VERSION = 3; private const int OPTIONS_VERSION = 3;
private static readonly Dictionary<string, object> _Settings = new Dictionary<string, object>(); private static readonly Dictionary<string, object> Settings = new Dictionary<string, object>();
// List of renderers compatible with the user's system. // List of renderers compatible with the user's system.
static public List<RendererInterop.Capabilities> CompatibleRenderers; static public List<RendererInterop.Capabilities> CompatibleRenderers;
public static object Get(string settingName) public static object Get(string settingName)
{ {
if (_Settings.ContainsKey(settingName)) if (Settings.ContainsKey(settingName))
return _Settings[settingName]; return Settings[settingName];
else else
return 0; return 0;
@ -30,23 +29,23 @@ namespace Giants.Launcher
public static void Modify(string settingName, object settingValue) public static void Modify(string settingName, object settingValue)
{ {
_Settings[settingName] = settingValue; Settings[settingName] = settingValue;
} }
public static void SetDefaults(string gamePath) public static void SetDefaults(string gamePath)
{ {
// Set default settings: // Set default settings:
_Settings["Renderer"] = "gg_dx7r.dll"; Settings["Renderer"] = "gg_dx7r.dll";
_Settings["Antialiasing"] = 0; Settings["Antialiasing"] = 0;
_Settings["AnisotropicFiltering"] = 0; Settings["AnisotropicFiltering"] = 0;
_Settings["VideoWidth"] = 640; Settings["VideoWidth"] = 640;
_Settings["VideoHeight"] = 480; Settings["VideoHeight"] = 480;
_Settings["VideoDepth"] = 32; Settings["VideoDepth"] = 32;
_Settings["Windowed"] = 0; Settings["Windowed"] = 0;
_Settings["BorderlessWindow"] = 0; Settings["BorderlessWindow"] = 0;
_Settings["VerticalSync"] = 1; Settings["VerticalSync"] = 1;
_Settings["TripleBuffering"] = 1; Settings["TripleBuffering"] = 1;
_Settings["NoAutoUpdate"] = 0; Settings["NoAutoUpdate"] = 0;
// Get a list of renderers compatible with the user's system // Get a list of renderers compatible with the user's system
if (CompatibleRenderers == null) if (CompatibleRenderers == null)
@ -61,11 +60,11 @@ namespace Giants.Launcher
// Select the highest priority renderer // Select the highest priority renderer
if (CompatibleRenderers.Count > 0) 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: // Set the current desktop resolution, leaving bit depth at the default 32:
_Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width; Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width;
_Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height; Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height;
} }
public static void Load(string gamePath) public static void Load(string gamePath)
@ -76,18 +75,18 @@ namespace Giants.Launcher
{ {
try 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); //System.Diagnostics.Debug.Assert(_Settings["Renderer"] is string);
_Settings["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", _Settings["Antialiasing"], 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["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], typeof(int));
_Settings["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", _Settings["VideoWidth"], 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["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], typeof(int));
_Settings["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", _Settings["VideoDepth"], 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["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], typeof(int));
_Settings["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", _Settings["BorderlessWindow"], 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["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], typeof(int));
_Settings["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", _Settings["TripleBuffering"], 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["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -101,17 +100,17 @@ namespace Giants.Launcher
try try
{ {
Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Renderer", _Settings["Renderer"], RegistryValueKind.String); Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String);
Registry.SetValue(REGISTRY_KEY, "Antialiasing", _Settings["Antialiasing"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", _Settings["AnisotropicFiltering"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoWidth", _Settings["VideoWidth"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoHeight", _Settings["VideoHeight"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoDepth", _Settings["VideoDepth"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Windowed", _Settings["Windowed"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", _Settings["BorderlessWindow"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VerticalSync", _Settings["VerticalSync"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "TripleBuffering", _Settings["TripleBuffering"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", _Settings["NoAutoUpdate"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord);
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -72,7 +72,7 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Common.cs" /> <Compile Include="WindowType.cs" />
<Compile Include="GameSettings.cs" /> <Compile Include="GameSettings.cs" />
<Compile Include="ImageButton.cs"> <Compile Include="ImageButton.cs">
<SubType>Component</SubType> <SubType>Component</SubType>
@ -95,6 +95,9 @@
</Compile> </Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ScreenResolution.cs" />
<Compile Include="Updater\UpdateInfo.cs" />
<Compile Include="Updater\UpdateType.cs" />
<EmbeddedResource Include="LauncherForm.resx"> <EmbeddedResource Include="LauncherForm.resx">
<DependentUpon>LauncherForm.cs</DependentUpon> <DependentUpon>LauncherForm.cs</DependentUpon>
<CustomToolNamespace>Giants.Launcher</CustomToolNamespace> <CustomToolNamespace>Giants.Launcher</CustomToolNamespace>
@ -114,7 +117,7 @@
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
</Compile> </Compile>
<Compile Include="Extensions.cs" /> <Compile Include="Extensions.cs" />
<Compile Include="Updater.cs" /> <Compile Include="Updater\Updater.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="Resources\LauncherStart.wav" /> <None Include="Resources\LauncherStart.wav" />

View File

@ -17,17 +17,17 @@ namespace Giants.Launcher
{ {
get get
{ {
return m_DialogResult; return this.m_DialogResult;
} }
set set
{ {
m_DialogResult = value; this.m_DialogResult = value;
} }
} }
public void NotifyDefault(bool value) public void NotifyDefault(bool value)
{ {
isDefault = value; this.isDefault = value;
} }
public void PerformClick() public void PerformClick()
@ -44,8 +44,8 @@ namespace Giants.Launcher
[Description("Image to show when the button is hovered over.")] [Description("Image to show when the button is hovered over.")]
public Image HoverImage public Image HoverImage
{ {
get { return m_HoverImage; } get { return this.m_HoverImage; }
set { m_HoverImage = value; if (hover) Image = value; } set { this.m_HoverImage = value; if (this.hover) this.Image = value; }
} }
#endregion #endregion
#region DownImage #region DownImage
@ -55,8 +55,8 @@ namespace Giants.Launcher
[Description("Image to show when the button is depressed.")] [Description("Image to show when the button is depressed.")]
public Image DownImage public Image DownImage
{ {
get { return m_DownImage; } get { return this.m_DownImage; }
set { m_DownImage = value; if (down) Image = value; } set { this.m_DownImage = value; if (this.down) this.Image = value; }
} }
#endregion #endregion
#region NormalImage #region NormalImage
@ -66,8 +66,8 @@ namespace Giants.Launcher
[Description("Image to show when the button is not in any other state.")] [Description("Image to show when the button is not in any other state.")]
public Image NormalImage public Image NormalImage
{ {
get { return m_NormalImage; } get { return this.m_NormalImage; }
set { m_NormalImage = value; if (!(hover || down)) Image = value; } set { this.m_NormalImage = value; if (!(this.hover || this.down)) this.Image = value; }
} }
#endregion #endregion
@ -155,60 +155,60 @@ namespace Giants.Launcher
#region Events #region Events
protected override void OnMouseMove(MouseEventArgs e) protected override void OnMouseMove(MouseEventArgs e)
{ {
hover = true; this.hover = true;
if (down) if (this.down)
{ {
if ((m_DownImage != null) && (Image != m_DownImage)) if ((this.m_DownImage != null) && (this.Image != this.m_DownImage))
Image = m_DownImage; this.Image = this.m_DownImage;
} }
else else
if (m_HoverImage != null) if (this.m_HoverImage != null)
Image = m_HoverImage; this.Image = this.m_HoverImage;
else else
Image = m_NormalImage; this.Image = this.m_NormalImage;
base.OnMouseMove(e); base.OnMouseMove(e);
} }
protected override void OnMouseLeave(EventArgs e) protected override void OnMouseLeave(EventArgs e)
{ {
hover = false; this.hover = false;
Image = m_NormalImage; this.Image = this.m_NormalImage;
base.OnMouseLeave(e); base.OnMouseLeave(e);
} }
protected override void OnMouseDown(MouseEventArgs e) protected override void OnMouseDown(MouseEventArgs e)
{ {
base.Focus(); base.Focus();
OnMouseUp(null); this.OnMouseUp(null);
down = true; this.down = true;
if (m_DownImage != null) if (this.m_DownImage != null)
Image = m_DownImage; this.Image = this.m_DownImage;
base.OnMouseDown(e); base.OnMouseDown(e);
} }
protected override void OnMouseUp(MouseEventArgs e) protected override void OnMouseUp(MouseEventArgs e)
{ {
down = false; this.down = false;
if (hover) if (this.hover)
{ {
if (m_HoverImage != null) if (this.m_HoverImage != null)
Image = m_HoverImage; this.Image = this.m_HoverImage;
} }
else else
Image = m_NormalImage; this.Image = this.m_NormalImage;
base.OnMouseUp(e); base.OnMouseUp(e);
} }
protected override void OnLostFocus(EventArgs e) protected override void OnLostFocus(EventArgs e)
{ {
OnMouseUp(null); this.OnMouseUp(null);
base.OnLostFocus(e); base.OnLostFocus(e);
} }
protected override void OnPaint(PaintEventArgs pe) protected override void OnPaint(PaintEventArgs pe)
{ {
base.OnPaint(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); SolidBrush drawBrush = new SolidBrush(base.ForeColor);
SizeF drawStringSize = pe.Graphics.MeasureString(base.Text, base.Font); SizeF drawStringSize = pe.Graphics.MeasureString(base.Text, base.Font);
@ -223,7 +223,7 @@ namespace Giants.Launcher
protected override void OnTextChanged(EventArgs e) protected override void OnTextChanged(EventArgs e)
{ {
Refresh(); this.Refresh();
base.OnTextChanged(e); base.OnTextChanged(e);
} }
#endregion #endregion

View File

@ -24,7 +24,7 @@ namespace Giants.Launcher
public LauncherForm() public LauncherForm()
{ {
InitializeComponent(); this.InitializeComponent();
// Set window title // Set window title
this.Text = GAME_NAME; this.Text = GAME_NAME;
@ -40,31 +40,31 @@ namespace Giants.Launcher
GameSettings.Save(); GameSettings.Save();
foreach (string c in Environment.GetCommandLineArgs()) 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 try
{ {
Process gameProcess = new Process(); Process gameProcess = new Process();
gameProcess.StartInfo.Arguments = commandLine; gameProcess.StartInfo.Arguments = commandLine;
gameProcess.StartInfo.FileName = _gamePath; gameProcess.StartInfo.FileName = this._gamePath;
gameProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(_gamePath); gameProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(this._gamePath);
gameProcess.Start(); gameProcess.Start();
Application.Exit(); Application.Exit();
} }
catch(Exception ex) 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); "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void btnOptions_Click(object sender, EventArgs e) 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.MdiParent = this;
form.ShowDialog(); form.ShowDialog();
@ -74,14 +74,14 @@ namespace Giants.Launcher
{ {
// Find the game executable, first looking for it relative to our current directory and then // Find the game executable, first looking for it relative to our current directory and then
// using the registry path if that fails. // using the registry path if that fails.
_gamePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + GAME_PATH; this._gamePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + GAME_PATH;
if (!File.Exists(_gamePath)) if (!File.Exists(this._gamePath))
{ {
_gamePath = (string)Registry.GetValue(REGISTRY_KEY, REGISTRY_VALUE, null); this._gamePath = (string)Registry.GetValue(REGISTRY_KEY, REGISTRY_VALUE, null);
if (_gamePath != null) if (this._gamePath != null)
_gamePath = Path.Combine(_gamePath, GAME_PATH); 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); string message = string.Format(Resources.AppNotFound, GAME_NAME);
MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -94,7 +94,7 @@ namespace Giants.Launcher
try try
{ {
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(_gamePath); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(this._gamePath);
gameVersion = new Version(fvi.FileVersion.Replace(',', '.')); gameVersion = new Version(fvi.FileVersion.Replace(',', '.'));
} }
finally finally
@ -108,13 +108,13 @@ namespace Giants.Launcher
} }
// Read game settings from registry // Read game settings from registry
GameSettings.Load(_gamePath); GameSettings.Load(this._gamePath);
if ((int)GameSettings.Get("NoAutoUpdate") == 0) if ((int)GameSettings.Get("NoAutoUpdate") == 0)
{ {
// Check for updates // Check for updates
_Updater = new Updater(new Uri(UPDATE_URL), gameVersion); this._Updater = new Updater(new Uri(UPDATE_URL), gameVersion);
_Updater.DownloadUpdateInfo(LauncherForm_DownloadCompletedCallback, LauncherForm_DownloadProgressCallback); this._Updater.DownloadUpdateInfo(this.LauncherForm_DownloadCompletedCallback, this.LauncherForm_DownloadProgressCallback);
} }
} }
@ -124,16 +124,16 @@ namespace Giants.Launcher
if (e.Button == MouseButtons.Left) if (e.Button == MouseButtons.Left)
{ {
NativeMethods.ReleaseCapture(); 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) private void LauncherForm_Shown(object sender, EventArgs e)
{ {
btnOptions.Visible = true; this.btnOptions.Visible = true;
btnPlay.Visible = true; this.btnPlay.Visible = true;
btnExit.Visible = true; this.btnExit.Visible = true;
// Play intro sound // Play intro sound
SoundPlayer player = new SoundPlayer(Resources.LauncherStart); SoundPlayer player = new SoundPlayer(Resources.LauncherStart);
@ -145,9 +145,9 @@ namespace Giants.Launcher
if (e.Cancelled) if (e.Cancelled)
return; return;
updateProgressBar.Value = 0; this.updateProgressBar.Value = 0;
updateProgressBar.Visible = false; this.updateProgressBar.Visible = false;
txtProgress.Visible = false; this.txtProgress.Visible = false;
if (e.Error != null) if (e.Error != null)
{ {
@ -187,13 +187,13 @@ namespace Giants.Launcher
private void LauncherForm_DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) private void LauncherForm_DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{ {
updateProgressBar.Visible = true; this.updateProgressBar.Visible = true;
updateProgressBar.Value = e.ProgressPercentage; this.updateProgressBar.Value = e.ProgressPercentage;
UpdateInfo info = (UpdateInfo)e.UserState; UpdateInfo info = (UpdateInfo)e.UserState;
txtProgress.Visible = true; this.txtProgress.Visible = true;
txtProgress.Text = string.Format(Resources.DownloadProgress, e.ProgressPercentage, (info.FileSize / 1024) / 1024); this.txtProgress.Text = string.Format(Resources.DownloadProgress, e.ProgressPercentage, (info.FileSize / 1024) / 1024);
} }
} }
} }

View File

@ -104,17 +104,17 @@ namespace Giants.Launcher
public Capabilities(string filePath, ref RendererInterop.GFXCapabilityInfo gfxCaps) public Capabilities(string filePath, ref RendererInterop.GFXCapabilityInfo gfxCaps)
{ {
FilePath = filePath; this.FilePath = filePath;
FileName = Path.GetFileName(filePath); this.FileName = Path.GetFileName(filePath);
MaxAnisotropy = gfxCaps.maxAnisotropy; this.MaxAnisotropy = gfxCaps.maxAnisotropy;
Flags = (RendererFlag)gfxCaps.flags; this.Flags = (RendererFlag)gfxCaps.flags;
Priority = gfxCaps.priority; this.Priority = gfxCaps.priority;
Name = gfxCaps.rendererName; this.Name = gfxCaps.rendererName;
} }
public override string ToString() 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) public int CompareTo(object obj)

View File

@ -11,7 +11,7 @@ namespace Giants.Launcher
public OptionsForm(string title, string gamePath) public OptionsForm(string title, string gamePath)
{ {
InitializeComponent(); this.InitializeComponent();
this.Text = title; this.Text = title;
this.gamePath = gamePath; this.gamePath = gamePath;
@ -19,40 +19,40 @@ namespace Giants.Launcher
private void OptionsForm_Load(object sender, EventArgs e) private void OptionsForm_Load(object sender, EventArgs e)
{ {
PopulateResolution(); this.PopulateResolution();
SetOptions(); this.SetOptions();
} }
private void SetOptions() private void SetOptions()
{ {
cmbRenderer.Items.Clear(); this.cmbRenderer.Items.Clear();
cmbRenderer.Items.AddRange(GameSettings.CompatibleRenderers.ToArray()); 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); RendererInterop.Capabilities renderer = GameSettings.CompatibleRenderers.Find(r => StringComparer.OrdinalIgnoreCase.Compare(Path.GetFileName(r.FilePath), GameSettings.Get("Renderer")) == 0);
if (renderer != null) if (renderer != null)
cmbRenderer.SelectedItem = renderer; this.cmbRenderer.SelectedItem = renderer;
else else
{ {
renderer = GameSettings.CompatibleRenderers.Find(r => r.Name == "DirectX 7"); renderer = GameSettings.CompatibleRenderers.Find(r => r.Name == "DirectX 7");
cmbRenderer.SelectedItem = renderer; this.cmbRenderer.SelectedItem = renderer;
} }
var Resolutions = (List<ScreenResolution>)cmbResolution.DataSource; var Resolutions = (List<ScreenResolution>)this.cmbResolution.DataSource;
cmbResolution.SelectedItem = Resolutions.Find(r => r.Width == (int)GameSettings.Get("VideoWidth") && r.Height == (int)GameSettings.Get("VideoHeight")); this.cmbResolution.SelectedItem = Resolutions.Find(r => r.Width == (int)GameSettings.Get("VideoWidth") && r.Height == (int)GameSettings.Get("VideoHeight"));
if (cmbResolution.SelectedItem == null) if (this.cmbResolution.SelectedItem == null)
cmbResolution.SelectedIndex = 0; this.cmbResolution.SelectedIndex = 0;
var AntialiasingOptions = (List<KeyValuePair<string, int>>)cmbAntialiasing.DataSource; var AntialiasingOptions = (List<KeyValuePair<string, int>>)this.cmbAntialiasing.DataSource;
cmbAntialiasing.SelectedItem = AntialiasingOptions.Find(o => o.Value == (int)GameSettings.Get("Antialiasing")); this.cmbAntialiasing.SelectedItem = AntialiasingOptions.Find(o => o.Value == (int)GameSettings.Get("Antialiasing"));
if (cmbAntialiasing.SelectedItem == null) if (this.cmbAntialiasing.SelectedItem == null)
cmbAntialiasing.SelectedIndex = 0; this.cmbAntialiasing.SelectedIndex = 0;
var AnisotropyOptions = (List<KeyValuePair<string, int>>)cmbAnisotropy.DataSource; var AnisotropyOptions = (List<KeyValuePair<string, int>>)this.cmbAnisotropy.DataSource;
cmbAnisotropy.SelectedItem = AnisotropyOptions.Find(o => o.Value == (int)GameSettings.Get("AnisotropicFiltering")); this.cmbAnisotropy.SelectedItem = AnisotropyOptions.Find(o => o.Value == (int)GameSettings.Get("AnisotropicFiltering"));
if (cmbAnisotropy.SelectedItem == null) if (this.cmbAnisotropy.SelectedItem == null)
cmbAnisotropy.SelectedIndex = 0; 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() private void PopulateAntialiasing()
@ -61,7 +61,7 @@ namespace Giants.Launcher
AntialiasingOptions.Add(new KeyValuePair<string, int>("None (Best performance)", 0)); AntialiasingOptions.Add(new KeyValuePair<string, int>("None (Best performance)", 0));
var renderer = (RendererInterop.Capabilities)cmbRenderer.SelectedItem; var renderer = (RendererInterop.Capabilities)this.cmbRenderer.SelectedItem;
if (renderer != null) if (renderer != null)
{ {
if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.MSAA2x) == RendererInterop.Capabilities.RendererFlag.MSAA2x) 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 // Try to keep current selection when repopulating
int? currentValue = null; int? currentValue = null;
if (cmbAntialiasing.SelectedValue != null) if (this.cmbAntialiasing.SelectedValue != null)
{ {
currentValue = (int)cmbAntialiasing.SelectedValue; currentValue = (int)this.cmbAntialiasing.SelectedValue;
} }
cmbAntialiasing.DataSource = AntialiasingOptions; this.cmbAntialiasing.DataSource = AntialiasingOptions;
cmbAntialiasing.DisplayMember = "Key"; this.cmbAntialiasing.DisplayMember = "Key";
cmbAntialiasing.ValueMember = "Value"; this.cmbAntialiasing.ValueMember = "Value";
if (currentValue != null) if (currentValue != null)
cmbAntialiasing.SelectedValue = currentValue; this.cmbAntialiasing.SelectedValue = currentValue;
if (cmbAntialiasing.SelectedValue == null) if (this.cmbAntialiasing.SelectedValue == null)
cmbAntialiasing.SelectedIndex = 0; this.cmbAntialiasing.SelectedIndex = 0;
} }
private bool IsPowerOfTwo(int x) private bool IsPowerOfTwo(int x)
@ -103,12 +103,12 @@ namespace Giants.Launcher
AnisotropyOptions.Add(new KeyValuePair<string, int>("None (Best performance)", 0)); AnisotropyOptions.Add(new KeyValuePair<string, int>("None (Best performance)", 0));
var renderer = (RendererInterop.Capabilities)cmbRenderer.SelectedItem; var renderer = (RendererInterop.Capabilities)this.cmbRenderer.SelectedItem;
if (renderer != null) if (renderer != null)
{ {
for (int i = 2; i <= renderer.MaxAnisotropy; i++) for (int i = 2; i <= renderer.MaxAnisotropy; i++)
{ {
if (!IsPowerOfTwo(i)) continue; if (!this.IsPowerOfTwo(i)) continue;
AnisotropyOptions.Add(new KeyValuePair<string,int>(String.Format("{0} Samples", i), i)); AnisotropyOptions.Add(new KeyValuePair<string,int>(String.Format("{0} Samples", i), i));
} }
@ -116,20 +116,20 @@ namespace Giants.Launcher
// Try to keep current selection when repopulating // Try to keep current selection when repopulating
int? currentValue = null; int? currentValue = null;
if (cmbAnisotropy.SelectedValue != null) if (this.cmbAnisotropy.SelectedValue != null)
{ {
currentValue = (int)cmbAnisotropy.SelectedValue; currentValue = (int)this.cmbAnisotropy.SelectedValue;
} }
cmbAnisotropy.DataSource = AnisotropyOptions; this.cmbAnisotropy.DataSource = AnisotropyOptions;
cmbAnisotropy.DisplayMember = "Key"; this.cmbAnisotropy.DisplayMember = "Key";
cmbAnisotropy.ValueMember = "Value"; this.cmbAnisotropy.ValueMember = "Value";
if (currentValue != null) if (currentValue != null)
cmbAnisotropy.SelectedValue = currentValue; this.cmbAnisotropy.SelectedValue = currentValue;
if (cmbAnisotropy.SelectedValue == null) if (this.cmbAnisotropy.SelectedValue == null)
cmbAnisotropy.SelectedIndex = 0; this.cmbAnisotropy.SelectedIndex = 0;
} }
private void PopulateResolution() private void PopulateResolution()
@ -149,75 +149,75 @@ namespace Giants.Launcher
} }
resolutions.Sort(); resolutions.Sort();
cmbResolution.DataSource = resolutions; this.cmbResolution.DataSource = resolutions;
} }
private void cmbRenderer_SelectedIndexChanged(object sender, EventArgs e) private void cmbRenderer_SelectedIndexChanged(object sender, EventArgs e)
{ {
PopulateAntialiasing(); this.PopulateAntialiasing();
PopulateAnisotropy(); this.PopulateAnisotropy();
bool windowed = ((int)GameSettings.Get("Windowed") == 1 ? true : false); bool windowed = ((int)GameSettings.Get("Windowed") == 1 ? true : false);
if (windowed) if (windowed)
{ {
bool borderless = (int)GameSettings.Get("BorderlessWindow") == 1 ? true : false; bool borderless = (int)GameSettings.Get("BorderlessWindow") == 1 ? true : false;
if (borderless) if (borderless)
cmbMode.SelectedIndex = 2; this.cmbMode.SelectedIndex = 2;
else else
cmbMode.SelectedIndex = 1; this.cmbMode.SelectedIndex = 1;
} }
else 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) if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.VSync) != RendererInterop.Capabilities.RendererFlag.VSync)
{ {
chkVSync.Checked = false; this.chkVSync.Checked = false;
chkVSync.Enabled = false; this.chkVSync.Enabled = false;
} }
else else
{ {
chkVSync.Checked = ((int)GameSettings.Get("VerticalSync") == 1 ? true : false); this.chkVSync.Checked = ((int)GameSettings.Get("VerticalSync") == 1 ? true : false);
chkVSync.Enabled = true; this.chkVSync.Enabled = true;
} }
if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.TripleBuffer) != RendererInterop.Capabilities.RendererFlag.TripleBuffer) if ((renderer.Flags & RendererInterop.Capabilities.RendererFlag.TripleBuffer) != RendererInterop.Capabilities.RendererFlag.TripleBuffer)
{ {
chkTripleBuffering.Checked = false; this.chkTripleBuffering.Checked = false;
chkTripleBuffering.Enabled = false; this.chkTripleBuffering.Enabled = false;
} }
else else
{ {
chkTripleBuffering.Checked = ((int)GameSettings.Get("TripleBuffering") == 1 ? true : false); this.chkTripleBuffering.Checked = ((int)GameSettings.Get("TripleBuffering") == 1 ? true : false);
chkTripleBuffering.Enabled = true; this.chkTripleBuffering.Enabled = true;
} }
} }
private void btnOK_Click(object sender, EventArgs e) 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) if (renderer != null)
{ {
GameSettings.Modify("Renderer", renderer.FileName); GameSettings.Modify("Renderer", renderer.FileName);
} }
var resolution = (ScreenResolution)cmbResolution.SelectedItem; var resolution = (ScreenResolution)this.cmbResolution.SelectedItem;
if (resolution != null) if (resolution != null)
{ {
GameSettings.Modify("VideoWidth", resolution.Width); GameSettings.Modify("VideoWidth", resolution.Width);
GameSettings.Modify("VideoHeight", resolution.Height); GameSettings.Modify("VideoHeight", resolution.Height);
} }
GameSettings.Modify("Antialiasing", cmbAntialiasing.SelectedValue); GameSettings.Modify("Antialiasing", this.cmbAntialiasing.SelectedValue);
GameSettings.Modify("AnisotropicFiltering", cmbAnisotropy.SelectedValue); GameSettings.Modify("AnisotropicFiltering", this.cmbAnisotropy.SelectedValue);
bool windowed = ((WindowType)cmbMode.SelectedIndex == WindowType.Windowed || (WindowType)cmbMode.SelectedIndex == WindowType.Borderless); bool windowed = ((WindowType)this.cmbMode.SelectedIndex == WindowType.Windowed || (WindowType)this.cmbMode.SelectedIndex == WindowType.Borderless);
GameSettings.Modify("Windowed", (windowed == true ? 1 : 0)); 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("BorderlessWindow", borderless == true ? 1 : 0);
GameSettings.Modify("VerticalSync", (chkVSync.Checked == true ? 1 : 0)); GameSettings.Modify("VerticalSync", (this.chkVSync.Checked == true ? 1 : 0));
GameSettings.Modify("TripleBuffering", (chkTripleBuffering.Checked == true ? 1 : 0)); GameSettings.Modify("TripleBuffering", (this.chkTripleBuffering.Checked == true ? 1 : 0));
GameSettings.Modify("NoAutoUpdate", (chkUpdates.Checked == false ? 1 : 0)); GameSettings.Modify("NoAutoUpdate", (this.chkUpdates.Checked == false ? 1 : 0));
GameSettings.Save(); GameSettings.Save();
@ -227,13 +227,13 @@ namespace Giants.Launcher
private void btnCancel_Click(object sender, EventArgs e) private void btnCancel_Click(object sender, EventArgs e)
{ {
this.Close(); this.Close();
GameSettings.Load(gamePath); GameSettings.Load(this.gamePath);
} }
private void btnResetDefaults_Click(object sender, EventArgs e) private void btnResetDefaults_Click(object sender, EventArgs e)
{ {
GameSettings.SetDefaults(gamePath); GameSettings.SetDefaults(this.gamePath);
SetOptions(); this.SetOptions();
} }
} }
} }

View File

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Giants.Launcher namespace Giants.Launcher
{ {
@ -12,8 +9,8 @@ namespace Giants.Launcher
public ScreenResolution(int width, int height) public ScreenResolution(int width, int height)
{ {
Width = width; this.Width = width;
Height = height; this.Height = height;
} }
public int CompareTo(object obj) public int CompareTo(object obj)
@ -34,15 +31,8 @@ namespace Giants.Launcher
public override string ToString() 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,
}
} }

View File

@ -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;
}
}

View File

@ -0,0 +1,8 @@
namespace Giants.Launcher
{
public enum UpdateType
{
Launcher,
Game,
}
}

View File

@ -8,35 +8,6 @@ using System.Xml.Linq;
namespace Giants.Launcher 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 public class Updater
{ {
private readonly Uri updateUri; private readonly Uri updateUri;
@ -54,13 +25,13 @@ namespace Giants.Launcher
WebClient client = new WebClient(); WebClient client = new WebClient();
// Keep track of our progress callbacks // Keep track of our progress callbacks
updateCompletedCallback = downloadCompleteCallback; this.updateCompletedCallback = downloadCompleteCallback;
updateProgressCallback = downloadProgressCallback; this.updateProgressCallback = downloadProgressCallback;
// Download update info XML // Download update info XML
client.Proxy = null; client.Proxy = null;
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCallback); client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadDataCallback);
client.DownloadDataAsync(updateUri); client.DownloadDataAsync(this.updateUri);
} }
private int GetHttpFileSize(Uri uri) private int GetHttpFileSize(Uri uri)
@ -109,7 +80,7 @@ namespace Giants.Launcher
if (File.Exists(path)) if (File.Exists(path))
File.Delete(path); File.Delete(path);
info.FileSize = GetHttpFileSize(info.DownloadUri); info.FileSize = this.GetHttpFileSize(info.DownloadUri);
if (info.FileSize == -1) if (info.FileSize == -1)
{ {
string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server."); string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server.");
@ -124,8 +95,8 @@ namespace Giants.Launcher
Proxy = null Proxy = null
}; };
client.DownloadFileAsync(info.DownloadUri, path, info); client.DownloadFileAsync(info.DownloadUri, path, info);
client.DownloadFileCompleted += updateCompletedCallback; client.DownloadFileCompleted += this.updateCompletedCallback;
client.DownloadProgressChanged += updateProgressCallback; client.DownloadProgressChanged += this.updateProgressCallback;
} }
private void StartLauncherUpdate(XElement root) private void StartLauncherUpdate(XElement root)
@ -151,7 +122,7 @@ namespace Giants.Launcher
if (File.Exists(path)) if (File.Exists(path))
File.Delete(path); File.Delete(path);
info.FileSize = GetHttpFileSize(info.DownloadUri); info.FileSize = this.GetHttpFileSize(info.DownloadUri);
if (info.FileSize == -1) if (info.FileSize == -1)
{ {
string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server."); string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server.");
@ -165,8 +136,8 @@ namespace Giants.Launcher
Proxy = null Proxy = null
}; };
client.DownloadFileAsync(info.DownloadUri, path, info); client.DownloadFileAsync(info.DownloadUri, path, info);
client.DownloadFileCompleted += updateCompletedCallback; client.DownloadFileCompleted += this.updateCompletedCallback;
client.DownloadProgressChanged += updateProgressCallback; client.DownloadProgressChanged += this.updateProgressCallback;
} }
private void DownloadDataCallback(Object sender, DownloadDataCompletedEventArgs e) private void DownloadDataCallback(Object sender, DownloadDataCompletedEventArgs e)
@ -186,11 +157,11 @@ namespace Giants.Launcher
Version ourVersion = new Version(Application.ProductVersion); Version ourVersion = new Version(Application.ProductVersion);
if (launcherVersion > ourVersion) if (launcherVersion > ourVersion)
{ {
StartLauncherUpdate(root); this.StartLauncherUpdate(root);
return; return;
} }
else if (gameVersion > appVersion) else if (gameVersion > this.appVersion)
StartGameUpdate(root, appVersion); this.StartGameUpdate(root, this.appVersion);
} }
} }

View File

@ -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,
}
}

View File

@ -7,5 +7,6 @@
public static class CacheKeys public static class CacheKeys
{ {
public const string ServerInfo = nameof(ServerInfo); public const string ServerInfo = nameof(ServerInfo);
public const string VersionInfo = nameof(VersionInfo);
} }
} }

View File

@ -1,4 +1,4 @@
namespace Giants.Services.Core.Entities namespace Giants.Services
{ {
public interface IIdentifiable public interface IIdentifiable
{ {

View File

@ -1,33 +1,32 @@
namespace Giants.Services namespace Giants.Services
{ {
using System; using System;
using Giants.Services.Core.Entities;
public class ServerInfo : DataContract.ServerInfo, IIdentifiable 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 string HostIpAddress { get; set; }
public DateTime LastHeartbeat { get; set; } public DateTime LastHeartbeat { get; set; }
public string DocumentType => nameof(ServerInfo);
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return obj is ServerInfo info && return obj is ServerInfo info &&
base.Equals(obj) && base.Equals(obj) &&
HostIpAddress == info.HostIpAddress && this.HostIpAddress == info.HostIpAddress &&
DocumentType == info.DocumentType; this.DocumentType == info.DocumentType;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
HashCode hash = new HashCode(); HashCode hash = new HashCode();
hash.Add(base.GetHashCode()); hash.Add(base.GetHashCode());
hash.Add(id); hash.Add(this.id);
hash.Add(HostIpAddress); hash.Add(this.HostIpAddress);
hash.Add(DocumentType); hash.Add(this.DocumentType);
return hash.ToHashCode(); return hash.ToHashCode();
} }
} }

View File

@ -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}";
}
}

View File

@ -1,6 +1,7 @@
namespace Giants.Services namespace Giants.Services
{ {
using Giants.Services.Core; using Giants.Services.Core;
using Giants.Services.Store;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -13,6 +14,8 @@
services.AddSingleton<IServerRegistryStore, CosmosDbServerRegistryStore>(); services.AddSingleton<IServerRegistryStore, CosmosDbServerRegistryStore>();
services.AddSingleton<IDateTimeProvider, DefaultDateTimeProvider>(); services.AddSingleton<IDateTimeProvider, DefaultDateTimeProvider>();
services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddSingleton<IMemoryCache, MemoryCache>();
services.AddSingleton<IUpdaterStore, CosmosDbUpdaterStore>();
services.AddSingleton<IUpdaterService, UpdaterService>();
services.AddHostedService<InitializerService>(); services.AddHostedService<InitializerService>();
services.AddHostedService<ServerRegistryCleanupService>(); services.AddHostedService<ServerRegistryCleanupService>();

View File

@ -20,6 +20,7 @@
cfg.CreateMap<DataContract.ServerInfo, Services.ServerInfo>(); cfg.CreateMap<DataContract.ServerInfo, Services.ServerInfo>();
cfg.CreateMap<Services.ServerInfo, DataContract.ServerInfo>(); cfg.CreateMap<Services.ServerInfo, DataContract.ServerInfo>();
cfg.CreateMap<Services.ServerInfo, DataContract.ServerInfoWithHostAddress>(); cfg.CreateMap<Services.ServerInfo, DataContract.ServerInfoWithHostAddress>();
cfg.CreateMap<Services.VersionInfo, DataContract.VersionInfo>();
}); });
Instance = new AutoMapper.Mapper(config); Instance = new AutoMapper.Mapper(config);

View File

@ -1,10 +1,9 @@
namespace Giants.Services namespace Giants.Services
{ {
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
public interface IUpdaterService public interface IUpdaterService
{ {
Task<VersionInfo> GetVersionInfo(string gameName);
} }
} }

View File

@ -6,16 +6,22 @@
public class InitializerService : IHostedService public class InitializerService : IHostedService
{ {
private readonly IUpdaterStore updaterStore;
private readonly IServerRegistryStore serverRegistryStore; 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; this.serverRegistryStore = serverRegistryStore;
} }
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
await this.serverRegistryStore.Initialize(); await this.serverRegistryStore.Initialize();
await this.updaterStore.Initialize();
} }
public Task StopAsync(CancellationToken cancellationToken) public Task StopAsync(CancellationToken cancellationToken)

View File

@ -36,7 +36,7 @@
public Task StartAsync(CancellationToken cancellationToken) 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; return Task.CompletedTask;
} }
@ -68,7 +68,7 @@
if (expiredServers.Any()) 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); await this.serverRegistryStore.DeleteServers(expiredServers);
} }

View File

@ -49,7 +49,7 @@
} }
// Check cache before we write to store // Check cache before we write to store
ConcurrentDictionary<string, ServerInfo> allServerInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, PopulateCache); ConcurrentDictionary<string, ServerInfo> allServerInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, this.PopulateCache);
if (allServerInfo.ContainsKey(serverInfo.HostIpAddress)) if (allServerInfo.ContainsKey(serverInfo.HostIpAddress))
{ {
@ -80,7 +80,7 @@
public async Task<IEnumerable<ServerInfo>> GetAllServers() public async Task<IEnumerable<ServerInfo>> GetAllServers()
{ {
ConcurrentDictionary<string, ServerInfo> serverInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, PopulateCache); ConcurrentDictionary<string, ServerInfo> serverInfo = await this.memoryCache.GetOrCreateAsync(CacheKeys.ServerInfo, this.PopulateCache);
return serverInfo.Values; return serverInfo.Values;
} }

View File

@ -1,10 +1,8 @@
namespace Giants.Services using System.Threading.Tasks;
{
using System;
using System.Collections.Generic;
using System.Text;
public class UpdaterService namespace Giants.Services
{
public class UpdaterService : IUpdaterService
{ {
private readonly IUpdaterStore updaterStore; private readonly IUpdaterStore updaterStore;
@ -12,5 +10,12 @@
{ {
this.updaterStore = updaterStore; this.updaterStore = updaterStore;
} }
public async Task<VersionInfo> GetVersionInfo(string gameName)
{
ArgumentUtility.CheckStringForNullOrEmpty(gameName, nameof(gameName));
return await this.updaterStore.GetVersionInfo(gameName);
}
} }
} }

View File

@ -5,7 +5,6 @@
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Giants.Services.Core.Entities;
using Microsoft.Azure.Cosmos; using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Linq; using Microsoft.Azure.Cosmos.Linq;
@ -129,11 +128,12 @@
public async Task Initialize(string partitionKeyPath = null) public async Task Initialize(string partitionKeyPath = null)
{ {
// TODO: Use static shared cosmos client
this.client = new CosmosClient( this.client = new CosmosClient(
this.connectionString, this.connectionString,
this.authKeyOrResourceToken); 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() var containerResponse = await databaseResponse.Database.CreateContainerIfNotExistsAsync(new ContainerProperties()
{ {
Id = containerId, Id = containerId,

View File

@ -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<CosmosDbServerRegistryStore> logger;
private readonly IMemoryCache memoryCache;
private readonly IConfiguration configuration;
private CosmosDbClient client;
public CosmosDbUpdaterStore(
ILogger<CosmosDbServerRegistryStore> logger,
IMemoryCache memoryCache,
IConfiguration configuration)
{
this.logger = logger;
this.memoryCache = memoryCache;
this.configuration = configuration;
}
public async Task<VersionInfo> GetVersionInfo(string gameName)
{
VersionInfo versionInfo = await this.memoryCache.GetOrCreateAsync<VersionInfo>(
key: GetCacheKey(gameName),
factory: async (entry) =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await this.client.GetItemById<VersionInfo>(
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}";
}
}
}

View File

@ -1,10 +1,18 @@
namespace Giants.Services namespace Giants.Services
{ {
using System; using System;
using System.Collections.Generic; using System.Threading.Tasks;
using System.Text;
public class FileUpdaterStore : IUpdaterStore public class FileUpdaterStore : IUpdaterStore
{ {
public Task<VersionInfo> GetVersionInfo(string gameName)
{
throw new NotImplementedException();
}
public Task Initialize()
{
throw new NotImplementedException();
}
} }
} }

View File

@ -1,10 +1,11 @@
namespace Giants.Services namespace Giants.Services
{ {
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
public interface IUpdaterStore public interface IUpdaterStore
{ {
Task<VersionInfo> GetVersionInfo(string gameName);
Task Initialize();
} }
} }

View File

@ -14,9 +14,9 @@
public Task<ServerInfo> GetServerInfo(string ipAddress) public Task<ServerInfo> 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); return Task.FromResult((ServerInfo)null);

View File

@ -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<DataContract.VersionInfo> GetVersionInfo(string gameName)
{
Services.VersionInfo versionInfo = await this.updaterService.GetVersionInfo(gameName);
return mapper.Map<DataContract.VersionInfo>(versionInfo);
}
}
}