Moved settings loading, and proxy and authentication module configuration to the Settings class as it's more relevant there.

Signed-off-by: Konstantina Chremmou <konstantina.chremmou@citrix.com>
This commit is contained in:
Konstantina Chremmou 2022-11-11 13:57:37 +00:00
parent cc808dff1d
commit 1102ac80e2
3 changed files with 120 additions and 121 deletions

View File

@ -257,7 +257,7 @@ namespace XenAdmin.Dialogs.OptionsPages
if (timeout != Properties.Settings.Default.ConnectionTimeout)
Properties.Settings.Default.ConnectionTimeout = timeout;
Program.ReconfigureConnectionSettings();
Settings.ReconfigureProxyAuthenticationSettings();
Core.HealthCheck.SendProxySettingsToHealthCheck();
}

View File

@ -56,15 +56,6 @@ namespace XenAdmin
{
public const int DEFAULT_WLB_PORT = 8012;
/// <summary>
/// Module for authenticating with proxy server using the Basic authentication scheme.
/// </summary>
private static IAuthenticationModule BasicAuthenticationModule;
/// <summary>
/// Module for authenticating with proxy server using the Digest authentication scheme.
/// </summary>
private static IAuthenticationModule DigestAuthenticationModule;
/// <summary>
/// A UUID for the current instance of XenCenter. Used to identify our own task instances.
/// </summary>
@ -127,7 +118,7 @@ namespace XenAdmin
// Start timer to record resource usage every 24hrs
dailyTimer = new System.Threading.Timer(delegate
{
logApplicationStats();
LogApplicationStats();
}, null, new TimeSpan(24, 0, 0), new TimeSpan(24, 0, 0));
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Assembly.GetCallingAssembly().Location + ".config"));
@ -142,48 +133,7 @@ namespace XenAdmin
[STAThread]
public static void Main(string[] args)
{
string appVersionString = Version.ToString();
log.InfoFormat("Application version of current settings {0}", appVersionString);
try
{
if (Properties.Settings.Default.ApplicationVersion != appVersionString)
{
log.Info("Upgrading settings...");
Properties.Settings.Default.Upgrade();
// if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings
// because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings.
// We will try and find a config file from a previous installation and update the settings from it
if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade)
Settings.UpgradeFromPreviousInstallation();
log.InfoFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString);
Properties.Settings.Default.ApplicationVersion = appVersionString;
Settings.TrySaveSettings();
}
}
catch (ConfigurationErrorsException ex)
{
log.Error("Could not load settings.", ex);
var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE,
string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath()));
using (var dlg = new ErrorDialog(msg)
{
StartPosition = FormStartPosition.CenterScreen,
//For reasons I do not fully comprehend at the moment, the runtime
//overrides the above StartPosition with WindowsDefaultPosition if
//ShowInTaskbar is false. However it's a good idea anyway to show it
//in the taskbar since the main form is not launched at this point.
ShowInTaskbar = true
})
{
dlg.ShowDialog();
}
Application.Exit();
return;
}
Settings.Load();
// Reset statics, because XenAdminTests likes to call Main() twice.
TestExceptionString = null;
@ -204,7 +154,6 @@ namespace XenAdmin
// We must NEVER request ProfessionalColors before we have called Application.EnableVisualStyles
// as it may prevent the program from displayed as expected.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Force the current culture, to make the layout the same whatever the culture of the underlying OS (CA-46983).
@ -217,12 +166,12 @@ namespace XenAdmin
ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Session.UserAgent = $"{BrandManager.BrandConsole} {Version}";
RememberProxyAuthenticationModules();
ReconfigureConnectionSettings();
Settings.ReconfigureProxyAuthenticationSettings();
Settings.ConfigureExternalSshClientSettings();
log.Info("Application started");
logSystemDetails();
LogSystemDetails();
Settings.Log();
// Remove the '--wait' argument, which may have been passed to the splash screen
@ -391,7 +340,7 @@ namespace XenAdmin
}
}
private static void logSystemDetails()
private static void LogSystemDetails()
{
log.InfoFormat("Version: {0}", Version);
log.InfoFormat(".NET runtime version: {0}", Environment.Version.ToString(4));
@ -404,7 +353,7 @@ namespace XenAdmin
{
Exiting = true;
logApplicationStats();
LogApplicationStats();
Clip.UnregisterClipboardViewer();
@ -423,7 +372,7 @@ namespace XenAdmin
conn.EndConnect(false, true);
}
private static void logApplicationStats()
private static void LogApplicationStats()
{
Process p = Process.GetCurrentProcess();
@ -479,8 +428,8 @@ namespace XenAdmin
{
log.Fatal("Fatal error");
}
logSystemDetails();
logApplicationStats();
LogSystemDetails();
LogApplicationStats();
if (RunInAutomatedTestMode)
{
@ -856,60 +805,6 @@ namespace XenAdmin
}
#endregion
public static void ReconfigureConnectionSettings()
{
ReconfigureProxyAuthenticationSettings();
Session.Proxy = XenAdminConfigManager.Provider.GetProxyFromSettings(null);
}
/// <summary>
/// Stores the Basic and Digest authentication modules, used for proxy server authentication,
/// for later use; this is needed because we cannot create new instances of them and it
/// saves us needing to create our own custom authentication modules.
/// </summary>
private static void RememberProxyAuthenticationModules()
{
var authModules = AuthenticationManager.RegisteredModules;
while (authModules.MoveNext())
{
if (!(authModules.Current is IAuthenticationModule module))
continue;
if (module.AuthenticationType == "Basic")
BasicAuthenticationModule = module;
else if (module.AuthenticationType == "Digest")
DigestAuthenticationModule = module;
}
}
/// <summary>
/// Configures .NET's AuthenticationManager to only use the authentication module that is
/// specified in the ProxyAuthenticationMethod setting. Also sets XenAPI's HTTP class to
/// use the same authentication method.
/// </summary>
private static void ReconfigureProxyAuthenticationSettings()
{
var authModules = AuthenticationManager.RegisteredModules;
var modulesToUnregister = new List<IAuthenticationModule>();
while (authModules.MoveNext())
{
var module = (IAuthenticationModule)authModules.Current;
modulesToUnregister.Add(module);
}
foreach (var module in modulesToUnregister)
AuthenticationManager.Unregister(module);
var authSetting = (HTTP.ProxyAuthenticationMethod)Properties.Settings.Default.ProxyAuthenticationMethod;
if (authSetting == HTTP.ProxyAuthenticationMethod.Basic)
AuthenticationManager.Register(BasicAuthenticationModule);
else
AuthenticationManager.Register(DigestAuthenticationModule);
HTTP.CurrentProxyAuthenticationMethod = authSetting;
}
private const string SplashWindowClass = "XenCenterSplash0001";
internal static void CloseSplash()
@ -924,7 +819,6 @@ namespace XenAdmin
log.Warn("PostMessage WM_DESTROY failed in CloseSplash()", new Win32Exception());
}
}
public static void OpenURL(string url)
{
if (RunInAutomatedTestMode || string.IsNullOrEmpty(url))

View File

@ -31,15 +31,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using XenAdmin.Core;
using XenAdmin.Dialogs;
using XenAdmin.Dialogs.RestoreSession;
using XenAdmin.Network;
using System.Configuration;
using System.IO;
using XenAPI;
using XenCenterLib;
using System.Linq;
namespace XenAdmin
@ -48,6 +50,15 @@ namespace XenAdmin
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Module for authenticating with proxy server using the Basic authentication scheme.
/// </summary>
private static IAuthenticationModule BasicAuthenticationModule;
/// <summary>
/// Module for authenticating with proxy server using the Digest authentication scheme.
/// </summary>
private static IAuthenticationModule DigestAuthenticationModule;
/// <summary>
/// Used in place of the username, to indicate that a record is for a VM's VNC connection, rather
/// than a connection to a server.
@ -68,6 +79,26 @@ namespace XenAdmin
/// </summary>
private static Dictionary<string, string> VNCPasswords = new Dictionary<string, string>();
static Settings()
{
// Store the Basic and Digest authentication modules, used for proxy server authentication,
// for later use; this is needed because we cannot create new instances of them and it
// saves us needing to create our own custom authentication modules.
var authModules = AuthenticationManager.RegisteredModules;
while (authModules.MoveNext())
{
if (!(authModules.Current is IAuthenticationModule module))
continue;
if (module.AuthenticationType == "Basic")
BasicAuthenticationModule = module;
else if (module.AuthenticationType == "Digest")
DigestAuthenticationModule = module;
}
}
/// <summary>
/// MSDN info regarding the path to the user.config file is somewhat confusing.
/// It turns out it is not in Application.UserAppDataPath as stated on
@ -701,10 +732,55 @@ namespace XenAdmin
log.Info($"=== IgnoreOvfValidationWarnings: {Properties.Settings.Default.IgnoreOvfValidationWarnings}");
}
public static void Load()
{
string appVersionString = Program.Version.ToString();
log.InfoFormat("Application version of current settings {0}", appVersionString);
try
{
if (Properties.Settings.Default.ApplicationVersion != appVersionString)
{
log.Info("Upgrading settings...");
Properties.Settings.Default.Upgrade();
// if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings
// because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings.
// We will try and find a config file from a previous installation and update the settings from it
if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade)
UpgradeFromPreviousInstallation();
log.InfoFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString);
Properties.Settings.Default.ApplicationVersion = appVersionString;
TrySaveSettings();
}
}
catch (ConfigurationErrorsException ex)
{
log.Error("Could not load settings.", ex);
var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE,
string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, GetUserConfigPath()));
using (var dlg = new ErrorDialog(msg)
{
StartPosition = FormStartPosition.CenterScreen,
//For reasons I do not fully comprehend at the moment, the runtime
//overrides the above StartPosition with WindowsDefaultPosition if
//ShowInTaskbar is false. However it's a good idea anyway to show it
//in the taskbar since the main form is not launched at this point.
ShowInTaskbar = true
})
{
dlg.ShowDialog();
}
Application.Exit();
}
}
/// <summary>
/// Looks for a config file from a previous installation of the application and updates the settings from it.
/// </summary>
public static void UpgradeFromPreviousInstallation()
private static void UpgradeFromPreviousInstallation()
{
try
{
@ -767,5 +843,34 @@ namespace XenAdmin
log.Debug("Exception while updating settings.", ex);
}
}
/// <summary>
/// Configures .NET's AuthenticationManager to only use the authentication module that is
/// specified in the ProxyAuthenticationMethod setting. Also sets XenAPI's HTTP class to
/// use the same authentication method.
/// </summary>
public static void ReconfigureProxyAuthenticationSettings()
{
var authModules = AuthenticationManager.RegisteredModules;
var modulesToUnregister = new List<IAuthenticationModule>();
while (authModules.MoveNext())
{
var module = (IAuthenticationModule)authModules.Current;
modulesToUnregister.Add(module);
}
foreach (var module in modulesToUnregister)
AuthenticationManager.Unregister(module);
var authSetting = (HTTP.ProxyAuthenticationMethod)Properties.Settings.Default.ProxyAuthenticationMethod;
if (authSetting == HTTP.ProxyAuthenticationMethod.Basic)
AuthenticationManager.Register(BasicAuthenticationModule);
else
AuthenticationManager.Register(DigestAuthenticationModule);
HTTP.CurrentProxyAuthenticationMethod = authSetting;
Session.Proxy = XenAdminConfigManager.Provider.GetProxyFromSettings(null);
}
}
}