diff --git a/AddManifest.targets b/AddManifest.targets deleted file mode 100644 index b8a85d6b6f..0000000000 --- a/AddManifest.targets +++ /dev/null @@ -1,9 +0,0 @@ - - - - - $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot10', null, RegistryView.Registry32, RegistryView.Default)) - - "$(WinKits10Path)bin\10.0.18362.0\x64\mt.exe" -verbose -manifest "$(ProjectDir)app.manifest" -outputresource:"$(TargetDir)$(TargetFileName)";#1 - - diff --git a/CFUValidator/CFUValidator.cs b/CFUValidator/CFUValidator.cs deleted file mode 100644 index 94bc434a4f..0000000000 --- a/CFUValidator/CFUValidator.cs +++ /dev/null @@ -1,207 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Linq; -using System.Collections.Generic; -using System.Text; -using CFUValidator.CommandLineOptions; -using CFUValidator.OutputDecorators; -using CFUValidator.Updates; -using CFUValidator.Validators; -using Moq; -using XenAdmin; -using XenAdmin.Core; -using XenAdminTests; -using XenAPI; - - -namespace CFUValidator -{ - public class CFUValidationException : Exception - { - public CFUValidationException(string message) : base(message){} - } - - public class CFUValidator - { - private readonly MockObjectManager mom = new MockObjectManager(); - private readonly XmlRetrieverFactory xmlFactory = new XmlRetrieverFactory(); - private const string id = "id"; - private readonly string _xmlLocation; - private readonly string _serverVersion; - private readonly OptionUsage UrlOrFile; - private readonly List _installedHotfixes; - private readonly bool _checkHotfixContents; - private readonly IConfigProvider _configProvider; - - public CFUValidator(OptionUsage urlOrFile, string xmlLocation, string serverVersion, - List installedHotfixes, bool checkHotfixContents, IConfigProvider configProvider) - { - if (urlOrFile != OptionUsage.File && urlOrFile != OptionUsage.Url) - throw new ArgumentException("urlOrFile option should be either File or Url"); - - mom.CreateNewConnection(id); - ConnectionsManager.XenConnections.AddRange(mom.AllConnections); - _xmlLocation = xmlLocation; - _serverVersion = serverVersion; - _installedHotfixes = installedHotfixes; - UrlOrFile = urlOrFile; - _checkHotfixContents = checkHotfixContents; - _configProvider = configProvider; - } - - public void Validate(Action statusReporter) - { - statusReporter($"Getting check for updates XML from {_xmlLocation}..."); - ReadCheckForUpdatesXML(out var xenServerPatches, out var xenServerVersions); - - List versionsToCheck; - if (_serverVersion == CFUCommandLineOptionManager.AllVersions) - { - versionsToCheck = xenServerVersions.ConvertAll(i => i.Version.ToString()).Distinct().ToList(); - } - else - { - CheckVersionExistsInCfu(_serverVersion, xenServerVersions); - versionsToCheck = new List {_serverVersion}; - } - - var summaryGenerators = new List(); - foreach (string ver in versionsToCheck) - summaryGenerators.AddRange(RunTestsForGivenServerVersion(ver, xenServerVersions, xenServerPatches, statusReporter)); - - summaryGenerators.ForEach(s => statusReporter(s.GenerateSummary())); - } - - private List RunTestsForGivenServerVersion(string serverVersion, List xenServerVersions, - List xenServerPatches, Action statusReporter) - { - statusReporter($"Generating server {serverVersion} mock-ups..."); - SetupMocks(serverVersion, xenServerPatches, xenServerVersions); - - statusReporter("Determining required XenServer update..."); - var updateAlerts = XenAdmin.Core.Updates.NewXenServerVersionAlerts(xenServerVersions).Where(alert => !alert.CanIgnore).ToList(); - - statusReporter("Determining required patches..."); - var patchAlerts = XenAdmin.Core.Updates.NewXenServerPatchAlerts(xenServerVersions, xenServerPatches).Where(alert => !alert.CanIgnore).ToList(); - - statusReporter("Running patch check(s), this may take some time..."); - - var validators = new List - { - new HfxEligibilityValidator(xenServerVersions), - new CorePatchDetailsValidator(patchAlerts), - new PatchURLValidator(patchAlerts) - }; - - if (_checkHotfixContents) - validators.Add(new ZipContentsValidator(patchAlerts, _configProvider)); - - validators.ForEach(v => v.Validate(statusReporter)); - - var summaryGenerators = new List {new HeaderDecorator(serverVersion, _xmlLocation)}; - summaryGenerators.AddRange(validators); - summaryGenerators.Add(new XenServerUpdateDecorator(updateAlerts)); - summaryGenerators.Add(new PatchAlertDecorator(patchAlerts)); - return summaryGenerators; - } - - private void CheckVersionExistsInCfu(string serverVersion, List xenServerVersions) - { - if (xenServerVersions.All(v => v.Version.ToString() != serverVersion)) - { - var sb = new StringBuilder(); - sb.AppendLine($"Could not find version {serverVersion} in the CFU file."); - sb.AppendLine("Available versions are:"); - xenServerVersions.Select(i => i.Version.ToString()).Distinct().ToList().ForEach(v => sb.AppendLine(v)); - throw new CFUValidationException(sb.ToString()); - } - } - - private void ReadCheckForUpdatesXML(out List patches, out List versions) - { - ICheckForUpdatesXMLSource checkForUpdates = xmlFactory.GetAction(UrlOrFile, _xmlLocation); - checkForUpdates.RunAsync(); - - ConsoleSpinner spinner = new ConsoleSpinner(); - while(!checkForUpdates.IsCompleted) - { - spinner.Turn(checkForUpdates.PercentComplete); - } - - if (checkForUpdates.ErrorRaised != null) - throw checkForUpdates.ErrorRaised; - - patches = checkForUpdates.XenServerPatches; - versions = checkForUpdates.XenServerVersions; - } - - private void SetupMocks(string versionToCheck, List xenServerPatches, List xenServerVersions) - { - Mock coordinator = mom.NewXenObject(id); - Mock pool = mom.NewXenObject(id); - XenRef coordinatorRef = new XenRef("ref"); - pool.Setup(p => p.master).Returns(coordinatorRef); - pool.Setup(p => p.other_config).Returns(new Dictionary()); - mom.MockCacheFor(id).Setup(c => c.Resolve(It.IsAny>())).Returns(pool.Object); - mom.MockConnectionFor(id).Setup(c => c.Resolve(coordinatorRef)).Returns(coordinator.Object); - mom.MockConnectionFor(id).Setup(c => c.IsConnected).Returns(true); - coordinator.Setup(h => h.software_version).Returns(new Dictionary()); - coordinator.Setup(h => h.ProductVersion()).Returns(versionToCheck); - coordinator.Setup(h => h.AppliedPatches()).Returns(GenerateMockPoolPatches(xenServerPatches)); - - //Currently build number will be referenced first so if it's present hook it up - string buildNumber = xenServerVersions.First(v => v.Version.ToString() == versionToCheck).BuildNumber; - coordinator.Setup(h=>h.BuildNumberRaw()).Returns(buildNumber); - } - - private List GenerateMockPoolPatches(List xenServerPatches) - { - List patches = new List(); - - foreach (string installedHotfix in _installedHotfixes) - { - string hotfix = installedHotfix; - XenServerPatch match = xenServerPatches.Find(m => m.Name.Contains(hotfix)); - - if(match == null) - throw new CFUValidationException("No patch could be found in the XML matching " + hotfix); - - Mock pp = mom.NewXenObject(id); - pp.Setup(p => p.uuid).Returns(match.Uuid); - patches.Add(pp.Object); - } - - return patches; - } - - } -} diff --git a/CFUValidator/CFUValidator.csproj b/CFUValidator/CFUValidator.csproj deleted file mode 100644 index be6951a37e..0000000000 --- a/CFUValidator/CFUValidator.csproj +++ /dev/null @@ -1,145 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {39308480-78C3-40B4-924D-06914F343ACD} - Exe - Properties - CFUValidator - CFUValidator - v4.8 - 512 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - true - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - ..\packages\Moq.dll - - - - 3.5 - - - - - - Properties\CommonAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - false - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {21B9482C-D255-40D5-ABA7-C8F00F99547C} - XenAdminTests - - - {70BDA4BC-F062-4302-8ACD-A15D8BF31D65} - XenAdmin - - - {9861DFA1-B41F-432D-A43F-226257DEBBB9} - XenCenterLib - - - {B306FC59-4441-4A5F-9F54-D3F68D4EE38D} - XenModel - - - - - - - - \ No newline at end of file diff --git a/CFUValidator/CommandLineOptions/CFUCommandLineOptionManager.cs b/CFUValidator/CommandLineOptions/CFUCommandLineOptionManager.cs deleted file mode 100644 index 6f8c5f3a34..0000000000 --- a/CFUValidator/CommandLineOptions/CFUCommandLineOptionManager.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace CFUValidator.CommandLineOptions -{ - internal class CFUCommandLineOptionManager - { - public CFUCommandLineOptionManager(CommandLineArgument[] args) - { - if (args.First(c => c.Usage == OptionUsage.Help).IsActiveOption || - args.All(c => !c.IsActiveOption)) - throw new CFUValidationException(GetHelp(args)); - - CommandLineArgument urlArg = args.First(c => c.Usage == OptionUsage.Url); - CommandLineArgument fileArg = args.First(c => c.Usage == OptionUsage.File); - - if (urlArg.IsActiveOption && fileArg.IsActiveOption) - throw new CFUValidationException($"Switches '-{fileArg.Switch}' and '-{urlArg.Switch}' cannot be used at the same time"); - - if (!urlArg.IsActiveOption && !fileArg.IsActiveOption) - throw new CFUValidationException($"You must provide either option '-{fileArg.Switch}' or '-{urlArg.Switch}'"); - - if (fileArg.IsActiveOption) - { - XmlLocation = fileArg.Options.First(); - XmlLocationType = fileArg.Usage; - } - else - { - XmlLocation = urlArg.Options.First(); - XmlLocationType = urlArg.Usage; - } - - CheckHotfixContents = args.First(c => c.Usage == OptionUsage.CheckZipContents).IsActiveOption; - - CommandLineArgument usernameArg = args.First(c => c.Usage == OptionUsage.Username); - CommandLineArgument clientIdArg = args.First(c => c.Usage == OptionUsage.ClientId); - - if (CheckHotfixContents) - { - Username = usernameArg.Options.First(); - ClientId = clientIdArg.Options.First(); - } - - var serverArg = args.First(c => c.Usage == OptionUsage.ServerVersion); - ServerVersion = serverArg.IsActiveOption ? serverArg.Options.First() : AllVersions; - - var hotfixArg = args.First(c => c.Usage == OptionUsage.Hotfix); - InstalledHotfixes = hotfixArg.IsActiveOption ? hotfixArg.Options : new List(); - } - - public static string AllVersions = "999.999.999"; - - public string XmlLocation { get; } - - public bool CheckHotfixContents { get; } - - public string Username { get; } - - public string ClientId { get; } - - public OptionUsage XmlLocationType { get; } - - public string ServerVersion { get; } - - public List InstalledHotfixes { get; } - - private static string GetHelp(CommandLineArgument[] args) - { - StringBuilder sb = new StringBuilder(); - sb.AppendLine("\nUsage:"); - sb.AppendLine("\n CFUValidator.exe [options]"); - sb.AppendLine("\nOptions:"); - - var orderedArgs = args.OrderBy(c => c.Switch); - foreach (CommandLineArgument cla in orderedArgs) - sb.AppendLine($" -{cla.Switch} {cla.Description}"); - return sb.ToString(); - } - } -} diff --git a/CFUValidator/CommandLineOptions/CommandLineArgument.cs b/CFUValidator/CommandLineOptions/CommandLineArgument.cs deleted file mode 100644 index 9de2ebef66..0000000000 --- a/CFUValidator/CommandLineOptions/CommandLineArgument.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System.Collections.Generic; - -namespace CFUValidator.CommandLineOptions -{ - public enum OptionUsage - { - Help, - Url, - File, - Hotfix, - ServerVersion, - CheckZipContents, - Username, - ClientId - } - - public class CommandLineArgument - { - public CommandLineArgument(OptionUsage usage, char commandSwitch, string description) - { - Switch = commandSwitch; - Description = description; - Usage = usage; - Options = null; - IsActiveOption = false; - } - - public OptionUsage Usage { get; private set; } - public char Switch { get; private set; } - public List Options { get; set; } - public string Description { get; private set; } - public bool IsActiveOption { get; set; } - } -} diff --git a/CFUValidator/CommandLineOptions/CommandLineParser.cs b/CFUValidator/CommandLineOptions/CommandLineParser.cs deleted file mode 100644 index d7b534aacf..0000000000 --- a/CFUValidator/CommandLineOptions/CommandLineParser.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Linq; -using System.Text.RegularExpressions; - -namespace CFUValidator.CommandLineOptions -{ - public class CommandLineParser - { - private readonly string[] args; - - public CommandLineArgument[] ParsedArguments { get; } = - { - new CommandLineArgument(OptionUsage.Help, 'h', "Display this help."), - new CommandLineArgument(OptionUsage.CheckZipContents, 'c', "Optionally check the zip contents of the hotfixes."), - new CommandLineArgument(OptionUsage.Url, 'u', "URL of CFU XML. Cannot be used with -f flag."), - new CommandLineArgument(OptionUsage.File, 'f', "Path to CFU XML file. Cannot be used with -u flag."), - new CommandLineArgument(OptionUsage.ServerVersion, 's', "Server version to test, eg. 6.0.2."), - new CommandLineArgument(OptionUsage.Hotfix, 'p', "Space delimited list of patches/hotfixes to test, e.g. XS602E001."), - new CommandLineArgument(OptionUsage.Username, 'n', "Username for downloading hotfixes, e.g. john123."), - new CommandLineArgument(OptionUsage.ClientId, 'k', "ClientId to use for downloading hotfixes (alphanumeric string).") - }; - - public CommandLineParser(string[] args) - { - this.args = args; - } - - public void Parse() - { - string[] recastArgs = Regex.Split(string.Join(" ", args).Trim(), @"(?=[-])(?<=[ ])"); - foreach (string arg in recastArgs) - { - if (String.IsNullOrEmpty(arg)) - continue; - - string optionSwitch = Regex.Match(arg, "[-]{1}[a-z]{1}").Value.Trim(); - char switchChar = Convert.ToChar(optionSwitch.Substring(1, 1)); - string[] splitArgs = arg.Replace(optionSwitch, "").Trim().Split(' '); - - CommandLineArgument cla = ParsedArguments.FirstOrDefault(c => c.Switch == switchChar); - if (cla != null) - { - cla.Options = splitArgs.Where(s => !String.IsNullOrEmpty(s)).ToList(); - cla.IsActiveOption = true; - } - } - } - } -} diff --git a/CFUValidator/ConsoleSpinner.cs b/CFUValidator/ConsoleSpinner.cs deleted file mode 100644 index 7c54f7a492..0000000000 --- a/CFUValidator/ConsoleSpinner.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Threading; - -namespace CFUValidator -{ - public class ConsoleSpinner - { - int counter; - private const string working = "Working "; - - public ConsoleSpinner() - { - counter = 0; - } - - public void Turn() - { - counter++; - switch (counter % 4) - { - case 0: WriteAtOrigin(working + "/"); break; - case 1: WriteAtOrigin(working + "-"); break; - case 2: WriteAtOrigin(working + "\\"); break; - case 3: WriteAtOrigin(working + "|"); break; - } - Thread.Sleep(500); - } - - public void Turn(double percentageComplete) - { - counter++; - switch (counter % 4) - { - case 0: WriteAtOrigin(working + "/ (" + percentageComplete + "%)"); break; - case 1: WriteAtOrigin(working + "- (" + percentageComplete + "%)"); break; - case 2: WriteAtOrigin(working + "\\ (" + percentageComplete + "%)"); break; - case 3: WriteAtOrigin(working + "| (" + percentageComplete + "%)"); break; - } - Thread.Sleep(500); - } - - private void WriteAtOrigin(string toWrite) - { - try - { - Console.SetCursorPosition(0, Console.CursorTop); - Console.Write(toWrite); - Console.SetCursorPosition(0, Console.CursorTop); - } - catch (SystemException){} - } - } -} - diff --git a/CFUValidator/OutputDecorators/AlertDecorator.cs b/CFUValidator/OutputDecorators/AlertDecorator.cs deleted file mode 100644 index 888cc59787..0000000000 --- a/CFUValidator/OutputDecorators/AlertDecorator.cs +++ /dev/null @@ -1,137 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using XenAdmin.Alerts; - - -namespace CFUValidator.OutputDecorators -{ - public interface ISummaryGenerator - { - string GenerateSummary(); - } - - public class HeaderDecorator : ISummaryGenerator - { - private readonly string _serverVersion; - private readonly string _xmlLocation; - - public HeaderDecorator(string serverVersion, string xmlLocation) - { - _serverVersion = serverVersion; - _xmlLocation = xmlLocation; - } - - public string GenerateSummary() - { - return $"Summary for server version {_serverVersion}, XML from {_xmlLocation}, generated at {DateTime.Now.ToLocalTime()}\n"; - } - } - - public abstract class AlertDecorator : ISummaryGenerator - { - public string GenerateSummary() - { - var sb = new StringBuilder(); - sb.AppendLine(SummaryTitle); - sb.AppendLine(GenerateSummaryCore()); - return sb.ToString(); - } - - protected abstract string GenerateSummaryCore(); - - protected abstract string SummaryTitle { get; } - } - - class XenServerUpdateDecorator : AlertDecorator - { - private readonly List _alerts; - - public XenServerUpdateDecorator(List alerts) - { - _alerts = alerts; - } - - protected override string GenerateSummaryCore() - { - if (_alerts.Count == 0) - return "None"; - - var sb = new StringBuilder(); - foreach (XenServerVersionAlert alert in _alerts) - sb.AppendLine(alert == null ? "XenServer update could not be found" : alert.Version.Name); - return sb.ToString(); - } - - protected override string SummaryTitle => "XenServer updates required:"; - } - - - class PatchAlertDecorator : AlertDecorator - { - private readonly List _alerts; - private const string HOTFIX_REGEX = "XS[0-9]+E[A-Z]*[0-9]+"; - - public PatchAlertDecorator(List alerts) - { - _alerts = alerts; - } - - protected override string GenerateSummaryCore() - { - if (_alerts.Count == 0) - return "None"; - - var sb = new StringBuilder(); - - foreach (XenServerPatchAlert alert in _alerts.OrderBy(a => a.Patch.Name)) - { - string patchName = Regex.Match(alert.Patch.Name, HOTFIX_REGEX).Value; - - if (string.IsNullOrEmpty(patchName)) - patchName = alert.Patch.Name.Trim(); - - if (string.IsNullOrEmpty(patchName)) - patchName = $"Name unknown (uuid={alert.Patch.Uuid})"; - - sb.AppendLine(patchName); - } - - return sb.ToString(); - } - - protected override string SummaryTitle => "Patches required:"; - } -} diff --git a/CFUValidator/Program.cs b/CFUValidator/Program.cs deleted file mode 100644 index 5a244b8390..0000000000 --- a/CFUValidator/Program.cs +++ /dev/null @@ -1,97 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Net; -using CFUValidator.CommandLineOptions; -using XenAdmin; -using XenAdmin.Core; -using XenAdmin.Network; - -namespace CFUValidator -{ - static class Program - { - static void Main(string[] args) - { - try - { - CommandLineParser parser = new CommandLineParser(args); - parser.Parse(); - - CFUCommandLineOptionManager manager = new CFUCommandLineOptionManager(parser.ParsedArguments); - - var cfuValidator = new CFUValidator(manager.XmlLocationType, manager.XmlLocation, - manager.ServerVersion, manager.InstalledHotfixes, - manager.CheckHotfixContents, new ConfigProvider(manager.Username, manager.ClientId)); - - cfuValidator.Validate(Console.WriteLine); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - - if (!(ex is CFUValidationException)) - Console.WriteLine(ex.StackTrace); - - Environment.Exit(1); - } - - Environment.Exit(0); - } - } - - public class ConfigProvider : IConfigProvider - { - public ConfigProvider(string username, string clientId) - { - FileServiceUsername = username; - FileServiceClientId = clientId; - } - - public string FileServiceUsername { get; } - public string FileServiceClientId { get; } - - public string GetCustomTokenUrl() - { - return Registry.GetCustomTokenUrl() ?? InvisibleMessages.TOKEN_API_URL; - } - - public IWebProxy GetProxyFromSettings(IXenConnection connection) - { - return null; - } - - public IWebProxy GetProxyFromSettings(IXenConnection connection, bool isForXenServer) - { - return null; - } - } -} diff --git a/CFUValidator/Properties/AssemblyInfo.cs b/CFUValidator/Properties/AssemblyInfo.cs deleted file mode 100644 index e6cfaecbb1..0000000000 --- a/CFUValidator/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CFUValidator")] -[assembly: AssemblyDescription("Utility for testing [XenServerProduct] update packages")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("[XenCenter]")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1fc53fff-32d6-4775-a913-203c3410d388")] diff --git a/CFUValidator/Updates/AlternativeUrlDownloadUpdatesXmlSourceAction.cs b/CFUValidator/Updates/AlternativeUrlDownloadUpdatesXmlSourceAction.cs deleted file mode 100644 index 9b0b0f50c1..0000000000 --- a/CFUValidator/Updates/AlternativeUrlDownloadUpdatesXmlSourceAction.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Net; -using System.Xml; -using XenAdmin.Actions; - - -namespace CFUValidator.Updates -{ - class AlternativeUrlDownloadUpdatesXmlSourceAction : DownloadCfuAction, ICheckForUpdatesXMLSource - { - private readonly string _url; - - public AlternativeUrlDownloadUpdatesXmlSourceAction(string url) - : base(true, true, "CFU", url, true) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } - - protected override XmlDocument FetchCheckForUpdatesXml() - { - try - { - XmlDocument doc = new XmlDocument(); - XmlReaderSettings settings = new XmlReaderSettings - { - IgnoreComments = true, - IgnoreWhitespace = true, - IgnoreProcessingInstructions = true - }; - - WebRequest wr = WebRequest.Create(_url); - using (Stream xmlStream = wr.GetResponse().GetResponseStream()) - { - if (xmlStream != null) - using (var reader = XmlReader.Create(xmlStream, settings)) - doc.Load(reader); - } - - return doc; - } - catch (Exception) - { - ErrorRaised = new CFUValidationException("Failed to wget the URL: " + _url); - throw ErrorRaised; - } - } - - public Exception ErrorRaised { get; private set; } - } -} diff --git a/CFUValidator/Updates/ICheckForUpdatesXMLSource.cs b/CFUValidator/Updates/ICheckForUpdatesXMLSource.cs deleted file mode 100644 index e1fab94207..0000000000 --- a/CFUValidator/Updates/ICheckForUpdatesXMLSource.cs +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using XenAdmin.Core; - -namespace CFUValidator.Updates -{ - interface ICheckForUpdatesXMLSource - { - List XenServerPatches { get; } - List XenServerVersions{ get; } - bool IsCompleted { get; } - void RunAsync(); - int PercentComplete { get; } - Exception ErrorRaised { get; } - } -} diff --git a/CFUValidator/Updates/ReadFromFileUpdatesXmlSource.cs b/CFUValidator/Updates/ReadFromFileUpdatesXmlSource.cs deleted file mode 100644 index 2b62fe26b3..0000000000 --- a/CFUValidator/Updates/ReadFromFileUpdatesXmlSource.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Xml; -using XenAdmin.Actions; - -namespace CFUValidator.Updates -{ - class ReadFromFileUpdatesXmlSource : DownloadCfuAction, ICheckForUpdatesXMLSource - { - private readonly string _location; - - public ReadFromFileUpdatesXmlSource(string location) - : base(true, true, "CFU", location, true) - { - _location = location ?? throw new ArgumentNullException(nameof(location)); - } - - protected override XmlDocument FetchCheckForUpdatesXml() - { - if (!File.Exists(_location)) - { - ErrorRaised = new CFUValidationException("File not found at: " + _location); - throw ErrorRaised; - } - - try - { - XmlDocument xdoc = new XmlDocument(); - using (StreamReader sr = new StreamReader(_location)) - xdoc.Load(sr); - return xdoc; - } - catch(Exception) - { - ErrorRaised = new CFUValidationException("Could not read/parse file: " + _location); - throw ErrorRaised; - } - - } - - public Exception ErrorRaised { get; private set; } - } -} diff --git a/CFUValidator/Validators/CorePatchDetailsValidator.cs b/CFUValidator/Validators/CorePatchDetailsValidator.cs deleted file mode 100644 index 22dd2bed30..0000000000 --- a/CFUValidator/Validators/CorePatchDetailsValidator.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using XenAdmin.Alerts; - -namespace CFUValidator.Validators -{ - class CorePatchDetailsValidator : Validator - { - private readonly List alerts; - - public CorePatchDetailsValidator(List alerts) - { - this.alerts = alerts; - } - - protected override string SummaryTitle => "Core details in patch checks:"; - - protected override string Header => "Verifying core patch details..."; - - protected override string Footer => "Verification of core patch details completed."; - - protected override void ValidateCore(Action statusReporter) - { - foreach (XenServerPatchAlert alert in alerts) - { - if(string.IsNullOrEmpty(alert.Patch.Uuid)) - Errors.Add("Missing patch uuid for patch: " + alert.Patch.Name); - if(string.IsNullOrEmpty(alert.Patch.Name)) - Errors.Add("Missing patch name for patch with UUID: " + alert.Patch.Uuid); - if(string.IsNullOrEmpty(alert.Patch.PatchUrl)) - Errors.Add("Missing patch patch-url for patch with UUID: " + alert.Patch.Uuid); - if (string.IsNullOrEmpty(alert.Patch.Description)) - Errors.Add("Missing patch description for patch with UUID: " + alert.Patch.Uuid); - if (string.IsNullOrEmpty(alert.Patch.Url)) - Errors.Add("Missing patch webpage url for patch with UUID: " + alert.Patch.Uuid); - if (string.IsNullOrEmpty(alert.Patch.Guidance)) - Errors.Add("Missing patch guidance for patch with UUID: " + alert.Patch.Uuid); - if (string.IsNullOrEmpty(alert.Patch.TimeStamp.ToString())) - Errors.Add("Missing patch timestamp for patch with UUID: " + alert.Patch.Uuid); - } - } - } -} diff --git a/CFUValidator/Validators/HfxEligibilityValidator.cs b/CFUValidator/Validators/HfxEligibilityValidator.cs deleted file mode 100644 index d489891f04..0000000000 --- a/CFUValidator/Validators/HfxEligibilityValidator.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using XenAdmin.Core; - -namespace CFUValidator.Validators -{ - class HfxEligibilityValidator : Validator - { - private List xsversions; - - public HfxEligibilityValidator(List xsversions) - { - this.xsversions = xsversions; - } - - protected override string Header => "Running hotfix eligibility check..."; - - protected override string Footer => "Hotfix Eligibility check completed."; - - protected override string SummaryTitle => "Hotfix eligibility check:"; - - protected override void ValidateCore(Action statusReporter) - { - foreach (XenServerVersion version in xsversions) - DateSanityCheck(version); - } - - private void DateSanityCheck(XenServerVersion version) - { - if (version.HotfixEligibility == hotfix_eligibility.none && version.EolDate == DateTime.MinValue) - Errors.Add("Missing or wrong eol-date field on: " + version.Name); - if (version.HotfixEligibility == hotfix_eligibility.premium && version.HotfixEligibilityPremiumDate == DateTime.MinValue) - Errors.Add("Missing or wrong hotfix-eligibility-premium-date field on: " + version.Name); - if (version.HotfixEligibility == hotfix_eligibility.cu && version.HotfixEligibilityNoneDate == DateTime.MinValue) - Errors.Add("Missing or wrong hotfix-eligibility-none-date field on: " + version.Name); - if (version.HotfixEligibility == hotfix_eligibility.cu && version.HotfixEligibilityPremiumDate == DateTime.MinValue) - Errors.Add("Missing or wrong hotfix-eligibility-premium-date field on: " + version.Name); - } - } -} diff --git a/CFUValidator/Validators/PatchURLValidator.cs b/CFUValidator/Validators/PatchURLValidator.cs deleted file mode 100644 index 0caf2e3a7c..0000000000 --- a/CFUValidator/Validators/PatchURLValidator.cs +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Net; -using XenAdmin.Alerts; - -namespace CFUValidator.Validators -{ - class PatchURLValidator : Validator - { - private readonly List alerts; - - public PatchURLValidator(List alerts) - { - this.alerts = alerts; - } - - protected override string Header => "Checking the patch URLs return a suitable http response..."; - - protected override string Footer => "Patch URL check completed."; - - protected override string SummaryTitle => "Required patch URL checks:"; - - protected override void ValidateCore(Action statusReporter) - { - ConsoleSpinner spinner = new ConsoleSpinner(); - - using (var workerThread = new BackgroundWorker()) - { - workerThread.DoWork += CheckAllPatchURLs; - workerThread.RunWorkerAsync(); - - while (workerThread.IsBusy) - spinner.Turn(); - } - } - - private void CheckAllPatchURLs(object sender, DoWorkEventArgs e) - { - foreach (XenServerPatchAlert alert in alerts) - { - if (String.IsNullOrEmpty(alert.Patch.PatchUrl)) - { - Errors.Add($"Patch '{alert.Patch.Name}' URL is missing"); - continue; - } - - HttpWebResponse response = null; - try - { - WebRequest request = WebRequest.Create(alert.Patch.PatchUrl); - request.Method = "HEAD"; - response = request.GetResponse() as HttpWebResponse; - if (response == null || response.StatusCode != HttpStatusCode.OK) - Errors.Add($"Patch '{alert.Patch.Name}' URL '{alert.Patch.PatchUrl}' is invalid"); - } - catch (WebException ex) - { - Errors.Add($"Patch '{alert.Patch.Name}' URL '{alert.Patch.PatchUrl}' failed: {ex.Message}"); - } - finally - { - response?.Close(); - } - } - } - } -} diff --git a/CFUValidator/Validators/Validator.cs b/CFUValidator/Validators/Validator.cs deleted file mode 100644 index 3cbabb6837..0000000000 --- a/CFUValidator/Validators/Validator.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Text; -using CFUValidator.OutputDecorators; - - -namespace CFUValidator.Validators -{ - public abstract class Validator : ISummaryGenerator - { - protected List Errors { get; } = new List(); - - public void Validate(Action statusReporter) - { - statusReporter(Header); - ValidateCore(statusReporter); - statusReporter(Footer); - statusReporter(string.Empty); - } - - public string GenerateSummary() - { - var sb = new StringBuilder(); - sb.AppendLine(SummaryTitle); - - if (Errors.Count > 0) - Errors.ForEach(v => sb.AppendLine(v)); - else - sb.AppendLine("All OK"); - - return sb.ToString(); - } - - protected abstract void ValidateCore(Action statusReporter); - - protected abstract string Header { get; } - - protected abstract string Footer { get; } - - protected abstract string SummaryTitle { get; } - } -} diff --git a/CFUValidator/Validators/ZipContentsValidator.cs b/CFUValidator/Validators/ZipContentsValidator.cs deleted file mode 100644 index 85f20537a3..0000000000 --- a/CFUValidator/Validators/ZipContentsValidator.cs +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System; -using System.Linq; -using System.Collections.Generic; -using XenAdmin; -using XenAdmin.Core; -using XenAdmin.Actions; -using XenAdmin.Actions.Updates; -using XenAdmin.Alerts; - -namespace CFUValidator.Validators -{ - class ZipContentsValidator : Validator - { - private readonly List alerts; - private IConfigProvider _configProvider; - - public ZipContentsValidator(List alerts, IConfigProvider configProvider) - { - this.alerts = alerts; - _configProvider = configProvider; - } - - protected override string Header => "Downloading and checking the contents of the zip files in the patch..."; - - protected override string Footer => "Download and content check of patch zip files completed."; - - protected override string SummaryTitle => "Required patch zip content checks:"; - - protected override void ValidateCore(Action statusReporter) - { - try - { - TokenManager.GetToken(_configProvider); - - foreach (XenServerPatchAlert alert in alerts.OrderBy(a => a.Patch.Name)) - DownloadPatchFile(alert, statusReporter); - } - finally - { - TokenManager.InvalidateToken(_configProvider); - } - } - - private void DownloadPatchFile(XenServerPatchAlert patch, Action statusReporter) - { - if (string.IsNullOrEmpty(patch.Patch.PatchUrl)) - { - Errors.Add("Patch contained no URL: " + patch.Patch.Name); - return; - } - - var action = new DownloadAndUnzipUpdateAction(patch.Patch.Name, new Uri(patch.Patch.PatchUrl), - BrandManager.ExtensionUpdate, "iso"); - - try - { - statusReporter("Download and unzip patch " + patch.Patch.Name); - - ConsoleSpinner spinner = new ConsoleSpinner(); - action.RunAsync(); - while (!action.IsCompleted) - { - spinner.Turn(action.PercentComplete); - } - - if (!action.Succeeded) - Errors.Add("Patch download and unzip unsuccessful: " + action.Exception.Message); - } - catch (Exception ex) - { - Errors.Add("Patch download error: " + ex.Message); - } - } - } -} diff --git a/CFUValidator/app.config b/CFUValidator/app.config deleted file mode 100644 index 99dca7597b..0000000000 --- a/CFUValidator/app.config +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/CONTRIB b/CONTRIBUTING.md similarity index 93% rename from CONTRIB rename to CONTRIBUTING.md index 19385127c5..0191ac3508 100644 --- a/CONTRIB +++ b/CONTRIBUTING.md @@ -41,4 +41,4 @@ xs-devel@lists.xenserver.org. ---------------------------------------------------------------------------- -For a list of maintainers, please see MAINTAINERS file. \ No newline at end of file +For a list of maintainers, please see [MAINTAINERS](./MAINTAINERS.md) file. diff --git a/CommandLib/CommandLib.csproj b/CommandLib/CommandLib.csproj index eedc9f828f..c7b9c6ab4f 100644 --- a/CommandLib/CommandLib.csproj +++ b/CommandLib/CommandLib.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU diff --git a/Jenkinsfile b/Jenkinsfile index b287fa9d71..32677764e7 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,6 +1,6 @@ #!groovy -/* Copyright (c) Cloud Software Group, Inc. +/* Copyright (c) Cloud Software Group, Inc. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided @@ -30,10 +30,10 @@ * SUCH DAMAGE. */ -def XENADMIN_BRANDING_TAG = 'v5.0' +def XENADMIN_BRANDING_TAG = 'v5.3' -@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.9"]) -import com.citrix.pipeline.xencenter.* +@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.10"]) +import com.xenserver.pipeline.xencenter.* properties([ [ diff --git a/MAINTAINERS b/MAINTAINERS.md similarity index 87% rename from MAINTAINERS rename to MAINTAINERS.md index 12622e53bd..91c8dcbe9c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS.md @@ -8,4 +8,4 @@ List of maintainers ----------------------------------------------------------------------------- -For information on how to contribute to the project, please see CONTRIB file. +For information on how to contribute to the project, please see [CONTRIBUTING](./CONTRIBUTING.md) file. diff --git a/README.md b/README.md index acb4f8053c..cb6052ca1b 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ XenCenter This repository contains the source code for XenCenter. -XenCenter is a Windows-based management tool for Citrix Hypervisor environments, +XenCenter is a Windows-based management tool for XenServer and Citrix Hypervisor environments, which enables users to manage and monitor server and resource pools, and to deploy, monitor, manage, and migrate virtual machines. -XenCenter is written mostly in C#. +XenCenter is written in C#. Contributions ------------- @@ -34,7 +34,7 @@ How to build XenCenter To build XenCenter, you need * the source from xenadmin repository -* Visual Studio 2019 +* Visual Studio 2022 * .NET Framework 4.8 and also some libraries which we do not store in the source tree: @@ -54,3 +54,7 @@ To run the [NUnit](http://www.nunit.org/) tests you will need the following libr * Moq.dll which can be obtained from . + +Note that the build script assumes that you have added MSBuild's location (usually +`C:\Program Files\Microsoft Visual Studio\2022\\MSBuild\Current\Bin`) +to your `PATH` environment variable. diff --git a/WixInstaller/XenCenter.wxs b/WixInstaller/XenCenter.wxs index 3b33d7ff31..f026e6129e 100644 --- a/WixInstaller/XenCenter.wxs +++ b/WixInstaller/XenCenter.wxs @@ -1,7 +1,7 @@ - + - - + @@ -150,16 +149,16 @@ INSTALLSHORTCUT - + - + @@ -170,12 +169,12 @@ - + - + - + @@ -201,7 +200,7 @@ = "#528040")]]> - + @@ -239,9 +238,9 @@ - WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT (WixUI_InstallMode="Remove") AND XS_WixUIRMPressedOk="0" diff --git a/WixInstaller/branding.wxi b/WixInstaller/branding.wxi index b3eadb2027..b4be2e9290 100644 --- a/WixInstaller/branding.wxi +++ b/WixInstaller/branding.wxi @@ -1,7 +1,7 @@ Required Disk Size Volume -+ ++ + A newer version of this product is already installed. + Install for: + &All Users @@ -600,10 +600,10 @@ diff -ru wixlib/WixUI_FeatureTree.wxs wixlib/WixUI_FeatureTree.wxs 1 1 1 -+ ++ + 1 + 1 -+ ++ @@ -1023,4 +1023,5 @@ diff --git wixlib/MsiRMFilesInUse.wxs wixlib/MsiRMFilesInUse.wxs + 1 - 1 \ No newline at end of file + 1 + \ No newline at end of file diff --git a/XenAdmin.sln b/XenAdmin.sln index 053c7123d5..5e22eed501 100644 --- a/XenAdmin.sln +++ b/XenAdmin.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30011.22 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34003.232 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenAdmin", "XenAdmin\XenAdmin.csproj", "{70BDA4BC-F062-4302-8ACD-A15D8BF31D65}" ProjectSection(ProjectDependencies) = postProject @@ -10,8 +10,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenAdmin", "XenAdmin\XenAdm EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandLib", "CommandLib\CommandLib.csproj", "{6CE6A8FF-CF49-46B6-BEA4-6464A2F0A4D7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xva_verify", "xva_verify\xva_verify.csproj", "{2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenAdminTests", "XenAdminTests\XenAdminTests.csproj", "{21B9482C-D255-40D5-ABA7-C8F00F99547C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenCenterLib", "XenCenterLib\XenCenterLib.csproj", "{9861DFA1-B41F-432D-A43F-226257DEBBB9}" @@ -20,8 +18,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenModel", "XenModel\XenMod EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XenOvfApi", "XenOvfApi\XenOvfApi.csproj", "{2D78AC6C-B867-484A-A447-3C6FC8B8EAF7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CFUValidator", "CFUValidator\CFUValidator.csproj", "{39308480-78C3-40B4-924D-06914F343ACD}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xe", "xe\Xe.csproj", "{727E885D-14BE-40F0-9D0B-3853D44D3984}" EndProject Global @@ -58,18 +54,6 @@ Global {6CE6A8FF-CF49-46B6-BEA4-6464A2F0A4D7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {6CE6A8FF-CF49-46B6-BEA4-6464A2F0A4D7}.Release|Win32.ActiveCfg = Release|Any CPU {6CE6A8FF-CF49-46B6-BEA4-6464A2F0A4D7}.Release|Win32.Build.0 = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Win32.ActiveCfg = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Debug|Win32.Build.0 = Debug|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Any CPU.Build.0 = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Win32.ActiveCfg = Release|Any CPU - {2A70D7E7-EAB2-4C36-B3F4-85B79D2384B5}.Release|Win32.Build.0 = Release|Any CPU {21B9482C-D255-40D5-ABA7-C8F00F99547C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21B9482C-D255-40D5-ABA7-C8F00F99547C}.Debug|Any CPU.Build.0 = Debug|Any CPU {21B9482C-D255-40D5-ABA7-C8F00F99547C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -110,16 +94,6 @@ Global {2D78AC6C-B867-484A-A447-3C6FC8B8EAF7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {2D78AC6C-B867-484A-A447-3C6FC8B8EAF7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2D78AC6C-B867-484A-A447-3C6FC8B8EAF7}.Release|Win32.ActiveCfg = Release|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Debug|Win32.ActiveCfg = Debug|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Release|Any CPU.Build.0 = Release|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {39308480-78C3-40B4-924D-06914F343ACD}.Release|Win32.ActiveCfg = Release|Any CPU {727E885D-14BE-40F0-9D0B-3853D44D3984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {727E885D-14BE-40F0-9D0B-3853D44D3984}.Debug|Any CPU.Build.0 = Debug|Any CPU {727E885D-14BE-40F0-9D0B-3853D44D3984}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU diff --git a/XenAdmin/Alerts/Types/ClientUpdateAlert.cs b/XenAdmin/Alerts/Types/ClientUpdateAlert.cs index 6fcb5bc2a6..233d193240 100644 --- a/XenAdmin/Alerts/Types/ClientUpdateAlert.cs +++ b/XenAdmin/Alerts/Types/ClientUpdateAlert.cs @@ -98,7 +98,7 @@ public override bool Equals(Alert other) public static void DownloadAndInstallNewClient(ClientUpdateAlert updateAlert, IWin32Window parent) { - var outputPathAndFileName = Path.Combine(Path.GetTempPath(), $"{BrandManager.BrandConsoleNoSpace}.msi"); + var outputPathAndFileName = Path.Combine(Path.GetTempPath(), $"{BrandManager.BrandConsole}.msi"); var downloadAndInstallClientAction = new DownloadAndUpdateClientAction(updateAlert.Name, new Uri(updateAlert.NewVersion.Url), outputPathAndFileName, updateAlert.Checksum); diff --git a/XenAdmin/Alerts/Types/OutOfSyncWithCdnAlert.cs b/XenAdmin/Alerts/Types/OutOfSyncWithCdnAlert.cs index a08aadfc90..bba89f26ab 100644 --- a/XenAdmin/Alerts/Types/OutOfSyncWithCdnAlert.cs +++ b/XenAdmin/Alerts/Types/OutOfSyncWithCdnAlert.cs @@ -40,7 +40,7 @@ namespace XenAdmin.Alerts { public class OutOfSyncWithCdnAlert : Alert { - private readonly TimeSpan _outOfSyncSpan; + private readonly TimeSpan _outOfSyncSpan = TimeSpan.Zero; private readonly Pool _pool; private OutOfSyncWithCdnAlert(Pool pool, DateTime timestamp) @@ -49,12 +49,19 @@ private OutOfSyncWithCdnAlert(Pool pool, DateTime timestamp) _pool = pool; Connection = _pool.Connection; - _outOfSyncSpan = _timestamp - _pool.last_update_sync; + if (pool.last_update_sync > Util.GetUnixMinDateTime()) + { + _outOfSyncSpan = _timestamp - _pool.last_update_sync; - if (_outOfSyncSpan >= TimeSpan.FromDays(180)) - Priority = AlertPriority.Priority1; - else if (_outOfSyncSpan >= TimeSpan.FromDays(90)) - Priority = AlertPriority.Priority2; + if (_outOfSyncSpan >= TimeSpan.FromDays(180)) + Priority = AlertPriority.Priority1; + else if (_outOfSyncSpan >= TimeSpan.FromDays(90)) + Priority = AlertPriority.Priority2; + } + else + { + Priority = AlertPriority.Priority3; + } } public static bool TryCreate(IXenConnection connection, out Alert alert) @@ -79,8 +86,9 @@ public static bool TryCreate(IXenConnection connection, out Alert alert) public override string AppliesTo => Helpers.GetName(_pool); - public override string Description => string.Format(Messages.ALERT_CDN_OUT_OF_SYNC_DESCRIPTION, - AlertExtensions.GetGuiDate(_pool.last_update_sync)); + public override string Description => _outOfSyncSpan == TimeSpan.Zero + ? Messages.ALERT_CDN_NEVER_SYNC_TITLE + : string.Format(Messages.ALERT_CDN_OUT_OF_SYNC_DESCRIPTION, AlertExtensions.GetGuiDate(_pool.last_update_sync)); public override Action FixLinkAction { @@ -97,9 +105,11 @@ public override Action FixLinkAction public override string FixLinkText => Messages.UPDATES_GENERAL_TAB_SYNC_NOW; - public override string HelpID => "TODO"; + public override string HelpID => "OutOfSyncWithCdnAlert"; - public override string Title => string.Format(Messages.ALERT_CDN_OUT_OF_SYNC_TITLE, _outOfSyncSpan.Days); + public override string Title => _outOfSyncSpan == TimeSpan.Zero + ? Messages.ALERT_CDN_NEVER_SYNC_TITLE + : string.Format(Messages.ALERT_CDN_OUT_OF_SYNC_TITLE, _outOfSyncSpan.Days); } @@ -149,7 +159,7 @@ public override Action FixLinkAction public override string FixLinkText => Messages.ALERT_CDN_REPO_NOT_CONFIGURED_ACTION_LINK; - public override string HelpID => "TODO"; + public override string HelpID => "YumRepoNotConfiguredAlert"; public override string Title => string.Format(Messages.ALERT_CDN_REPO_NOT_CONFIGURED_TITLE, Connection.Name); } diff --git a/XenAdmin/ConsoleView/RdpClient.cs b/XenAdmin/ConsoleView/RdpClient.cs index 0e950bd9d8..ad291e58c9 100644 --- a/XenAdmin/ConsoleView/RdpClient.cs +++ b/XenAdmin/ConsoleView/RdpClient.cs @@ -97,6 +97,11 @@ internal RdpClient(ContainerControl parent, Size size, EventHandler resizeHandle rdpControl.Resize += resizeHandler; } + private bool _connecting; + private bool _authWarningVisible; + + public bool IsAttemptingConnection => _connecting || _authWarningVisible; + private void RDPConfigure(Size currentConsoleSize) { rdpControl.BeginInit(); @@ -104,7 +109,7 @@ private void RDPConfigure(Size currentConsoleSize) rdpControl.Dock = DockStyle.None; rdpControl.Anchor = AnchorStyles.None; rdpControl.Size = currentConsoleSize; - RDPAddOnDisconnected(); + AddRDPEventHandlers(); rdpControl.Enter += RdpEnter; rdpControl.Leave += rdpClient_Leave; rdpControl.GotFocus += rdpClient_GotFocus; @@ -123,15 +128,28 @@ public Point rdpLocationOffset } } - private void RDPAddOnDisconnected() + private void AddRDPEventHandlers() { if (rdpControl == null) return; - if (rdpClient9 == null) - rdpClient6.OnDisconnected += rdpClient_OnDisconnected; - else - rdpClient9.OnDisconnected += rdpClient_OnDisconnected; + var rdpClient = (IRdpClient)rdpClient9 ?? rdpClient6; + if (rdpClient == null) + { + return; + } + + rdpClient.OnDisconnected += (_, e) => + { + Program.AssertOnEventThread(); + OnDisconnected?.Invoke(this, EventArgs.Empty); + }; + rdpClient.OnConnected += (_, e) => _connecting = false; + rdpClient.OnConnecting += (_, e) => _connecting = true; + rdpClient.OnDisconnected += (_, e) => _connecting = _authWarningVisible = false; + rdpClient.OnAuthenticationWarningDisplayed += (_, e) => _authWarningVisible = true; + rdpClient.OnAuthenticationWarningDismissed += (_, e) => _authWarningVisible = false; + } private void RDPSetSettings() @@ -161,26 +179,43 @@ private void RDPSetSettings() } } - public void RDPConnect(string rdpIP, int w, int h) + public void RDPConnect(string rdpIP, int width, int height) { if (rdpControl == null) return; - if (rdpClient9 == null) + var rdpClientName = rdpClient9 == null ? "RDPClient6" : "RDPClient9"; + var rdpClient = (IRdpClient) rdpClient9 ?? rdpClient6; + + Log.Debug($"Connecting {rdpClientName} using server '{rdpIP}', width '{width}' and height '{height}'"); + + if (rdpClient == null) { - Log.Debug($"Connecting RDPClient6 using server '{rdpIP}', width '{w}' and height '{h}'"); - rdpClient6.Server = rdpIP; - rdpClient6.DesktopWidth = w; - rdpClient6.DesktopHeight = h; - rdpClient6.Connect(); + Log.Warn("RDPConnect called with an uninitialized RDP client. Aborting connection attempt."); + return; } - else + + rdpClient.Server = rdpIP; + rdpClient.DesktopWidth = width; + rdpClient.DesktopHeight = height; + try { - Log.Debug($"Connecting RDPClient9 using server '{rdpIP}', width '{w}' and height '{h}'"); - rdpClient9.Server = rdpIP; - rdpClient9.DesktopWidth = w; - rdpClient9.DesktopHeight = h; - rdpClient9.Connect(); + rdpClient.Connect(); + } + catch (COMException comException) + { + // The Connect method returns E_FAIL if it is called while the control is already connected or in the connecting state. + // see https://learn.microsoft.com/en-us/windows/win32/termserv/imstscax-connect#remarks for more information. + // The HRESULT value is taken from https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/705fb797-2175-4a90-b5a3-3918024b10b8 + var eFailHResultValue = Convert.ToInt32("0x80004005", 16); + if (comException.ErrorCode == eFailHResultValue) + { + Log.Warn("Attempted connection while RDP client was connected or connected already."); + } + else + { + throw; + } } } @@ -223,15 +258,6 @@ private int DesktopWidth get { return rdpControl == null ? 0 : (rdpClient9 == null ? rdpClient6.DesktopWidth : rdpClient9.DesktopWidth); } } - void rdpClient_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e) - { - Program.AssertOnEventThread(); - - if (OnDisconnected != null) - OnDisconnected(this, null); - - } - //refresh to draw focus border in correct position after display is updated void rdpClient_OnRemoteDesktopSizeChange(object sender, AxMSTSCLib.IMsTscAxEvents_OnRemoteDesktopSizeChangeEvent e) { diff --git a/XenAdmin/ConsoleView/VNCTabView.cs b/XenAdmin/ConsoleView/VNCTabView.cs index a1061a8b7b..bb3314f8c6 100644 --- a/XenAdmin/ConsoleView/VNCTabView.cs +++ b/XenAdmin/ConsoleView/VNCTabView.cs @@ -1227,7 +1227,7 @@ private void UpdateTooltipOfToggleButton() private void TryToConnectRDP(object x) { bool hasToReconnect = vncScreen.RdpIp == null; - vncScreen.RdpIp = vncScreen.PollPort(XSVNCScreen.RDP_PORT, true); + vncScreen.RdpIp = vncScreen.PollPort(XSVNCScreen.RDPPort, true); Program.Invoke(this, (MethodInvoker)(() => { if (hasToReconnect) @@ -1324,7 +1324,7 @@ private void rdpDisconnected() if (!RDPControlEnabled) toggleConsoleButton.Enabled = false; - vncScreen.imediatelyPollForConsole(); + vncScreen.ImmediatelyPollForConsole(); } internal void SwitchIfRequired() diff --git a/XenAdmin/ConsoleView/XSVNCScreen.cs b/XenAdmin/ConsoleView/XSVNCScreen.cs index 37fc8d2183..aee968e872 100644 --- a/XenAdmin/ConsoleView/XSVNCScreen.cs +++ b/XenAdmin/ConsoleView/XSVNCScreen.cs @@ -60,35 +60,35 @@ public class XSVNCScreen : UserControl private const int SHORT_RETRY_SLEEP_TIME = 100; private const int RETRY_SLEEP_TIME = 5000; private const int RDP_POLL_INTERVAL = 30000; - public const int RDP_PORT = 3389; + public const int RDPPort = 3389; private const int VNC_PORT = 5900; private const int CONSOLE_SIZE_OFFSET = 6; - private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType); - private int ConnectionRetries = 0; + private int _connectionRetries; - private volatile bool useVNC = true; + private volatile bool _useVNC = true; - private bool autoCaptureKeyboardAndMouse = true; + private readonly bool _autoCaptureKeyboardAndMouse = true; - private readonly Color focusColor = SystemColors.MenuHighlight; + private readonly Color _focusColor = SystemColors.MenuHighlight; /// /// May only be written on the event thread. May be read off the event thread, to check whether /// the VNC source has been switched during connection. /// - private volatile VNCGraphicsClient vncClient = null; + private volatile VNCGraphicsClient _vncClient; - private RdpClient rdpClient; + private RdpClient _rdpClient; - private Timer connectionPoller = null; + private Timer _connectionPoller; - private VM sourceVM = null; - private bool sourceIsPV = false; + private VM _sourceVm; + private bool _sourceIsPv; - private readonly Object hostedConsolesLock = new Object(); - private List> hostedConsoles = null; + private readonly object _hostedConsolesLock = new object(); + private List> _hostedConsoles; /// /// This is assigned when the hosted connection connects up. It's used by PollPort to check for @@ -96,8 +96,9 @@ public class XSVNCScreen : UserControl /// poll for the in-guest VNC using the same session. activeSession must be accessed only under /// the activeSessionLock. /// - private Session activeSession = null; - private readonly Object activeSessionLock = new Object(); + private Session _activeSession; + + private readonly object _activeSessionLock = new object(); /// /// Xvnc will block us if we're too quick with the disconnect and reconnect that we do @@ -106,8 +107,9 @@ public class XSVNCScreen : UserControl /// pendingVNCConnectionLock. Work under this lock must be non-blocking, because it's used on /// Dispose. /// - private Stream pendingVNCConnection = null; - private readonly Object pendingVNCConnectionLock = new Object(); + private Stream _pendingVNCConnection; + + private readonly object _pendingVNCConnectionLock = new object(); internal EventHandler ResizeHandler; @@ -116,65 +118,65 @@ public class XSVNCScreen : UserControl public event Action GpuStatusChanged; public event Action ConnectionNameChanged; - public bool RdpVersionWarningNeeded { get { return rdpClient != null && rdpClient.needsRdpVersionWarning; }} + public bool RdpVersionWarningNeeded => _rdpClient != null && _rdpClient.needsRdpVersionWarning; - internal readonly VNCTabView parentVNCTabView; + internal readonly VNCTabView ParentVNCTabView; - [DefaultValue(false)] - public bool UserWantsToSwitchProtocol { get; set; } + [DefaultValue(false)] public bool UserWantsToSwitchProtocol { get; set; } - private bool hasRDP { get { return Source != null && Source.HasRDP(); } } + private bool HasRDP => Source != null && Source.HasRDP(); /// /// Whether we have tried to login without providing a password (covers the case where the user /// has configured VNC not to require a login password). If no password is saved, passwordless /// login is tried once. /// - private bool haveTriedLoginWithoutPassword = false; - private bool ignoreNextError = false; + private bool _haveTriedLoginWithoutPassword; + + private bool _ignoreNextError; - private Dictionary cachedNetworks; + private Dictionary _cachedNetworks; /// /// The last known VNC password for this VM. /// - private char[] vncPassword = null; + private char[] _vncPassword; internal ConsoleKeyHandler KeyHandler; internal string ElevatedUsername; internal string ElevatedPassword; - internal XSVNCScreen(VM source, EventHandler resizeHandler, VNCTabView parent, string elevatedUsername, string elevatedPassword) - : base() + internal XSVNCScreen(VM source, EventHandler resizeHandler, VNCTabView parent, string elevatedUsername, + string elevatedPassword) { - this.ResizeHandler = resizeHandler; - this.parentVNCTabView = parent; - this.Source = source; - this.KeyHandler = parentVNCTabView.KeyHandler; + ResizeHandler = resizeHandler; + ParentVNCTabView = parent; + Source = source; + KeyHandler = ParentVNCTabView.KeyHandler; ElevatedUsername = elevatedUsername; ElevatedPassword = elevatedPassword; #pragma warning disable 0219 - IntPtr _ = Handle; + var _ = Handle; #pragma warning restore 0219 - initSubControl(); + InitSubControl(); //We're going to try and catch when the IP address changes for the VM, and re-scan for ports. if (source == null) return; Properties.Settings.Default.PropertyChanged += Default_PropertyChanged; - VM_guest_metrics guestMetrics = Source.Connection.Resolve(Source.guest_metrics); + var guestMetrics = Source.Connection.Resolve(Source.guest_metrics); if (guestMetrics == null) return; - cachedNetworks = guestMetrics.networks; + _cachedNetworks = guestMetrics.networks; - guestMetrics.PropertyChanged += new PropertyChangedEventHandler(guestMetrics_PropertyChanged); + guestMetrics.PropertyChanged += guestMetrics_PropertyChanged; } - void Default_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void Default_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "EnableRDPPolling") Program.Invoke(this, StartPolling); @@ -185,41 +187,41 @@ private void UnregisterEventListeners() if (Source == null) return; - Source.PropertyChanged -= new PropertyChangedEventHandler(VM_PropertyChanged); + Source.PropertyChanged -= VM_PropertyChanged; - VM_guest_metrics guestMetrics = Source.Connection.Resolve(Source.guest_metrics); + var guestMetrics = Source.Connection.Resolve(Source.guest_metrics); if (guestMetrics == null) return; - guestMetrics.PropertyChanged -= new PropertyChangedEventHandler(guestMetrics_PropertyChanged); - + guestMetrics.PropertyChanged -= guestMetrics_PropertyChanged; } - void guestMetrics_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void guestMetrics_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (Source == null) return; if (e.PropertyName == "networks") { - Dictionary newNetworks = (sender as VM_guest_metrics).networks; - if (!equateDictionary(newNetworks, cachedNetworks)) + var newNetworks = (sender as VM_guest_metrics).networks; + if (!EquateDictionary(newNetworks, _cachedNetworks)) { Log.InfoFormat("Detected IP address change in vm {0}, repolling for VNC/RDP...", Source.Name()); - cachedNetworks = newNetworks; + _cachedNetworks = newNetworks; Program.Invoke(this, StartPolling); } } } - private static bool equateDictionary(Dictionary d1, Dictionary d2) where S : IEquatable + private static bool EquateDictionary(Dictionary d1, Dictionary d2) + where TS : IEquatable { if (d1.Count != d2.Count) return false; - foreach (T key in d1.Keys) + foreach (var key in d1.Keys) { if (!d2.ContainsKey(key) || !d2[key].Equals(d1[key])) return false; @@ -228,13 +230,13 @@ private static bool equateDictionary(Dictionary d1, Dictionary return true; } - private bool wasPaused = true; + private bool _wasPaused = true; public void Pause() { if (RemoteConsole != null) { - wasPaused = true; + _wasPaused = true; RemoteConsole.Pause(); } } @@ -243,18 +245,12 @@ public void Unpause() { if (RemoteConsole != null) { - wasPaused = false; + _wasPaused = false; RemoteConsole.UnPause(); } } - public Size DesktopSize - { - get - { - return RemoteConsole != null ? RemoteConsole.DesktopSize : Size.Empty; - } - } + public Size DesktopSize => RemoteConsole?.DesktopSize ?? Size.Empty; /// /// Nothrow guarantee. @@ -265,11 +261,11 @@ protected override void Dispose(bool disposing) if (disposing) { - if (connectionPoller != null) + if (_connectionPoller != null) { - connectionPoller.Change(Timeout.Infinite, Timeout.Infinite); - connectionPoller.Dispose(); - connectionPoller = null; + _connectionPoller.Change(Timeout.Infinite, Timeout.Infinite); + _connectionPoller.Dispose(); + _connectionPoller = null; } if (RemoteConsole != null) @@ -292,7 +288,7 @@ protected override void Dispose(bool disposing) private void PollRDPPort(object sender) { - if (hasRDP) + if (HasRDP) { if (OnDetectRDP != null) Program.Invoke(this, OnDetectRDP); @@ -300,7 +296,7 @@ private void PollRDPPort(object sender) else { RdpIp = null; - var openIp = PollPort(RDP_PORT, false); + var openIp = PollPort(RDPPort, false); if (openIp == null) return; @@ -315,11 +311,11 @@ private void PollVNCPort(object sender) VncIp = null; var openIp = PollPort(VNC_PORT, true); - if (openIp == null) + if (openIp == null) return; VncIp = openIp; - connectionPoller?.Change(Timeout.Infinite, Timeout.Infinite); + _connectionPoller?.Change(Timeout.Infinite, Timeout.Infinite); if (OnDetectVNC != null) Program.Invoke(this, OnDetectVNC); @@ -378,12 +374,13 @@ public string PollPort(int port, bool vnc) } } } + ipAddresses = ipAddresses.Distinct().ToList(); ipAddresses.AddRange(ipv6Addresses); // make sure IPv4 addresses are scanned first (CA-102755) // add IP addresses for networks without PIFs ipAddresses.AddRange(ipAddressesForNetworksWithoutPifs); - ipAddresses.AddRange(ipv6AddressesForNetworksWithoutPifs); + ipAddresses.AddRange(ipv6AddressesForNetworksWithoutPifs); foreach (var ipAddress in ipAddresses) @@ -391,7 +388,7 @@ public string PollPort(int port, bool vnc) try { Log.DebugFormat("Poll port {0}:{1}", ipAddress, port); - var s = connectGuest(ipAddress, port, vm.Connection); + var s = ConnectGuest(ipAddress, port, vm.Connection); if (vnc) { Log.DebugFormat("Connected. Set Pending Vnc connection {0}:{1}", ipAddress, port); @@ -401,6 +398,7 @@ public string PollPort(int port, bool vnc) { s.Close(); } + return ipAddress; } catch (Exception exn) @@ -428,9 +426,9 @@ public string PollPort(int port, bool vnc) { // SESSION_INVALID is fine -- these will expire from time to time. // We need to invalidate the session though. - lock (activeSessionLock) + lock (_activeSessionLock) { - activeSession = null; + _activeSession = null; } break; @@ -444,6 +442,7 @@ public string PollPort(int port, bool vnc) { Log.Warn("Exception while polling VM for port " + port + ".", e); } + return null; } @@ -455,17 +454,18 @@ public string PollPort(int port, bool vnc) /// May be null private void SetPendingVNCConnection(Stream s) { - Stream old_pending; - lock (pendingVNCConnectionLock) + Stream oldPending; + lock (_pendingVNCConnectionLock) { - old_pending = pendingVNCConnection; - pendingVNCConnection = s; + oldPending = _pendingVNCConnection; + _pendingVNCConnection = s; } - if (old_pending != null) + + if (oldPending != null) { try { - old_pending.Close(); + oldPending.Close(); } catch (Exception) { @@ -474,19 +474,20 @@ private void SetPendingVNCConnection(Stream s) } } - private bool scaling; + private bool _scaling; + public bool Scaling { get { Program.AssertOnEventThread(); - return scaling; + return _scaling; } set { Program.AssertOnEventThread(); - scaling = value; + _scaling = value; if (RemoteConsole != null) RemoteConsole.Scaling = value; } @@ -494,80 +495,89 @@ public bool Scaling public IRemoteConsole RemoteConsole { - get { return vncClient != null ? (IRemoteConsole)vncClient : rdpClient; } - set + get => _vncClient != null ? (IRemoteConsole)_vncClient : _rdpClient; + set { - if (vncClient != null) - vncClient = (VNCGraphicsClient) value ; - else if (rdpClient != null) - rdpClient = (RdpClient)value; + if (_vncClient != null) + _vncClient = (VNCGraphicsClient)value; + else if (_rdpClient != null) + _rdpClient = (RdpClient)value; } } /// /// Creates the actual VNC or RDP client control. /// - private void initSubControl() + private void InitSubControl() { Program.AssertOnEventThread(); //When switch to RDP from VNC, if RDP IP is empty, do not try to switch. - if (String.IsNullOrEmpty(RdpIp) && !UseVNC && RemoteConsole != null) + if (string.IsNullOrEmpty(RdpIp) && !UseVNC && RemoteConsole != null) return; - bool wasFocused = false; - this.Controls.Clear(); + var wasFocused = false; + Controls.Clear(); //console size with some offset to accomodate focus rectangle - Size currentConsoleSize = new Size(this.Size.Width - CONSOLE_SIZE_OFFSET, this.Size.Height - CONSOLE_SIZE_OFFSET); - - // Stop the old client. + var currentConsoleSize = new Size(Size.Width - CONSOLE_SIZE_OFFSET, Size.Height - CONSOLE_SIZE_OFFSET); + if (RemoteConsole != null) { + var preventResetConsole = false; wasFocused = RemoteConsole.ConsoleControl != null && RemoteConsole.ConsoleControl.Focused; - RemoteConsole.DisconnectAndDispose(); - RemoteConsole = null; - this.vncPassword = null; + if (RemoteConsole is RdpClient client && client.IsAttemptingConnection) + { + preventResetConsole = true; + } + + if (!preventResetConsole) + { + RemoteConsole.DisconnectAndDispose(); + RemoteConsole = null; + } + + _vncPassword = null; } // Reset - haveTriedLoginWithoutPassword = false; + _haveTriedLoginWithoutPassword = false; - if (UseVNC || String.IsNullOrEmpty(RdpIp)) + if (UseVNC || string.IsNullOrEmpty(RdpIp)) { - this.AutoScroll = false; - this.AutoScrollMinSize = new Size(0, 0); + AutoScroll = false; + AutoScrollMinSize = new Size(0, 0); - vncClient = new VNCGraphicsClient(this); + _vncClient = new VNCGraphicsClient(this); - vncClient.UseSource = UseSource; - vncClient.DesktopResized += ResizeHandler; - vncClient.Resize += ResizeHandler; - vncClient.ErrorOccurred += ErrorHandler; - vncClient.ConnectionSuccess += ConnectionSuccess; - vncClient.Dock = DockStyle.Fill; + _vncClient.UseSource = UseSource; + _vncClient.DesktopResized += ResizeHandler; + _vncClient.Resize += ResizeHandler; + _vncClient.ErrorOccurred += ErrorHandler; + _vncClient.ConnectionSuccess += ConnectionSuccess; + _vncClient.Dock = DockStyle.Fill; } else { - if (rdpClient == null) + if (_rdpClient == null) { - if (this.ParentForm is FullScreenForm) - currentConsoleSize = ((FullScreenForm)ParentForm).GetContentSize(); - this.AutoScroll = true; - this.AutoScrollMinSize = oldSize; - rdpClient = new RdpClient(this, currentConsoleSize, ResizeHandler); + if (ParentForm is FullScreenForm form) + currentConsoleSize = form.GetContentSize(); + AutoScroll = true; + AutoScrollMinSize = _oldSize; + _rdpClient = new RdpClient(this, currentConsoleSize, ResizeHandler); - rdpClient.OnDisconnected += new EventHandler(parentVNCTabView.RdpDisconnectedHandler); + _rdpClient.OnDisconnected += ParentVNCTabView.RdpDisconnectedHandler; } } - if (RemoteConsole != null && RemoteConsole.ConsoleControl != null) + if (RemoteConsole?.ConsoleControl != null) { - RemoteConsole.KeyHandler = this.KeyHandler; - RemoteConsole.SendScanCodes = !this.sourceIsPV; + RemoteConsole.KeyHandler = KeyHandler; + RemoteConsole.SendScanCodes = !_sourceIsPv; RemoteConsole.Scaling = Scaling; - RemoteConsole.DisplayBorder = this.displayFocusRectangle; - SetKeyboardAndMouseCapture(autoCaptureKeyboardAndMouse); - if (wasPaused) + RemoteConsole.DisplayBorder = _displayFocusRectangle; + SetKeyboardAndMouseCapture(_autoCaptureKeyboardAndMouse); + if (_wasPaused) RemoteConsole.Pause(); else RemoteConsole.UnPause(); @@ -577,137 +587,126 @@ private void initSubControl() RemoteConsole.Activate(); } - if (GpuStatusChanged != null) - GpuStatusChanged(MustConnectRemoteDesktop()); + GpuStatusChanged?.Invoke(MustConnectRemoteDesktop()); } internal bool MustConnectRemoteDesktop() { return (UseVNC || string.IsNullOrEmpty(RdpIp)) && - Source.HasGPUPassthrough() && Source.power_state == vm_power_state.Running; + Source.HasGPUPassthrough() && Source.power_state == vm_power_state.Running; } - + private void SetKeyboardAndMouseCapture(bool value) { - if (RemoteConsole != null && RemoteConsole.ConsoleControl != null) + if (RemoteConsole?.ConsoleControl != null) RemoteConsole.ConsoleControl.TabStop = value; } private void ConnectToRemoteConsole() { - if (vncClient != null) - ThreadPool.QueueUserWorkItem(new WaitCallback(Connect), new KeyValuePair(vncClient, null)); - else if (rdpClient != null) - rdpClient.Connect(RdpIp); + if (_vncClient != null) + ThreadPool.QueueUserWorkItem(Connect, new KeyValuePair(_vncClient, null)); + else if (_rdpClient != null) + _rdpClient.Connect(RdpIp); } - void ConnectionSuccess(object sender, EventArgs e) + private void ConnectionSuccess(object sender, EventArgs e) { - ConnectionRetries = 0; + _connectionRetries = 0; if (AutoSwitchRDPLater) { if (OnDetectRDP != null) Program.Invoke(this, OnDetectRDP); AutoSwitchRDPLater = false; } - if (parentVNCTabView.IsRDPControlEnabled()) - parentVNCTabView.EnableToggleVNCButton(); - } - internal bool AutoSwitchRDPLater - { - get; - set; + if (ParentVNCTabView.IsRDPControlEnabled()) + ParentVNCTabView.EnableToggleVNCButton(); } + internal bool AutoSwitchRDPLater { get; set; } + internal bool UseVNC { - get - { - return useVNC; - } + get => _useVNC; set { - if (value != useVNC) + if (value != _useVNC) { - ConnectionRetries = 0; - useVNC = value; - scaling = false; - initSubControl(); + _connectionRetries = 0; + _useVNC = value; + _scaling = false; + InitSubControl(); // Check if we have really switched. If not, change useVNC back (CA-102755) - bool switched = true; - if (useVNC) // we wanted VNC + var switched = true; + if (_useVNC) // we wanted VNC { - if (vncClient == null && rdpClient != null) // it is actually RDP + if (_vncClient == null && _rdpClient != null) // it is actually RDP switched = false; } else // we wanted RDP { - if (rdpClient == null && vncClient != null) // it is actually VNC + if (_rdpClient == null && _vncClient != null) // it is actually VNC switched = false; } - if (!switched) + + if (!switched) { - useVNC = !useVNC; - } + _useVNC = !_useVNC; + } } } } - private volatile bool useSource = true; + private volatile bool _useSource = true; + /// /// Indicates whether to use the source or the detected vncIP /// public bool UseSource { - get - { - return useSource; - } + get => _useSource; set { - if (value != useSource) + if (value != _useSource) { - useSource = value; - ConnectionRetries = 0; - initSubControl(); + _useSource = value; + _connectionRetries = 0; + InitSubControl(); } } } private VM Source { - get - { - return this.sourceVM; - } + get => _sourceVm; set { - if (connectionPoller != null) + if (_connectionPoller != null) { - connectionPoller.Change(Timeout.Infinite, Timeout.Infinite); - connectionPoller = null; + _connectionPoller.Change(Timeout.Infinite, Timeout.Infinite); + _connectionPoller = null; } - if (sourceVM != null) + if (_sourceVm != null) { - sourceVM.PropertyChanged -= new PropertyChangedEventHandler(VM_PropertyChanged); - sourceVM = null; + _sourceVm.PropertyChanged -= VM_PropertyChanged; + _sourceVm = null; } - sourceVM = value; + _sourceVm = value; if (value != null) { - value.PropertyChanged += new PropertyChangedEventHandler(VM_PropertyChanged); + value.PropertyChanged += VM_PropertyChanged; + + _sourceIsPv = !value.IsHVM(); - sourceIsPV = !value.IsHVM(); - StartPolling(); - lock (hostedConsolesLock) + lock (_hostedConsolesLock) { - hostedConsoles = Source.consoles; + _hostedConsoles = Source.consoles; } VM_PropertyChanged(value, new PropertyChangedEventArgs("consoles")); @@ -722,10 +721,10 @@ public string ConnectionName if (Source == null) return null; - if (Source.IsControlDomainZero(out Host host)) + if (Source.IsControlDomainZero(out var host)) return string.Format(Messages.CONSOLE_HOST, host.Name()); - if (Source.IsSrDriverDomain(out SR sr)) + if (Source.IsSrDriverDomain(out var sr)) return string.Format(Messages.CONSOLE_SR_DRIVER_DOMAIN, sr.Name()); return Source.Name(); @@ -749,27 +748,31 @@ private void StartPolling() //Disable the button first, but only if in text/default console (to allow user to return to the text console - ref. CA-70314) if (InDefaultConsole()) { - parentVNCTabView.DisableToggleVNCButton(); + ParentVNCTabView.DisableToggleVNCButton(); } - if (parentVNCTabView.IsRDPControlEnabled()) + if (ParentVNCTabView.IsRDPControlEnabled()) return; if (InDefaultConsole()) { - parentVNCTabView.DisableToggleVNCButton(); + ParentVNCTabView.DisableToggleVNCButton(); } - if (Source == null || Source.IsControlDomainZero(out _)) + if (Source == null || Source.IsControlDomainZero(out _)) return; + _connectionPoller?.Dispose(); + //Start the polling again - connectionPoller = !Source.IsHVM() ? new Timer(PollVNCPort, null, RETRY_SLEEP_TIME, RDP_POLL_INTERVAL) : new Timer(PollRDPPort, null, RETRY_SLEEP_TIME, RDP_POLL_INTERVAL); + _connectionPoller = !Source.IsHVM() + ? new Timer(PollVNCPort, null, RETRY_SLEEP_TIME, RDP_POLL_INTERVAL) + : new Timer(PollRDPPort, null, RETRY_SLEEP_TIME, RDP_POLL_INTERVAL); } private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e) { - VM vm = (VM)sender; + var vm = (VM)sender; if (vm.uuid != Source.uuid) return; @@ -783,25 +786,23 @@ private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e) //If the consoles change under us then refresh hostedConsoles else if (e.PropertyName == "consoles" && vm.power_state == vm_power_state.Running && !UseSource) { - lock (hostedConsolesLock) + lock (_hostedConsolesLock) { - hostedConsoles = Source.consoles; + _hostedConsoles = Source.consoles; } } //Or if the VM legitimately turns on else if (e.PropertyName == "power_state" && vm.power_state == vm_power_state.Running) { - parentVNCTabView.VMPowerOn(); + ParentVNCTabView.VMPowerOn(); ConnectNewHostedConsole(); - if (connectionPoller != null) - connectionPoller.Change(RETRY_SLEEP_TIME, RDP_POLL_INTERVAL); + _connectionPoller?.Change(RETRY_SLEEP_TIME, RDP_POLL_INTERVAL); } else if (e.PropertyName == "power_state" && - (vm.power_state == vm_power_state.Halted || vm.power_state == vm_power_state.Suspended)) + (vm.power_state == vm_power_state.Halted || vm.power_state == vm_power_state.Suspended)) { - parentVNCTabView.VMPowerOff(); - if (connectionPoller != null) - connectionPoller.Change(Timeout.Infinite, Timeout.Infinite); + ParentVNCTabView.VMPowerOff(); + _connectionPoller?.Change(Timeout.Infinite, Timeout.Infinite); } else if (e.PropertyName == "domid") { @@ -811,39 +812,35 @@ private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e) if (e.PropertyName == "power_state" || e.PropertyName == "VGPUs") { - Program.Invoke(this, () => - { - if (GpuStatusChanged != null) - GpuStatusChanged(MustConnectRemoteDesktop()); - }); + Program.Invoke(this, () => { GpuStatusChanged?.Invoke(MustConnectRemoteDesktop()); }); } if (e.PropertyName == "name_label" && ConnectionNameChanged != null) ConnectionNameChanged(ConnectionName); } - internal void imediatelyPollForConsole() + internal void ImmediatelyPollForConsole() { - if (connectionPoller != null) - connectionPoller.Change(0, RDP_POLL_INTERVAL); + _connectionPoller?.Change(0, RDP_POLL_INTERVAL); } private void ConnectNewHostedConsole() { Program.AssertOnEventThread(); - lock (hostedConsolesLock) + lock (_hostedConsolesLock) { - hostedConsoles = Source.consoles; + _hostedConsoles = Source.consoles; } - if (UseVNC && vncClient != null && ConnectionSuperceded()) + + if (UseVNC && _vncClient != null && ConnectionSuperseded()) { - initSubControl(); + InitSubControl(); } } /// - /// A connection is superceded if it's connected to a console that's no longer being + /// A connection is superseded if it's connected to a console that's no longer being /// advertised by the server and there's a replacement that _is_ being advertised, or /// if its not connected at all. /// @@ -851,38 +848,41 @@ private void ConnectNewHostedConsole() /// For this reason, we need to close down ourselves when we see that the console has /// been replaced by a newer one (i.e. after a reboot). /// - private bool ConnectionSuperceded() + private bool ConnectionSuperseded() { - return !vncClient.Connected || ConsoleSuperceded((Console)vncClient.Console); + return !_vncClient.Connected || ConsoleSuperseded((Console)_vncClient.Console); } - private bool ConsoleSuperceded(Console old_console) + private bool ConsoleSuperseded(Console oldConsole) { - if (old_console == null) + if (oldConsole == null) return true; List consoles; - lock (hostedConsolesLock) + lock (_hostedConsolesLock) { - consoles = Source.Connection.ResolveAll(hostedConsoles); + consoles = Source.Connection.ResolveAll(_hostedConsoles); } - bool good_console = false; - foreach (Console console in consoles) + + var goodConsole = false; + foreach (var console in consoles) { - if (console.opaque_ref == old_console.opaque_ref && - console.location == old_console.location) + if (console.opaque_ref == oldConsole.opaque_ref && + console.location == oldConsole.location) return false; else if (console.protocol == console_protocol.rfb) - good_console = true; + goodConsole = true; } - return good_console; + + return goodConsole; } /// /// CA-11201: GUI logs are being massively spammed. Prevent "INTERNAL_ERROR Host has disappeared" /// appearing more than once. /// - private bool _suppressHostGoneMessage = false; + private bool _suppressHostGoneMessage; + private void Connect(object o) { if (Program.RunInAutomatedTestMode) @@ -890,24 +890,24 @@ private void Connect(object o) Program.AssertOffEventThread(); - KeyValuePair kvp = (KeyValuePair)o; + var kvp = (KeyValuePair)o; - VNCGraphicsClient v = kvp.Key; - Exception error = kvp.Value; + var v = kvp.Key; + var error = kvp.Value; try { if (UseSource) { List consoles; - lock (hostedConsolesLock) + lock (_hostedConsolesLock) { - consoles = sourceVM.Connection.ResolveAll(hostedConsoles); + consoles = _sourceVm.Connection.ResolveAll(_hostedConsoles); } - foreach (Console console in consoles) + foreach (var console in consoles) { - if (vncClient != v) + if (_vncClient != v) { // We've been replaced. Give up. return; @@ -922,11 +922,12 @@ private void Connect(object o) } catch (Exception exn) { - Failure failure = exn as Failure; - bool isHostGoneMessage = failure != null - && failure.ErrorDescription.Count == 2 - && failure.ErrorDescription[0] == Failure.INTERNAL_ERROR - && failure.ErrorDescription[1] == string.Format(Messages.HOST_GONE, BrandManager.BrandConsole); + var failure = exn as Failure; + var isHostGoneMessage = failure != null + && failure.ErrorDescription.Count == 2 + && failure.ErrorDescription[0] == Failure.INTERNAL_ERROR + && failure.ErrorDescription[1] == + string.Format(Messages.HOST_GONE, BrandManager.BrandConsole); if (isHostGoneMessage) { @@ -956,18 +957,17 @@ private void Connect(object o) OnVncConnectionAttemptCancelled(); return; } - this.vncPassword = Settings.GetVNCPassword(sourceVM.uuid); - if (this.vncPassword == null) + + _vncPassword = Settings.GetVNCPassword(_sourceVm.uuid); + if (_vncPassword == null) { - bool lifecycleOperationInProgress = sourceVM.current_operations.Values.Any(VM.is_lifecycle_operation); - if (haveTriedLoginWithoutPassword && !lifecycleOperationInProgress) + var lifecycleOperationInProgress = + _sourceVm.current_operations.Values.Any(VM.is_lifecycle_operation); + if (_haveTriedLoginWithoutPassword && !lifecycleOperationInProgress) { - Program.Invoke(this, delegate - { - promptForPassword(ignoreNextError ? null : error); - }); - ignoreNextError = false; - if (this.vncPassword == null) + Program.Invoke(this, delegate { PromptForPassword(_ignoreNextError ? null : error); }); + _ignoreNextError = false; + if (_vncPassword == null) { Log.Debug("User cancelled VNC password prompt: aborting connection attempt"); OnUserCancelledAuth(); @@ -977,30 +977,32 @@ private void Connect(object o) else { Log.Debug("Attempting passwordless VNC login"); - this.vncPassword = new char[0]; - ignoreNextError = true; - haveTriedLoginWithoutPassword = true; + _vncPassword = Array.Empty(); + _ignoreNextError = true; + _haveTriedLoginWithoutPassword = true; } } Stream s; - lock (pendingVNCConnectionLock) + lock (_pendingVNCConnectionLock) { - s = pendingVNCConnection; + s = _pendingVNCConnection; Log.DebugFormat("Using pending VNC connection"); - pendingVNCConnection = null; + _pendingVNCConnection = null; } + if (s == null) { - Log.DebugFormat("Connecting to vncIP={0}, port={1}", this.VncIp, VNC_PORT); - s = connectGuest(this.VncIp, VNC_PORT, sourceVM.Connection); - Log.DebugFormat("Connected to vncIP={0}, port={1}", this.VncIp, VNC_PORT); + Log.DebugFormat("Connecting to vncIP={0}, port={1}", VncIp, VNC_PORT); + s = ConnectGuest(VncIp, VNC_PORT, _sourceVm.Connection); + Log.DebugFormat("Connected to vncIP={0}, port={1}", VncIp, VNC_PORT); } + InvokeConnection(v, s, null); // store the empty vnc password after a successful passwordless login - if (haveTriedLoginWithoutPassword && this.vncPassword.Length == 0) - Program.Invoke(this, () => Settings.SetVNCPassword(sourceVM.uuid, this.vncPassword)); + if (_haveTriedLoginWithoutPassword && _vncPassword.Length == 0) + Program.Invoke(this, () => Settings.SetVNCPassword(_sourceVm.uuid, _vncPassword)); } } catch (Exception exn) @@ -1010,19 +1012,19 @@ private void Connect(object o) } } - private void promptForPassword(Exception error) + private void PromptForPassword(Exception error) { Program.AssertOnEventThread(); // Prompt for password - VNCPasswordDialog f = new VNCPasswordDialog(error, sourceVM); + var f = new VNCPasswordDialog(error, _sourceVm); try { if (f.ShowDialog(this) == DialogResult.OK) { // Store password for next time - this.vncPassword = f.Password; - Settings.SetVNCPassword(sourceVM.uuid, this.vncPassword); + _vncPassword = f.Password; + Settings.SetVNCPassword(_sourceVm.uuid, _vncPassword); } else { @@ -1040,8 +1042,7 @@ private void OnUserCancelledAuth() Program.Invoke(this, delegate { Log.Debug("User cancelled during VNC authentication"); - if (UserCancelledAuth != null) - UserCancelledAuth(this, null); + UserCancelledAuth?.Invoke(this, null); }); } @@ -1050,40 +1051,41 @@ private void OnVncConnectionAttemptCancelled() Program.Invoke(this, delegate { Log.Debug("Cancelled VNC connection attempt"); - if (VncConnectionAttemptCancelled != null) - VncConnectionAttemptCancelled(this, null); + VncConnectionAttemptCancelled?.Invoke(this, null); }); } - private Stream connectGuest(string ip_address, int port, IXenConnection connection) + private static Stream ConnectGuest(string ipAddress, int port, IXenConnection connection) { - string uriString = String.Format("http://{0}:{1}/", ip_address, port); - Log.DebugFormat("Trying to connect to: {0}", uriString); - return HTTP.ConnectStream(new Uri(uriString), XenAdminConfigManager.Provider.GetProxyFromSettings(connection), true, 0); + var uriString = $"http://{ipAddress}:{port}/"; + Log.DebugFormat("Trying to connect to: {0}", uriString); + return HTTP.ConnectStream(new Uri(uriString), + XenAdminConfigManager.Provider.GetProxyFromSettings(connection), true, 0); } private void ConnectHostedConsole(VNCGraphicsClient v, Console console) { Program.AssertOffEventThread(); - Host host = console.Connection.Resolve(Source.resident_on); + var host = console.Connection.Resolve(Source.resident_on); if (host == null) { throw new Failure(Failure.INTERNAL_ERROR, string.Format(Messages.HOST_GONE, BrandManager.BrandConsole)); } - Uri uri = new Uri(console.location); - string sesssionRef; + var uri = new Uri(console.location); + string sessionRef; - lock (activeSessionLock) + lock (_activeSessionLock) { // use the elevated credentials, if provided, for connecting to the console (CA-91132) - activeSession = (string.IsNullOrEmpty(ElevatedUsername) || string.IsNullOrEmpty(ElevatedPassword)) ? - console.Connection.DuplicateSession() : console.Connection.ElevatedSession(ElevatedUsername, ElevatedPassword); - sesssionRef = activeSession.opaque_ref; + _activeSession = (string.IsNullOrEmpty(ElevatedUsername) || string.IsNullOrEmpty(ElevatedPassword)) + ? console.Connection.DuplicateSession() + : console.Connection.ElevatedSession(ElevatedUsername, ElevatedPassword); + sessionRef = _activeSession.opaque_ref; } - Stream stream = HTTPHelper.CONNECT(uri, console.Connection, sesssionRef, false); + var stream = HTTPHelper.CONNECT(uri, console.Connection, sessionRef, false); InvokeConnection(v, stream, console); } @@ -1103,20 +1105,20 @@ private void InvokeConnection(VNCGraphicsClient v, Stream stream, Console consol } else { - v.SendScanCodes = UseSource && !this.sourceIsPV; - v.SourceVM = sourceVM; + v.SendScanCodes = UseSource && !_sourceIsPv; + v.SourceVM = _sourceVm; v.Console = console; - v.UseQemuExtKeyEncoding = sourceVM != null && Helpers.InvernessOrGreater(sourceVM.Connection); - v.Connect(stream, this.vncPassword); + v.UseQemuExtKeyEncoding = _sourceVm != null && Helpers.InvernessOrGreater(_sourceVm.Connection); + v.Connect(stream, _vncPassword); } }); } private void RetryConnection(VNCGraphicsClient v, Exception exn) { - if (vncClient == v && !v.Terminated && Source.power_state == vm_power_state.Running) + if (_vncClient == v && !v.Terminated && Source.power_state == vm_power_state.Running) { - ThreadPool.QueueUserWorkItem(new WaitCallback(Connect), new KeyValuePair(v, exn)); + ThreadPool.QueueUserWorkItem(Connect, new KeyValuePair(v, exn)); } } @@ -1124,31 +1126,28 @@ public void SendCAD() { Program.AssertOnEventThread(); - if (RemoteConsole != null) - { - RemoteConsole.SendCAD(); - } + RemoteConsole?.SendCAD(); } - private String errorMessage = null; + private string _errorMessage; private void ErrorHandler(object sender, Exception exn) { Program.AssertOffEventThread(); - if (this.Disposing || this.IsDisposed) + if (Disposing || IsDisposed) return; Program.Invoke(this, delegate() { - VNCGraphicsClient v = (VNCGraphicsClient)sender; + var v = (VNCGraphicsClient)sender; if (exn is VNCAuthenticationException || exn is CryptographicException) { Log.Debug(exn, exn); // Clear the stored VNC password for this server. - Settings.SetVNCPassword(sourceVM.uuid, null); + Settings.SetVNCPassword(_sourceVm.uuid, null); RetryConnection(v, exn); } else if (exn is IOException || exn is Failure) @@ -1159,45 +1158,45 @@ private void ErrorHandler(object sender, Exception exn) else { Log.Warn(exn, exn); - this.errorMessage = exn.Message; + _errorMessage = exn.Message; } }); } - private void SleepAndRetryConnection_(VNCGraphicsClient v) + private void SleepAndRetryConnection_(IDisposable v) { - ThreadPool.QueueUserWorkItem(new WaitCallback(SleepAndRetryConnection), v); + ThreadPool.QueueUserWorkItem(SleepAndRetryConnection, v); } private void SleepAndRetryConnection(object o) { - VNCGraphicsClient v = (VNCGraphicsClient)o; + var v = (VNCGraphicsClient)o; Program.AssertOffEventThread(); - ConnectionRetries++; - Thread.Sleep(ConnectionRetries < SHORT_RETRY_COUNT ? SHORT_RETRY_SLEEP_TIME : RETRY_SLEEP_TIME); + _connectionRetries++; + Thread.Sleep(_connectionRetries < SHORT_RETRY_COUNT ? SHORT_RETRY_SLEEP_TIME : RETRY_SLEEP_TIME); RetryConnection(v, null); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - if (this.errorMessage != null) + if (_errorMessage != null) { - SizeF size = e.Graphics.MeasureString(this.errorMessage, this.Font); - e.Graphics.DrawString(this.errorMessage, this.Font, Brushes.Black, - ((this.Width - size.Width) / 2), ((this.Height - size.Height) / 2)); + var size = e.Graphics.MeasureString(_errorMessage, Font); + e.Graphics.DrawString(_errorMessage, Font, Brushes.Black, + ((Width - size.Width) / 2), ((Height - size.Height) / 2)); } // draw focus rectangle - if (DisplayFocusRectangle && this.ContainsFocus && RemoteConsole != null) + if (DisplayFocusRectangle && ContainsFocus && RemoteConsole != null) { - Rectangle focusRect = Rectangle.Inflate(RemoteConsole.ConsoleBounds, VNCGraphicsClient.BORDER_PADDING / 2, - VNCGraphicsClient.BORDER_PADDING / 2); - using (Pen pen = new Pen(focusColor, VNCGraphicsClient.BORDER_WIDTH)) + var focusRect = Rectangle.Inflate(RemoteConsole.ConsoleBounds, VNCGraphicsClient.BORDER_PADDING / 2, + VNCGraphicsClient.BORDER_PADDING / 2); + using (var pen = new Pen(_focusColor, VNCGraphicsClient.BORDER_WIDTH)) { - if (this.Focused) + if (Focused) pen.DashStyle = DashStyle.Dash; e.Graphics.DrawRectangle(pen, focusRect); } @@ -1205,35 +1204,30 @@ protected override void OnPaint(PaintEventArgs e) } // Save this for when we init a new vncClient. - private bool displayFocusRectangle = true; + private bool _displayFocusRectangle = true; + public bool DisplayFocusRectangle { - get { return displayFocusRectangle; } + get => _displayFocusRectangle; set { - displayFocusRectangle = value; + _displayFocusRectangle = value; if (RemoteConsole != null) { - RemoteConsole.DisplayBorder = displayFocusRectangle; + RemoteConsole.DisplayBorder = _displayFocusRectangle; } } } internal Image Snapshot() { - if (RemoteConsole != null) - return RemoteConsole.Snapshot(); - - return null; + return RemoteConsole?.Snapshot(); } internal void RefreshScreen() { Program.AssertOnEventThread(); - if (RemoteConsole != null && RemoteConsole.ConsoleControl != null) - { - RemoteConsole.ConsoleControl.Refresh(); - } + RemoteConsole?.ConsoleControl?.Refresh(); Invalidate(); Update(); } @@ -1244,7 +1238,6 @@ protected override void OnGotFocus(EventArgs e) base.OnGotFocus(e); RefreshScreen(); - } protected override void OnLostFocus(EventArgs e) @@ -1252,17 +1245,17 @@ protected override void OnLostFocus(EventArgs e) Program.AssertOnEventThread(); base.OnLostFocus(e); - this.pressedKeys = new Set(); + _pressedKeys = new Set(); // reset tab stop - SetKeyboardAndMouseCapture(autoCaptureKeyboardAndMouse); + SetKeyboardAndMouseCapture(_autoCaptureKeyboardAndMouse); RefreshScreen(); } protected override void OnEnter(EventArgs e) { - Program.AssertOnEventThread(); + Program.AssertOnEventThread(); base.OnEnter(e); CaptureKeyboardAndMouse(); @@ -1275,19 +1268,20 @@ protected override void OnLeave(EventArgs e) base.OnLeave(e); // reset tab stop - SetKeyboardAndMouseCapture(autoCaptureKeyboardAndMouse); + SetKeyboardAndMouseCapture(_autoCaptureKeyboardAndMouse); RefreshScreen(); } internal void UncaptureKeyboardAndMouse() { - if (autoCaptureKeyboardAndMouse) + if (_autoCaptureKeyboardAndMouse) { SetKeyboardAndMouseCapture(false); } + ActiveControl = null; - + EnableMenuShortcuts(); } @@ -1296,10 +1290,11 @@ internal void CaptureKeyboardAndMouse() if (RemoteConsole != null) { RemoteConsole.Activate(); - if (autoCaptureKeyboardAndMouse) + if (_autoCaptureKeyboardAndMouse) { SetKeyboardAndMouseCapture(true); } + Unpause(); } @@ -1316,17 +1311,17 @@ public static void EnableMenuShortcuts() Program.MainWindow.MenuShortcutsEnabled = true; } - private Set pressedKeys = new Set(); - private bool modifierKeyPressedAlone = false; - + private Set _pressedKeys = new Set(); + private bool _modifierKeyPressedAlone; + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { const int WM_KEYDOWN = 0x100; const int WM_SYSKEYDOWN = 0x104; - bool down = ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN)); + var down = ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN)); - Keys key = keyData; + var key = keyData; if ((key & Keys.Control) == Keys.Control) key = key & ~Keys.Control; @@ -1338,24 +1333,25 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) key = key & ~Keys.Shift; // use TranslateKeyMessage to identify if Left or Right modifier keys have been pressed/released - Keys extKey = ConsoleKeyHandler.TranslateKeyMessage(msg); + var extKey = ConsoleKeyHandler.TranslateKeyMessage(msg); - return Keysym(down, key, extKey); + return KeySym(down, key, extKey); } protected override void OnKeyUp(KeyEventArgs e) { - e.Handled = Keysym(false, e.KeyCode, e.KeyCode); + e.Handled = KeySym(false, e.KeyCode, e.KeyCode); } - private bool Keysym(bool pressed, Keys key, Keys extendedKey) + private bool KeySym(bool pressed, Keys key, Keys extendedKey) { - if (!pressed && pressedKeys.Count == 0) // we received key-up, but not key-down - ignore + if (!pressed && _pressedKeys.Count == 0) // we received key-up, but not key-down - ignore return true; - if (KeyHandler.handleExtras(pressed, pressedKeys, KeyHandler.ExtraKeys, extendedKey, KeyHandler.ModifierKeys, ref modifierKeyPressedAlone)) + if (KeyHandler.handleExtras(pressed, _pressedKeys, KeyHandler.ExtraKeys, extendedKey, + KeyHandler.ModifierKeys, ref _modifierKeyPressedAlone)) { - this.Focus(); + Focus(); return true; } @@ -1363,32 +1359,34 @@ private bool Keysym(bool pressed, Keys key, Keys extendedKey) // we need to do this here, because we cannot otherwise distinguish between Left and Right modifier keys on KeyUp if (!pressed) { - List extendedKeys = ConsoleKeyHandler.GetExtendedKeys(key); + var extendedKeys = ConsoleKeyHandler.GetExtendedKeys(key); foreach (var k in extendedKeys) { - pressedKeys.Remove(k); + _pressedKeys.Remove(k); } } if (key == Keys.Tab || (key == (Keys.Tab | Keys.Shift))) - return false; + return false; return false; } - private Size oldSize; + private Size _oldSize; + public void UpdateRDPResolution(bool fullscreen = false) { - if (rdpClient == null || oldSize.Equals(this.Size)) + if (_rdpClient == null || _oldSize.Equals(Size)) return; //no offsets in fullscreen mode because there is no need to accomodate focus border if (fullscreen) - rdpClient.UpdateDisplay(this.Size.Width, this.Size.Height, new Point(0,0)); + _rdpClient.UpdateDisplay(Size.Width, Size.Height, new Point(0, 0)); else - rdpClient.UpdateDisplay(this.Size.Width - CONSOLE_SIZE_OFFSET, this.Size.Height - CONSOLE_SIZE_OFFSET, new Point(3,3)); - oldSize = new Size(this.Size.Width, this.Size.Height); + _rdpClient.UpdateDisplay(Size.Width - CONSOLE_SIZE_OFFSET, Size.Height - CONSOLE_SIZE_OFFSET, + new Point(3, 3)); + _oldSize = new Size(Size.Width, Size.Height); Refresh(); } } -} +} \ No newline at end of file diff --git a/XenAdmin/Controls/ComboBoxes/VgpuComboBox.cs b/XenAdmin/Controls/ComboBoxes/VgpuComboBox.cs index 313acc30cd..80538dc8b8 100644 --- a/XenAdmin/Controls/ComboBoxes/VgpuComboBox.cs +++ b/XenAdmin/Controls/ComboBoxes/VgpuComboBox.cs @@ -145,7 +145,7 @@ private void UpdateDisplayName() if (GpuGroup == null) { //this refers to the item "None" - displayName = Messages.GPU_NONE; + displayName = Messages.NONE_UPPER; } else if (VgpuTypes == null || VgpuTypes.Length == 0 || VgpuTypes[0] == null) { diff --git a/XenAdmin/Controls/CustomDataGraph/ArchiveMaintainer.cs b/XenAdmin/Controls/CustomDataGraph/ArchiveMaintainer.cs index d9a020f95c..bb762a4b0a 100644 --- a/XenAdmin/Controls/CustomDataGraph/ArchiveMaintainer.cs +++ b/XenAdmin/Controls/CustomDataGraph/ArchiveMaintainer.cs @@ -30,10 +30,9 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; -using System.IO; using System.Linq; -using System.Net; using System.Threading; using System.Xml; using XenAPI; @@ -42,224 +41,240 @@ namespace XenAdmin.Controls.CustomDataGraph { [Flags] - public enum ArchiveInterval { None = 0, FiveSecond = 1, OneMinute = 2, OneHour = 4, OneDay = 8 } - - public class ArchiveMaintainer + public enum ArchiveInterval { - private const long TicksInOneSecond = 10000000; - private const long TicksInFiveSeconds = 50000000; - internal const long TicksInTenSeconds = 100000000; - private const long TicksInOneMinute = 600000000; - internal const long TicksInTenMinutes = 6000000000; - private const long TicksInOneHour = 36000000000; - internal const long TicksInTwoHours = 72000000000; - private const long TicksInOneDay = 864000000000; - internal const long TicksInSevenDays = 6048000000000; - internal const long TicksInOneYear = 316224000000000; - - private const int FiveSecondsInTenMinutes = 120; - private const int MinutesInTwoHours = 120; - private const int HoursInOneWeek = 168; - private const int DaysInOneYear = 366; - - private static readonly TimeSpan FiveSeconds = TimeSpan.FromSeconds(5); - private static readonly TimeSpan OneMinute = TimeSpan.FromMinutes(1); - private static readonly TimeSpan OneHour = TimeSpan.FromHours(1); - private static readonly TimeSpan OneDay = TimeSpan.FromDays(1); - - private const int SleepTime = 5000; - - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Fired (on a background thread) when new performance data are received from the server - /// - internal event Action ArchivesUpdated; - - internal readonly Dictionary Archives = new Dictionary(); - - /// - /// for pausing the retrieval of updates - /// call Monitor.PulseAll(UpdateMonitor) on resume - /// - private readonly object UpdateMonitor = new object(); - /// - /// for waiting between updates - /// the Monitor has a timeout too so we either wait for 'SleepTime' or a pulseall on WaitUpdates - /// - private readonly object WaitUpdates = new object(); - - private Thread UpdaterThread; - - /// - /// if true UpdaterThread will keep looping - /// - private bool RunThread; - /// - /// Whether the thread is started or not - /// - private bool ThreadRunning; - - /// - /// collection for holding updates whil - /// - private List SetsAdded; - - private List _dataSources = new List(); - - private IXenObject _xenObject; - - private long EndTime; - private bool BailOut; - private long CurrentInterval; - private long StepSize; - private long CurrentTime; - private int ValueCount; - private string LastNode = ""; + None = 0, + FiveSecond = 1, + OneMinute = 2, + OneHour = 4, + OneDay = 8 + } - /// - /// Gui Thread - /// - public IXenObject XenObject - { - private get { return _xenObject; } - set - { - Program.AssertOnEventThread(); + public class ArchiveMaintainer : IDisposable + { + private static readonly log4net.ILog Log = + log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType); - string oldref = _xenObject == null ? "" : _xenObject.opaque_ref; - _xenObject = value; - string newref = _xenObject == null ? "" : _xenObject.opaque_ref; - FirstTime = FirstTime || newref != oldref; - } - } + public IXenObject XenObject { get; } public DateTime LastFiveSecondCollection = DateTime.MinValue; public DateTime LastOneMinuteCollection = DateTime.MinValue; public DateTime LastOneHourCollection = DateTime.MinValue; public DateTime LastOneDayCollection = DateTime.MinValue; - public bool FirstTime = true; + public DateTime GraphNow => DateTime.Now - (ClientServerOffset + TimeSpan.FromSeconds(15)); + public TimeSpan ClientServerOffset => XenObject?.Connection.ServerTimeOffset ?? TimeSpan.Zero; public bool LoadingInitialData; - private DateTime ServerNow => DateTime.UtcNow.Subtract(ClientServerOffset); + internal const long TICKS_IN_ONE_SECOND = 10000000; + internal const long TICKS_IN_FIVE_SECONDS = 50000000; + internal const long TICKS_IN_ONE_MINUTE = 600000000; + internal const long TICKS_IN_TEN_MINUTES = 6000000000; + internal const long TICKS_IN_ONE_HOUR = 36000000000; + internal const long TICKS_IN_TWO_HOURS = 72000000000; + internal const long TICKS_IN_ONE_DAY = 864000000000; + internal const long TICKS_IN_SEVEN_DAYS = 6048000000000; + internal const long TICKS_IN_ONE_YEAR = 316224000000000; + + internal const int FIVE_SECONDS_IN_TEN_MINUTES = 120; + internal const int MINUTES_IN_TWO_HOURS = 120; + internal const int HOURS_IN_ONE_WEEK = 168; + internal const int DAYS_IN_ONE_YEAR = 366; - public DateTime GraphNow => DateTime.Now - (ClientServerOffset + TimeSpan.FromSeconds(15)); + internal event Action ArchivesUpdated; - public TimeSpan ClientServerOffset => XenObject?.Connection.ServerTimeOffset ?? TimeSpan.Zero; + internal readonly Dictionary Archives = + new Dictionary(); - public ArchiveMaintainer() - { - Archives.Add(ArchiveInterval.FiveSecond, new DataArchive(FiveSecondsInTenMinutes + 4)); - Archives.Add(ArchiveInterval.OneMinute, new DataArchive(MinutesInTwoHours)); - Archives.Add(ArchiveInterval.OneHour, new DataArchive(HoursInOneWeek)); - Archives.Add(ArchiveInterval.OneDay, new DataArchive(DaysInOneYear)); - Archives.Add(ArchiveInterval.None, new DataArchive(0)); + private const int SLEEP_TIME = 5000; - UpdaterThread = new Thread(Update) {Name = "Archive Maintainer", IsBackground = true}; - } + private volatile bool _requestedCancellation; + private volatile bool _running; - /// - /// Call me, async update graph data set - /// UpdaterThread Thread - /// - private void Update() + private readonly object _runningLock = new object(); + private bool RequestedCancellation { - while (RunThread) + get { - IXenObject xenObject = XenObject; - - DateTime serverWas = ServerNow; // get time before updating so we don't miss any 5 second updates if getting the past data + lock (_runningLock) + { + return _requestedCancellation; + } + } + set + { + lock (_runningLock) + { + _requestedCancellation = value; + } + } + } - if (FirstTime) + private bool Running + { + get + { + lock (_runningLock) { - // Restrict to at most 24 hours data if necessary - if (Helpers.FeatureForbidden(_xenObject, XenAPI.Host.RestrictPerformanceGraphs)) - { - Archives[ArchiveInterval.OneHour].MaxPoints = 24; - Archives[ArchiveInterval.OneDay].MaxPoints = 0; - } - else - { - Archives[ArchiveInterval.OneHour].MaxPoints = HoursInOneWeek; - Archives[ArchiveInterval.OneDay].MaxPoints = DaysInOneYear; - } + return _running; + } + } + set + { + lock (_runningLock) + { + _running = value; + } + } + } - _dataSources.Clear(); - foreach (DataArchive a in Archives.Values) - a.ClearSets(); + private List _setsAdded; + private List _dataSources = new List(); + private DateTime ServerNow => DateTime.UtcNow.Subtract(ClientServerOffset); + private long _endTime; + private bool _bailOut; + private long _currentInterval; + private long _stepSize; + private long _currentTime; + private int _valueCount; + private string _lastNode = string.Empty; + + public ArchiveMaintainer(IXenObject xenObject) + { + Archives.Add(ArchiveInterval.FiveSecond, new DataArchive(FIVE_SECONDS_IN_TEN_MINUTES + 4)); + Archives.Add(ArchiveInterval.OneMinute, new DataArchive(MINUTES_IN_TWO_HOURS)); + Archives.Add(ArchiveInterval.OneHour, new DataArchive(HOURS_IN_ONE_WEEK)); + Archives.Add(ArchiveInterval.OneDay, new DataArchive(DAYS_IN_ONE_YEAR)); + Archives.Add(ArchiveInterval.None, new DataArchive(0)); - LoadingInitialData = true; - ArchivesUpdated?.Invoke(); + XenObject = xenObject; + } - try - { - if (xenObject is Host h) - _dataSources = Host.get_data_sources(h.Connection.Session, h.opaque_ref); - else if (xenObject is VM vm && vm.power_state == vm_power_state.Running) - _dataSources = VM.get_data_sources(vm.Connection.Session, vm.opaque_ref); + private void StartUpdateLoop(object _) + { + var serverWas = ServerNow; + InitialLoad(serverWas); - Get(ArchiveInterval.None, RrdsUri, RRD_Full_InspectCurrentNode, xenObject); - } - catch (Exception e) - { - //Get handles its own exception; - //anything caught here is thrown by the get_data_sources operations - log.Error($"Failed to retrieve data sources for '{xenObject.Name()}'", e); - } - finally - { - LoadingInitialData = false; - ArchivesUpdated?.Invoke(); - } + while (!RequestedCancellation) + { + serverWas = ServerNow; + if (serverWas - LastFiveSecondCollection > TimeSpan.FromSeconds(5)) + { + Get(ArchiveInterval.FiveSecond, UpdateUri, RRD_Update_InspectCurrentNode, XenObject); - LastFiveSecondCollection = serverWas; - LastOneMinuteCollection = serverWas; - LastOneHourCollection = serverWas; - LastOneDayCollection = serverWas; - FirstTime = false; - } + if (RequestedCancellation) + break; - if (serverWas - LastFiveSecondCollection > FiveSeconds) - { - Get(ArchiveInterval.FiveSecond, UpdateUri, RRD_Update_InspectCurrentNode, xenObject); LastFiveSecondCollection = serverWas; - Archives[ArchiveInterval.FiveSecond].Load(SetsAdded); + Archives[ArchiveInterval.FiveSecond].Load(_setsAdded); } - if (serverWas - LastOneMinuteCollection > OneMinute) + + if (serverWas - LastOneMinuteCollection > TimeSpan.FromMinutes(1)) { - Get(ArchiveInterval.OneMinute, UpdateUri, RRD_Update_InspectCurrentNode, xenObject); + Get(ArchiveInterval.OneMinute, UpdateUri, RRD_Update_InspectCurrentNode, XenObject); + + if (RequestedCancellation) + break; + LastOneMinuteCollection = serverWas; - Archives[ArchiveInterval.OneMinute].Load(SetsAdded); + Archives[ArchiveInterval.OneMinute].Load(_setsAdded); } - if (serverWas - LastOneHourCollection > OneHour) + + if (serverWas - LastOneHourCollection > TimeSpan.FromHours(1)) { - Get(ArchiveInterval.OneHour, UpdateUri, RRD_Update_InspectCurrentNode, xenObject); + Get(ArchiveInterval.OneHour, UpdateUri, RRD_Update_InspectCurrentNode, XenObject); + + if (RequestedCancellation) + break; + LastOneHourCollection = serverWas; - Archives[ArchiveInterval.OneHour].Load(SetsAdded); + Archives[ArchiveInterval.OneHour].Load(_setsAdded); } - if (serverWas - LastOneDayCollection > OneDay) + + if (serverWas - LastOneDayCollection > TimeSpan.FromDays(1)) { - Get(ArchiveInterval.OneDay, UpdateUri, RRD_Update_InspectCurrentNode, xenObject); + Get(ArchiveInterval.OneDay, UpdateUri, RRD_Update_InspectCurrentNode, XenObject); + + if (RequestedCancellation) + break; + LastOneDayCollection = serverWas; - Archives[ArchiveInterval.OneDay].Load(SetsAdded); + Archives[ArchiveInterval.OneDay].Load(_setsAdded); } + if (RequestedCancellation) + break; - lock (WaitUpdates) - { - Monitor.Wait(WaitUpdates, SleepTime); - } - lock (UpdateMonitor) + ArchivesUpdated?.Invoke(); + Thread.Sleep(SLEEP_TIME); + + if (RequestedCancellation) + break; + } + } + + private void InitialLoad(DateTime initialServerTime) + { + // Restrict to at most 24 hours data if necessary + if (Helpers.FeatureForbidden(XenObject, Host.RestrictPerformanceGraphs)) + { + Archives[ArchiveInterval.OneHour].MaxPoints = 24; + Archives[ArchiveInterval.OneDay].MaxPoints = 0; + } + else + { + Archives[ArchiveInterval.OneHour].MaxPoints = HOURS_IN_ONE_WEEK; + Archives[ArchiveInterval.OneDay].MaxPoints = DAYS_IN_ONE_YEAR; + } + + _dataSources.Clear(); + + foreach (var a in Archives.Values) + a.ClearSets(); + + if (RequestedCancellation) + return; + + LoadingInitialData = true; + ArchivesUpdated?.Invoke(); + + try + { + switch (XenObject) { - if (!ThreadRunning) - Monitor.Wait(UpdateMonitor); + case Host h: + _dataSources = Host.get_data_sources(h.Connection.Session, h.opaque_ref); + break; + case VM vm when vm.power_state == vm_power_state.Running: + _dataSources = VM.get_data_sources(vm.Connection.Session, vm.opaque_ref); + break; } + + if (RequestedCancellation) + return; + + Get(ArchiveInterval.None, RrdsUri, RRD_Full_InspectCurrentNode, XenObject); + } + catch (Exception e) + { + //Get handles its own exception; Anything caught here is thrown by the get_data_sources operations + Log.Error($"Failed to retrieve data sources for '{XenObject.Name()}'", e); } + + if (RequestedCancellation) + return; + + ArchivesUpdated?.Invoke(); + LoadingInitialData = false; + + LastFiveSecondCollection = initialServerTime; + LastOneMinuteCollection = initialServerTime; + LastOneHourCollection = initialServerTime; + LastOneDayCollection = initialServerTime; } private void Get(ArchiveInterval interval, Func uriBuilder, - ActionReader, IXenObject xenObject) + Action readerMethod, IXenObject xenObject) { try { @@ -267,27 +282,31 @@ private void Get(ArchiveInterval interval, Func(); - while (reader.Read()) + _setsAdded = new List(); + while (reader.Read() && !RequestedCancellation) { - Reader(reader, xenObject); + readerMethod(reader, xenObject); } } } } - catch (WebException) - { - } catch (Exception e) { - log.Debug(string.Format("ArchiveMaintainer: Get updates for {0}: {1} Failed.", xenObject is Host ? "Host" : "VM", xenObject != null ? xenObject.opaque_ref : Helper.NullOpaqueRef), e); + if (xenObject is Host host) + Log.Warn($"Get updates for host {host.Name()} ({host.opaque_ref}) failed.", e); + else if (xenObject is VM vm) + Log.Warn($"Get updates for VM {vm.Name()} ({vm.opaque_ref}) failed.", e); + else + Log.Warn($"Get updates for Unknown XenObject {xenObject?.Name() ?? "(unknown name)"} ({xenObject?.opaque_ref ?? "(unknown opaque_ref)"}) failed.", e); } } + #region Uri generators + private Uri UpdateUri(ArchiveInterval interval, IXenObject xo) { var sessionRef = xo?.Connection?.Session?.opaque_ref; @@ -298,20 +317,24 @@ private Uri UpdateUri(ArchiveInterval interval, IXenObject xo) var startTime = TimeFromInterval(interval); var duration = ToSeconds(interval); - if (xo is Host host) + switch (xo) { - return BuildUri(host, "rrd_updates", - $"session_id={escapedRef}&start={startTime}&cf=AVERAGE&interval={duration}&host=true"); - } - - if (xo is VM vm) - { - var vmHost = vm.Connection.Resolve(vm.resident_on) ?? Helpers.GetCoordinator(vm.Connection); - return BuildUri(vmHost, "rrd_updates", - $"session_id={escapedRef}&start={startTime}&cf=AVERAGE&interval={duration}&vm_uuid={vm.uuid}"); + case Host host: + return BuildUri(host, "rrd_updates", + $"session_id={escapedRef}&start={startTime}&cf=AVERAGE&interval={duration}&host=true"); + case VM vm: + { + var vmHost = vm.Connection.Resolve(vm.resident_on) ?? Helpers.GetCoordinator(vm.Connection); + return BuildUri(vmHost, "rrd_updates", + $"session_id={escapedRef}&start={startTime}&cf=AVERAGE&interval={duration}&vm_uuid={vm.uuid}"); + } + default: + const string issue = + "ArchiveMaintainer.UpdateUri was given an invalid XenObject. Only Hosts and VMs are supported."; + Log.Warn(issue); + Debug.Assert(false, issue); + return null; } - - return null; } private static Uri RrdsUri(ArchiveInterval interval, IXenObject xo) @@ -321,22 +344,28 @@ private static Uri RrdsUri(ArchiveInterval interval, IXenObject xo) return null; var escapedRef = Uri.EscapeDataString(sessionRef); - - if (xo is Host host) - return BuildUri(host, "host_rrds", $"session_id={escapedRef}"); - if (xo is VM vm) + switch (xo) { - var vmHost = vm.Connection.Resolve(vm.resident_on) ?? Helpers.GetCoordinator(vm.Connection); - return BuildUri(vmHost, "vm_rrds", $"session_id={escapedRef}&uuid={vm.uuid}"); + case Host host: + return BuildUri(host, "host_rrds", $"session_id={escapedRef}"); + case VM vm: + { + var vmHost = vm.Connection.Resolve(vm.resident_on) ?? Helpers.GetCoordinator(vm.Connection); + return BuildUri(vmHost, "vm_rrds", $"session_id={escapedRef}&uuid={vm.uuid}"); + } + default: + const string issue = + "ArchiveMaintainer.UpdateUri was given an invalid XenObject. Only Hosts and VMs are supported."; + Log.Warn(issue); + Debug.Assert(false, issue); + return null; } - - return null; } private static Uri BuildUri(Host host, string path, string query) { - UriBuilder builder = new UriBuilder + var builder = new UriBuilder { Scheme = host.Connection.UriScheme, Host = host.address, @@ -347,146 +376,108 @@ private static Uri BuildUri(Host host, string path, string query) return builder.Uri; } - public static long ToTicks(ArchiveInterval interval) - { - switch (interval) - { - case ArchiveInterval.FiveSecond: - return TicksInFiveSeconds; - case ArchiveInterval.OneMinute: - return TicksInOneMinute; - case ArchiveInterval.OneHour: - return TicksInOneHour; - default: - return TicksInOneDay; - } - } - - private static long ToSeconds(ArchiveInterval interval) - { - return ToTicks(interval) / TimeSpan.TicksPerSecond; - } - - private long TimeFromInterval(ArchiveInterval interval) - { - switch (interval) - { - case ArchiveInterval.FiveSecond: - if (LastFiveSecondCollection != DateTime.MinValue) - return Util.TicksToSecondsSince1970(LastFiveSecondCollection.Ticks - TicksInFiveSeconds); - break; - case ArchiveInterval.OneMinute: - if (LastOneMinuteCollection != DateTime.MinValue) - return Util.TicksToSecondsSince1970(LastOneMinuteCollection.Ticks - TicksInOneMinute); - break; - case ArchiveInterval.OneHour: - if (LastOneHourCollection != DateTime.MinValue) - return Util.TicksToSecondsSince1970(LastOneHourCollection.Ticks - TicksInOneHour); - break; - case ArchiveInterval.OneDay: - if (LastOneDayCollection != DateTime.MinValue) - return Util.TicksToSecondsSince1970(LastOneDayCollection.Ticks - TicksInOneDay); - break; - } - return 0; - } + #endregion - private static ArchiveInterval GetArchiveIntervalFromFiveSecs(long v) - { - switch (v) - { - case 1: - return ArchiveInterval.FiveSecond; - case 12: - return ArchiveInterval.OneMinute; - case 720: - return ArchiveInterval.OneHour; - case 17280: - return ArchiveInterval.OneDay; - default: - return ArchiveInterval.None; - } - } + #region Data fetcher methods private void RRD_Full_InspectCurrentNode(XmlReader reader, IXenObject xmo) { - if (reader.NodeType == XmlNodeType.Element) + switch (reader.NodeType) { - LastNode = reader.Name; - if (LastNode == "row") + case XmlNodeType.Element: { - CurrentTime += CurrentInterval * StepSize * TicksInOneSecond; - ValueCount = 0; - } - } + _lastNode = reader.Name; + if (_lastNode == "row") + { + _currentTime += _currentInterval * _stepSize * TICKS_IN_ONE_SECOND; + _valueCount = 0; + } - if (reader.NodeType == XmlNodeType.EndElement) - { - LastNode = reader.Name; - if (LastNode == "rra") + break; + } + case XmlNodeType.EndElement: { - if (BailOut) + _lastNode = reader.Name; + if (_lastNode == "rra") { - BailOut = false; - return; - } + if (_bailOut) + { + _bailOut = false; + return; + } - ArchiveInterval i = GetArchiveIntervalFromFiveSecs(CurrentInterval); - if (i != ArchiveInterval.None) - Archives[i].CopyLoad(SetsAdded, _dataSources); + var i = GetArchiveIntervalFromFiveSecs(_currentInterval); + if (i != ArchiveInterval.None) + Archives[i].CopyLoad(_setsAdded, _dataSources); - foreach (DataSet set in SetsAdded) - set.Points.Clear(); - BailOut = false; + foreach (var set in _setsAdded) + set.Points.Clear(); + _bailOut = false; + } + + break; } } if (reader.NodeType != XmlNodeType.Text) return; - if (LastNode == "name") - { - string str = reader.ReadContentAsString(); - SetsAdded.Add(new DataSet(xmo, false, str, _dataSources)); - } - else if (LastNode == "step") - { - string str = reader.ReadContentAsString(); - StepSize = long.Parse(str, CultureInfo.InvariantCulture); - } - else if (LastNode == "lastupdate") - { - string str = reader.ReadContentAsString(); - EndTime = long.Parse(str, CultureInfo.InvariantCulture); - } - else if (LastNode == "pdp_per_row") - { - string str = reader.ReadContentAsString(); - CurrentInterval = long.Parse(str, CultureInfo.InvariantCulture); - - long modInterval = EndTime % (StepSize * CurrentInterval); - long stepCount = CurrentInterval == 1 ? FiveSecondsInTenMinutes // 120 * 5 seconds in 10 minutes - : CurrentInterval == 12 ? MinutesInTwoHours // 120 minutes in 2 hours - : CurrentInterval == 720 ? HoursInOneWeek // 168 hours in a week - : DaysInOneYear; // 366 days in a year - - CurrentTime = new DateTime((((EndTime - modInterval) - (StepSize * CurrentInterval * stepCount)) * TimeSpan.TicksPerSecond) + Util.TicksBefore1970).ToLocalTime().Ticks; - } - else if (LastNode == "cf") + switch (_lastNode) { - string str = reader.ReadContentAsString(); - if (str != "AVERAGE") - BailOut = true; - } - else if (LastNode == "v") - { - if (BailOut || SetsAdded.Count <= ValueCount) + case "name": + { + var str = reader.ReadContentAsString(); + _setsAdded.Add(new DataSet(xmo, false, str, _dataSources)); + break; + } + case "step": + { + var str = reader.ReadContentAsString(); + _stepSize = long.Parse(str, CultureInfo.InvariantCulture); + break; + } + case "lastupdate": + { + var str = reader.ReadContentAsString(); + _endTime = long.Parse(str, CultureInfo.InvariantCulture); + break; + } + case "pdp_per_row": + { + var str = reader.ReadContentAsString(); + _currentInterval = long.Parse(str, CultureInfo.InvariantCulture); + + var modInterval = _endTime % (_stepSize * _currentInterval); + long stepCount = _currentInterval == 1 + ? FIVE_SECONDS_IN_TEN_MINUTES // 120 * 5 seconds in 10 minutes + : _currentInterval == 12 + ? MINUTES_IN_TWO_HOURS // 120 minutes in 2 hours + : _currentInterval == 720 + ? HOURS_IN_ONE_WEEK // 168 hours in a week + : DAYS_IN_ONE_YEAR; // 366 days in a year + + _currentTime = + new DateTime((_endTime - modInterval - _stepSize * _currentInterval * stepCount) * + TimeSpan.TicksPerSecond + Util.TicksBefore1970).ToLocalTime().Ticks; + break; + } + case "cf": + { + var str = reader.ReadContentAsString(); + if (str != "AVERAGE") + _bailOut = true; + break; + } + case "v" when _bailOut || _setsAdded.Count <= _valueCount: return; - - DataSet set = SetsAdded[ValueCount]; - string str = reader.ReadContentAsString(); - set.AddPoint(str, CurrentTime, SetsAdded, _dataSources); - ValueCount++; + case "v": + { + var set = _setsAdded[_valueCount]; + var str = reader.ReadContentAsString(); + set.AddPoint(str, _currentTime, _setsAdded, _dataSources); + _valueCount++; + break; + } } } @@ -494,30 +485,33 @@ private void RRD_Update_InspectCurrentNode(XmlReader reader, IXenObject xo) { if (reader.NodeType == XmlNodeType.Element) { - LastNode = reader.Name; - if (LastNode == "row") + _lastNode = reader.Name; + if (_lastNode == "row") { - ValueCount = 0; + _valueCount = 0; } } - if (reader.NodeType != XmlNodeType.Text) return; - if (LastNode == "entry") + + if (reader.NodeType != XmlNodeType.Text) + return; + + if (_lastNode == "entry") { - string str = reader.ReadContentAsString(); + var str = reader.ReadContentAsString(); DataSet set = null; - if (DataSet.ParseId(str, out string objType, out string objUuid, out string dataSourceName)) + if (DataSet.ParseId(str, out var objType, out var objUuid, out var dataSourceName)) { if (objType == "host") { - Host host = xo.Connection.Cache.Hosts.FirstOrDefault(h => h.uuid == objUuid); + var host = xo.Connection.Cache.Hosts.FirstOrDefault(h => h.uuid == objUuid); if (host != null) set = new DataSet(host, (xo as Host)?.uuid != objUuid, dataSourceName, _dataSources); } if (objType == "vm") { - VM vm = xo.Connection.Cache.VMs.FirstOrDefault(v => v.uuid == objUuid); + var vm = xo.Connection.Cache.VMs.FirstOrDefault(v => v.uuid == objUuid); if (vm != null) set = new DataSet(vm, (xo as VM)?.uuid != objUuid, dataSourceName, _dataSources); } @@ -526,65 +520,62 @@ private void RRD_Update_InspectCurrentNode(XmlReader reader, IXenObject xo) if (set == null) set = new DataSet(null, true, str, _dataSources); - SetsAdded.Add(set); + _setsAdded.Add(set); } - else if (LastNode == "t") + else if (_lastNode == "t") { - string str = reader.ReadContentAsString(); - CurrentTime = new DateTime((Convert.ToInt64(str) * TimeSpan.TicksPerSecond) + Util.TicksBefore1970).ToLocalTime().Ticks; + var str = reader.ReadContentAsString(); + _currentTime = new DateTime(Convert.ToInt64(str) * TimeSpan.TicksPerSecond + Util.TicksBefore1970) + .ToLocalTime().Ticks; } - else if (LastNode == "v") + else if (_lastNode == "v") { - if (SetsAdded.Count <= ValueCount) return; - DataSet set = SetsAdded[ValueCount]; - string str = reader.ReadContentAsString(); - set.AddPoint(str, CurrentTime, SetsAdded, _dataSources); - ValueCount++; + if (_setsAdded.Count <= _valueCount) + return; + + var set = _setsAdded[_valueCount]; + var str = reader.ReadContentAsString(); + set.AddPoint(str, _currentTime, _setsAdded, _dataSources); + _valueCount++; } } - /// - /// run this to start or resume getting updates - /// + #endregion + + #region Actions + public void Start() { - if (ThreadRunning) - return; // if we are already running dont start twice! - ThreadRunning = true; - RunThread = true; // keep looping - if ((UpdaterThread.ThreadState & ThreadState.Unstarted) > 0) - UpdaterThread.Start(); // if we have never been started - else - { - lock (UpdateMonitor) - Monitor.PulseAll(UpdateMonitor); - lock (WaitUpdates) - Monitor.PulseAll(WaitUpdates); - } + Debug.Assert(!Running, "ArchiveMaintainer is not meant to have more than one worker thread. Ensure you are not calling Start multiple times"); + // someone already tried to dispose this archive maintainer + if (RequestedCancellation || Running) + return; + + Running = ThreadPool.QueueUserWorkItem(StartUpdateLoop); } - /// - /// for clean-up on exit only - /// - public void Stop() + public void Dispose() { - ThreadRunning = false; - RunThread = false; // exit loop - // make sure we clear all Monitor.Waits so we can exit - lock (WaitUpdates) - Monitor.PulseAll(WaitUpdates); - lock (UpdateMonitor) - Monitor.PulseAll(UpdateMonitor); + RequestedCancellation = true; } - /// - /// for stoping getting updates when switching away from perfomance panel - /// - public void Pause() + #endregion + + #region Public static methods + + public static long ToTicks(ArchiveInterval interval) { - ThreadRunning = false; // stop updating - lock (WaitUpdates) // clear the first Monitor.Wait so we pause the thread instantly. - Monitor.PulseAll(WaitUpdates); + switch (interval) + { + case ArchiveInterval.FiveSecond: + return TICKS_IN_FIVE_SECONDS; + case ArchiveInterval.OneMinute: + return TICKS_IN_ONE_MINUTE; + case ArchiveInterval.OneHour: + return TICKS_IN_ONE_HOUR; + default: + return TICKS_IN_ONE_DAY; + } } public static ArchiveInterval NextArchiveDown(ArchiveInterval current) @@ -603,5 +594,58 @@ public static ArchiveInterval NextArchiveDown(ArchiveInterval current) return ArchiveInterval.None; } } + + #endregion + + #region Helpers + + private static long ToSeconds(ArchiveInterval interval) + { + return ToTicks(interval) / TimeSpan.TicksPerSecond; + } + + private long TimeFromInterval(ArchiveInterval interval) + { + switch (interval) + { + case ArchiveInterval.FiveSecond: + if (LastFiveSecondCollection != DateTime.MinValue) + return Util.TicksToSecondsSince1970(LastFiveSecondCollection.Ticks - TICKS_IN_FIVE_SECONDS); + break; + case ArchiveInterval.OneMinute: + if (LastOneMinuteCollection != DateTime.MinValue) + return Util.TicksToSecondsSince1970(LastOneMinuteCollection.Ticks - TICKS_IN_ONE_MINUTE); + break; + case ArchiveInterval.OneHour: + if (LastOneHourCollection != DateTime.MinValue) + return Util.TicksToSecondsSince1970(LastOneHourCollection.Ticks - TICKS_IN_ONE_HOUR); + break; + case ArchiveInterval.OneDay: + if (LastOneDayCollection != DateTime.MinValue) + return Util.TicksToSecondsSince1970(LastOneDayCollection.Ticks - TICKS_IN_ONE_DAY); + break; + } + + return 0; + } + + private static ArchiveInterval GetArchiveIntervalFromFiveSecs(long v) + { + switch (v) + { + case 1: + return ArchiveInterval.FiveSecond; + case 12: + return ArchiveInterval.OneMinute; + case 720: + return ArchiveInterval.OneHour; + case 17280: + return ArchiveInterval.OneDay; + default: + return ArchiveInterval.None; + } + } + + #endregion } -} +} \ No newline at end of file diff --git a/XenAdmin/Controls/CustomDataGraph/DataPlotNav.cs b/XenAdmin/Controls/CustomDataGraph/DataPlotNav.cs index 8e055ad28c..694890703b 100644 --- a/XenAdmin/Controls/CustomDataGraph/DataPlotNav.cs +++ b/XenAdmin/Controls/CustomDataGraph/DataPlotNav.cs @@ -220,22 +220,22 @@ public TimeSpan GetArchiveSpan() ArchiveInterval interval = GetCurrentLeftArchiveInterval(); if (interval == ArchiveInterval.FiveSecond) - return TimeSpan.FromTicks(ArchiveMaintainer.TicksInTenMinutes); + return TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_TEN_MINUTES); if (interval == ArchiveInterval.OneMinute) - return TimeSpan.FromTicks(ArchiveMaintainer.TicksInTwoHours); + return TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_TWO_HOURS); if (interval == ArchiveInterval.OneHour) - return TimeSpan.FromTicks(ArchiveMaintainer.TicksInSevenDays); - return TimeSpan.FromTicks(ArchiveMaintainer.TicksInOneYear); + return TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_SEVEN_DAYS); + return TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_ONE_YEAR); } public ArchiveInterval GetCurrentLeftArchiveInterval() { //TimeSpan t = ArchiveMaintainer != null ? ArchiveMaintainer.ClientServerOffset : TimeSpan.Zero; - if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TicksInTenMinutes) + if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_TEN_MINUTES) return ArchiveInterval.FiveSecond; - if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TicksInTwoHours) + if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_TWO_HOURS) return ArchiveInterval.OneMinute; - if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TicksInSevenDays) + if (GraphOffset.Ticks + GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_SEVEN_DAYS) return ArchiveInterval.OneHour; return ArchiveInterval.OneDay; } @@ -243,11 +243,11 @@ public ArchiveInterval GetCurrentLeftArchiveInterval() public ArchiveInterval GetCurrentWidthArchiveInterval() { //TimeSpan t = ArchiveMaintainer != null ? ArchiveMaintainer.ClientServerOffset : TimeSpan.Zero; - if (GraphWidth.Ticks < ArchiveMaintainer.TicksInTenMinutes) + if (GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_TEN_MINUTES) return ArchiveInterval.FiveSecond; - if (GraphWidth.Ticks < ArchiveMaintainer.TicksInTwoHours) + if (GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_TWO_HOURS) return ArchiveInterval.OneMinute; - if (GraphWidth.Ticks < ArchiveMaintainer.TicksInSevenDays) + if (GraphWidth.Ticks < ArchiveMaintainer.TICKS_IN_SEVEN_DAYS) return ArchiveInterval.OneHour; return ArchiveInterval.OneDay; } @@ -391,11 +391,11 @@ private ArchiveInterval ScrollViewLeftArchiveInterval { TimeSpan width = Animating ? AnimateCurrentWidth : ScrollViewWidth; TimeSpan offset = Animating ? AnimateCurrentOffset : ScrollViewOffset; - if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TicksInTenMinutes) + if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TICKS_IN_TEN_MINUTES) return ArchiveInterval.FiveSecond; - else if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TicksInTwoHours) + else if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TICKS_IN_TWO_HOURS) return ArchiveInterval.OneMinute; - else if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TicksInSevenDays) + else if (offset.Ticks + width.Ticks <= ArchiveMaintainer.TICKS_IN_SEVEN_DAYS) return ArchiveInterval.OneHour; else return ArchiveInterval.OneDay; @@ -407,11 +407,11 @@ private ArchiveInterval ScrollViewWidthArchiveInterval get { TimeSpan width = Animating ? AnimateCurrentWidth : ScrollViewWidth; - if (width.Ticks <= ArchiveMaintainer.TicksInTenMinutes) + if (width.Ticks <= ArchiveMaintainer.TICKS_IN_TEN_MINUTES) return ArchiveInterval.FiveSecond; - else if (width.Ticks <= ArchiveMaintainer.TicksInTwoHours) + else if (width.Ticks <= ArchiveMaintainer.TICKS_IN_TWO_HOURS) return ArchiveInterval.OneMinute; - else if (width.Ticks <= ArchiveMaintainer.TicksInSevenDays) + else if (width.Ticks <= ArchiveMaintainer.TICKS_IN_SEVEN_DAYS) return ArchiveInterval.OneHour; else return ArchiveInterval.OneDay; @@ -567,7 +567,7 @@ public TimeSpan ScrollViewOffset set { _scrollViewOffset = value; } } - private TimeSpan _scrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TicksInTwoHours); + private TimeSpan _scrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_TWO_HOURS); public TimeSpan ScrollViewWidth { @@ -647,12 +647,12 @@ private void AutoScaleGraph() { while (true) { - if (GraphWidth.Ticks < ScrollViewWidth.Ticks * 0.1 && ScrollViewWidth.Ticks / 7 > ArchiveMaintainer.TicksInTenMinutes) + if (GraphWidth.Ticks < ScrollViewWidth.Ticks * 0.1 && ScrollViewWidth.Ticks / 7 > ArchiveMaintainer.TICKS_IN_TEN_MINUTES) { AnimateCurrentWidth = ScrollViewWidth; Animating = true; - if (ScrollViewWidth.Ticks / 7 > ArchiveMaintainer.TicksInTenMinutes) + if (ScrollViewWidth.Ticks / 7 > ArchiveMaintainer.TICKS_IN_TEN_MINUTES) { ScrollViewWidth = TimeSpan.FromTicks(ScrollViewWidth.Ticks / 7); } @@ -661,10 +661,10 @@ private void AutoScaleGraph() { AnimateCurrentWidth = ScrollViewWidth; Animating = true; - ScrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TicksInTenMinutes); + ScrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_TEN_MINUTES); break; } - else if (GraphWidth.Ticks > ScrollViewWidth.Ticks * 0.7 && ScrollViewWidth.Ticks * 7 < ArchiveMaintainer.TicksInOneYear) + else if (GraphWidth.Ticks > ScrollViewWidth.Ticks * 0.7 && ScrollViewWidth.Ticks * 7 < ArchiveMaintainer.TICKS_IN_ONE_YEAR) { AnimateCurrentWidth = ScrollViewWidth; Animating = true; @@ -674,7 +674,7 @@ private void AutoScaleGraph() { AnimateCurrentWidth = ScrollViewWidth; Animating = true; - ScrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TicksInOneYear); + ScrollViewWidth = TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_ONE_YEAR); break; } else @@ -898,11 +898,11 @@ protected override void OnMouseWheel(MouseEventArgs e) return; GraphOffset = TimeSpan.Zero; } - else if (GraphOffset.Ticks + GraphWidth.Ticks - delta > ArchiveMaintainer.TicksInOneYear) + else if (GraphOffset.Ticks + GraphWidth.Ticks - delta > ArchiveMaintainer.TICKS_IN_ONE_YEAR) { - if (GraphOffset.Ticks == ArchiveMaintainer.TicksInOneYear - GraphWidth.Ticks) + if (GraphOffset.Ticks == ArchiveMaintainer.TICKS_IN_ONE_YEAR - GraphWidth.Ticks) return; - GraphOffset = TimeSpan.FromTicks(ArchiveMaintainer.TicksInOneYear - GraphWidth.Ticks); + GraphOffset = TimeSpan.FromTicks(ArchiveMaintainer.TICKS_IN_ONE_YEAR - GraphWidth.Ticks); } else { diff --git a/XenAdmin/Controls/CustomDataGraph/DataSet.cs b/XenAdmin/Controls/CustomDataGraph/DataSet.cs index bff579f204..d6d2c8b43f 100644 --- a/XenAdmin/Controls/CustomDataGraph/DataSet.cs +++ b/XenAdmin/Controls/CustomDataGraph/DataSet.cs @@ -41,7 +41,7 @@ public class DataSet : IComparable { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private const int NegativeValue = -1; + private const int NEGATIVE_VALUE = -1; /// /// Things can only be added to the beginning or end of this list; it should @@ -50,12 +50,12 @@ public class DataSet : IComparable public List Points = new List(); public bool Selected; public List CurrentlyDisplayed = new List(); - public IXenObject XenObject; + public readonly IXenObject XenObject; public readonly string Id = ""; - public string DataSourceName; + public readonly string DataSourceName; public string FriendlyName { get; } - private int MultiplyingFactor = 1; - public DataRange CustomYRange = new DataRange(1, 0, 1, Unit.None, RangeScaleMode.Auto); + private readonly int _multiplyingFactor = 1; + public readonly DataRange CustomYRange = new DataRange(1, 0, 1, Unit.None, RangeScaleMode.Auto); public bool Hide { get; } public DataSet(IXenObject xo, bool hide, string datasourceName, List datasources) @@ -87,10 +87,13 @@ public DataSet(IXenObject xo, bool hide, string datasourceName, List setsAdded, List { double value = Helpers.StringToDouble(str); bool isNanOrInfinity = double.IsNaN(value) || double.IsInfinity(value); - double yValue = isNanOrInfinity ? NegativeValue : value * MultiplyingFactor; + double yValue = isNanOrInfinity ? NEGATIVE_VALUE : value * _multiplyingFactor; #region cpu @@ -370,7 +373,7 @@ public void AddPoint(string str, long currentTime, List setsAdded, List } if (isNanOrInfinity || pt.Y < 0) - pt.Y = NegativeValue; + pt.Y = NEGATIVE_VALUE; else { double cpu_vals_added = 0d; @@ -395,8 +398,8 @@ public void AddPoint(string str, long currentTime, List setsAdded, List if (other != null && other.Points.Count - 1 == Points.Count) { yValue = isNanOrInfinity || other.Points[other.Points.Count - 1].Y < 0 - ? NegativeValue - : (value * MultiplyingFactor) - other.Points[other.Points.Count - 1].Y; + ? NEGATIVE_VALUE + : value * _multiplyingFactor - other.Points[other.Points.Count - 1].Y; other.Points[other.Points.Count - 1].Y = yValue; } } @@ -406,8 +409,8 @@ public void AddPoint(string str, long currentTime, List setsAdded, List if (other != null && other.Points.Count - 1 == Points.Count) { yValue = isNanOrInfinity || other.Points[other.Points.Count - 1].Y < 0 - ? NegativeValue - : other.Points[other.Points.Count - 1].Y - (value * MultiplyingFactor); + ? NEGATIVE_VALUE + : other.Points[other.Points.Count - 1].Y - value * _multiplyingFactor; } } else if (DataSourceName == "memory") @@ -416,8 +419,8 @@ public void AddPoint(string str, long currentTime, List setsAdded, List if (other != null && other.Points.Count - 1 == Points.Count) { yValue = isNanOrInfinity || other.Points[other.Points.Count - 1].Y < 0 - ? NegativeValue - : (value * MultiplyingFactor) - other.Points[other.Points.Count - 1].Y; + ? NEGATIVE_VALUE + : value * _multiplyingFactor - other.Points[other.Points.Count - 1].Y; other.Points[other.Points.Count - 1].Y = yValue; } } @@ -427,8 +430,8 @@ public void AddPoint(string str, long currentTime, List setsAdded, List if (other != null && other.Points.Count - 1 == Points.Count) { yValue = isNanOrInfinity || other.Points[other.Points.Count - 1].Y < 0 - ? NegativeValue - : other.Points[other.Points.Count - 1].Y - (value * MultiplyingFactor); + ? NEGATIVE_VALUE + : other.Points[other.Points.Count - 1].Y - value * _multiplyingFactor; } } diff --git a/XenAdmin/Controls/Wlb/WlbOptModeScheduler.cs b/XenAdmin/Controls/Wlb/WlbOptModeScheduler.cs index 9e4bacfd63..5c061148a1 100644 --- a/XenAdmin/Controls/Wlb/WlbOptModeScheduler.cs +++ b/XenAdmin/Controls/Wlb/WlbOptModeScheduler.cs @@ -432,35 +432,27 @@ public static uint Bitcount(int n) } - private static string GetTaskDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek taskDaysOfWeek) - { - return WlbScheduledTask.DaysOfWeekL10N(taskDaysOfWeek); - } - private static string GetTaskDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek taskDaysOfWeek, WlbScheduledTask.WlbTaskDaysOfWeek taskDaysofWeekSortedList) { - string returnStr = ""; - returnStr += WlbScheduledTask.DaysOfWeekL10N(taskDaysOfWeek); + string day = WlbScheduledTask.DaysOfWeekL10N(taskDaysOfWeek); //count the bits set in days of week. //this workaround had to be made to determine whether the original task was set for //weekends/weekdays/alldays uint bitCount = Bitcount((int)taskDaysofWeekSortedList); - if (bitCount == 2) - { - returnStr += " (" + Messages.ResourceManager.GetString("WLB_DAY_WEEKENDS") + ")"; - } - else if (bitCount == 5) - { - returnStr += " (" + Messages.ResourceManager.GetString("WLB_DAY_WEEKDAYS") + ")"; - } - else if (bitCount == 7) + + switch (bitCount) { - returnStr += " (" + Messages.ResourceManager.GetString("WLB_DAY_ALL") + ")"; + case 2: + return $"{day} ({Messages.WLB_DAY_WEEKENDS})"; + case 5: + return $"{day} ({Messages.WLB_DAY_WEEKDAYS})"; + case 7: + return $"{day} ({Messages.WLB_DAY_ALL})"; + default: + return day; } - - return returnStr; } public static string GetTaskRunTime(DateTime time) diff --git a/XenAdmin/Controls/XenTabPage.cs b/XenAdmin/Controls/XenTabPage.cs index a20d3c59cd..6e7c0dc5ff 100644 --- a/XenAdmin/Controls/XenTabPage.cs +++ b/XenAdmin/Controls/XenTabPage.cs @@ -103,7 +103,7 @@ public override string Text /// Gets the value by which the help files section for this page is identified /// Most derived classes override it to return a fixed string /// - public virtual string HelpID => ""; + public virtual string HelpID => string.Empty; public virtual string NextText(bool isLastPage) { diff --git a/XenAdmin/Core/Registry.cs b/XenAdmin/Core/Registry.cs index 7f411ea27c..5607ffbe82 100644 --- a/XenAdmin/Core/Registry.cs +++ b/XenAdmin/Core/Registry.cs @@ -266,7 +266,7 @@ public static string GetYumRepoDevTeamSource() private const string FORCE_SYSTEM_FONTS = "ForceSystemFonts"; private const string DISABLE_PLUGINS = "DisablePlugins"; private const string DONT_SUDO = "DontSudo"; - private static readonly string XENCENTER_LOCAL_KEYS = $"SOFTWARE\\{BrandManager.ProductBrand}\\{BrandManager.BrandConsoleNoSpace}"; + private static readonly string XENCENTER_LOCAL_KEYS = $"SOFTWARE\\{BrandManager.ProductBrand}\\{BrandManager.BrandConsole}"; private const string PSExecutionPolicyKey = @"Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell"; private const string PSExecutionPolicyName = "ExecutionPolicy"; private const string PowerShellKey = @"Software\Microsoft\PowerShell\1"; diff --git a/XenAdmin/Core/Updates.cs b/XenAdmin/Core/Updates.cs index c3e6cdfb42..0ee6cd53dd 100644 --- a/XenAdmin/Core/Updates.cs +++ b/XenAdmin/Core/Updates.cs @@ -120,34 +120,12 @@ public static void RemoveCdnInfoForConnection(IXenConnection connection) CdnUpdateInfoChanged?.Invoke(connection); } - public static void CheckForCdnUpdates(IXenConnection connection, bool isPlanAction = false) + public static void CheckForCdnUpdates(IXenConnection connection, bool runSynchronous = false) { - var pool = Helpers.GetPoolOfOne(connection); - if (pool == null) - return; - - if (!isPlanAction) - { - if (Helpers.XapiEqualOrGreater_23_18_0(connection)) - { - if (pool.last_update_sync == Util.GetUnixMinDateTime() || - connection.Cache.Hosts.All(h => h.latest_synced_updates_applied == latest_synced_updates_applied_state.yes)) - return; - } - else - { - if (pool.repositories.Count == 0) - return; - } - } - - if (!pool.allowed_operations.Contains(pool_allowed_operations.get_updates)) - return; - var action = new CheckForCdnUpdatesAction(connection); action.Completed += CheckForCdnUpdatesAction_Completed; - if (isPlanAction) + if (runSynchronous) action.RunSync(action.Session); else action.RunAsync(); @@ -158,14 +136,12 @@ private static void CheckForCdnUpdatesAction_Completed(ActionBase sender) if (!(sender is CheckForCdnUpdatesAction action)) return; - bool succeeded = action.Succeeded; - - if (succeeded) + lock (_cdnUpdatesLock) { - lock (_cdnUpdatesLock) - { + if (action.Succeeded && action.Updates != null) _cdnUpdateInfoPerConnection[action.Pool.Connection] = action.Updates; - } + else + _cdnUpdateInfoPerConnection.Remove(action.Pool.Connection); } CdnUpdateInfoChanged?.Invoke(action.Pool.Connection); diff --git a/XenAdmin/Diagnostics/Checks/HAOffCheck.cs b/XenAdmin/Diagnostics/Checks/HAOffCheck.cs deleted file mode 100644 index 14335cb9f7..0000000000 --- a/XenAdmin/Diagnostics/Checks/HAOffCheck.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using XenAPI; -using XenAdmin.Diagnostics.Problems; -using XenAdmin.Core; -using XenAdmin.Diagnostics.Problems.PoolProblem; - - -namespace XenAdmin.Diagnostics.Checks -{ - class HAOffCheck : HostPostLivenessCheck - { - public HAOffCheck(Host host) - : base(host) - { - } - - protected override Problem RunHostCheck() - { - Pool pool = Helpers.GetPoolOfOne(Host.Connection); - if (pool == null) - return null; - - if (pool.ha_enabled) - return new HAEnabledProblem(this, pool); - if (Helpers.WlbEnabled(pool.Connection)) - return new WLBEnabledProblem(this, pool); - return null; - } - - public override string Description => Messages.HA_CHECK_DESCRIPTION; - - public override string SuccessfulCheckDescription - { - get - { - var pool = Helpers.GetPool(Host.Connection); - return string.Format(Messages.PATCHING_WIZARD_CHECK_ON_XENOBJECT_OK, - pool != null ? pool.Name() : Host.Name(), Description); - } - } - } -} diff --git a/XenAdmin/Wizards/PatchingWizard/PlanActions/BringBabiesBackAction.cs b/XenAdmin/Diagnostics/Checks/HaWlbOffCheck.cs similarity index 64% rename from XenAdmin/Wizards/PatchingWizard/PlanActions/BringBabiesBackAction.cs rename to XenAdmin/Diagnostics/Checks/HaWlbOffCheck.cs index e358e671f0..84c9d6c31e 100644 --- a/XenAdmin/Wizards/PatchingWizard/PlanActions/BringBabiesBackAction.cs +++ b/XenAdmin/Diagnostics/Checks/HaWlbOffCheck.cs @@ -28,27 +28,34 @@ * SUCH DAMAGE. */ -using System.Collections.Generic; +using XenAdmin.Core; +using XenAdmin.Diagnostics.Problems; +using XenAdmin.Diagnostics.Problems.PoolProblem; using XenAPI; -namespace XenAdmin.Wizards.PatchingWizard.PlanActions +namespace XenAdmin.Diagnostics.Checks { - public class BringBabiesBackAction : HostPlanAction + class HaWlbOffCheck : PoolCheck { - private readonly List> _vms; - private readonly bool _enableOnly; - - public BringBabiesBackAction(List> vms, Host host, bool enableOnly) - : base(host) + public HaWlbOffCheck(Pool pool) + : base(pool) { - _vms = vms; - _enableOnly = enableOnly; } - protected override void RunWithSession(ref Session session) + protected override Problem RunCheck() { - BringBabiesBack(ref session, _vms, _enableOnly); + if (Pool.ha_enabled) + return new HAEnabledProblem(this, Pool); + + if (Helpers.WlbEnabled(Pool.Connection)) + return new WLBEnabledProblem(this, Pool); + + return null; } + + public override string Description => Messages.HA_WLB_CHECK_DESCRIPTION; + + public override string SuccessfulCheckDescription => string.Format(Messages.PATCHING_WIZARD_CHECK_ON_XENOBJECT_OK, Pool.Name(), Description); } } diff --git a/XenAdmin/Diagnostics/Checks/HostNeedsRebootCheck.cs b/XenAdmin/Diagnostics/Checks/HostNeedsRebootCheck.cs index 339e43109b..3efb934bac 100644 --- a/XenAdmin/Diagnostics/Checks/HostNeedsRebootCheck.cs +++ b/XenAdmin/Diagnostics/Checks/HostNeedsRebootCheck.cs @@ -74,17 +74,15 @@ public HostNeedsRebootCheck(Host host) protected override Problem RunHostCheck() { - if (Helpers.CloudOrGreater(Host)) - { + if (Helpers.CloudOrGreater(Host) && livePatchCodesByHost == null) return new HostNeedsReboot(this, Host); - } - var updateSequenceIsLivePatchable = restartHostPatches != null && restartHostPatches.Count > 0 && restartHostPatches.All(p => p.ContainsLivepatch); + var updateSequenceIsLivePatchable = restartHostPatches != null && restartHostPatches.Count > 0 && + restartHostPatches.All(p => p.ContainsLivepatch); + var hostHasBeenLivePatched = livePatchCodesByHost != null && livePatchCodesByHost.ContainsKey(Host.uuid) && + livePatchCodesByHost[Host.uuid] == livepatch_status.ok_livepatch_complete; - // when livepatching is available, no restart is expected - if (livePatchCodesByHost != null && livePatchCodesByHost.ContainsKey(Host.uuid) && - livePatchCodesByHost[Host.uuid] == livepatch_status.ok_livepatch_complete - || updateSequenceIsLivePatchable) + if (hostHasBeenLivePatched || updateSequenceIsLivePatchable) { var livePatchingRestricted = Helpers.FeatureForbidden(Host.Connection, Host.RestrictLivePatching); var livePatchingRDisabled = Helpers.GetPoolOfOne(Host.Connection)?.live_patching_disabled == true; @@ -96,11 +94,11 @@ protected override Problem RunHostCheck() return null; } - if ((updateGuidance != null && updateGuidance.Contains(update_after_apply_guidance.restartHost)) - || (patchGuidance != null && patchGuidance.Contains(after_apply_guidance.restartHost)) - || (restartHostPatches != null && restartHostPatches.Count > 0)) + if (updateGuidance != null && updateGuidance.Contains(update_after_apply_guidance.restartHost) || + patchGuidance != null && patchGuidance.Contains(after_apply_guidance.restartHost) || + restartHostPatches != null && restartHostPatches.Count > 0) { - return new HostNeedsReboot(this, Host); + return new HostNeedsReboot(this, Host); } successfulCheckDescription = string.Format(Messages.UPDATES_WIZARD_NO_REBOOT_NEEDED, Host); diff --git a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.Designer.cs b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.Designer.cs index 007e782141..15246f55aa 100644 --- a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.Designer.cs +++ b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.Designer.cs @@ -35,7 +35,7 @@ private void InitializeComponent() this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.labelInfoCdn = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); - this.linkLabelCongifUpdates = new System.Windows.Forms.LinkLabel(); + this.linkLabelConfigUpdates = new System.Windows.Forms.LinkLabel(); this.UpdatesTableLayoutPanel.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); @@ -66,7 +66,7 @@ private void InitializeComponent() resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3"); this.tableLayoutPanel3.Controls.Add(this.labelInfoCdn, 1, 0); this.tableLayoutPanel3.Controls.Add(this.pictureBox1, 0, 0); - this.tableLayoutPanel3.Controls.Add(this.linkLabelCongifUpdates, 2, 0); + this.tableLayoutPanel3.Controls.Add(this.linkLabelConfigUpdates, 2, 0); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; // // labelInfoCdn @@ -81,12 +81,12 @@ private void InitializeComponent() this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // - // linkLabelCongifUpdates + // linkLabelConfigUpdates // - resources.ApplyResources(this.linkLabelCongifUpdates, "linkLabelCongifUpdates"); - this.linkLabelCongifUpdates.Name = "linkLabelCongifUpdates"; - this.linkLabelCongifUpdates.TabStop = true; - this.linkLabelCongifUpdates.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelCongifUpdates_LinkClicked); + resources.ApplyResources(this.linkLabelConfigUpdates, "linkLabelConfigUpdates"); + this.linkLabelConfigUpdates.Name = "linkLabelConfigUpdates"; + this.linkLabelConfigUpdates.TabStop = true; + this.linkLabelConfigUpdates.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelConfigUpdates_LinkClicked); // // UpdatesOptionsPage // @@ -112,6 +112,6 @@ private void InitializeComponent() private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.CheckBox _checkBoxClientUpdates; private System.Windows.Forms.Label labelClientUpdates; - private System.Windows.Forms.LinkLabel linkLabelCongifUpdates; + private System.Windows.Forms.LinkLabel linkLabelConfigUpdates; } } diff --git a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.cs b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.cs index 3ffcd1f8e6..ce0863783e 100644 --- a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.cs +++ b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.cs @@ -92,7 +92,7 @@ public void Save() #endregion - private void linkLabelCongifUpdates_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + private void linkLabelConfigUpdates_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { using (var dialog = new ConfigUpdatesDialog()) dialog.ShowDialog(this); diff --git a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.resx b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.resx index bcdc67af52..6476c43ee0 100644 --- a/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.resx +++ b/XenAdmin/Dialogs/OptionsPages/UpdatesOptionsPage.resx @@ -273,37 +273,37 @@ 1 - + Left - + True - + 273, 4 - + 0, 0, 3, 0 - + 97, 13 - + 2 - + Configure Updates - - linkLabelCongifUpdates + + linkLabelConfigUpdates - + System.Windows.Forms.LinkLabel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + tableLayoutPanel3 - + 2 @@ -337,7 +337,7 @@ 2 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelInfoCdn" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="pictureBox1" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="linkLabelCongifUpdates" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelInfoCdn" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="pictureBox1" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="linkLabelConfigUpdates" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0" /></TableLayoutSettings> Fill diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index bdac9b8a87..94f72f9f40 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -134,7 +134,7 @@ private void Build() ShowTab(GeneralEditPage = new GeneralEditPage()); - if (!isVmAppliance) + if (!isVmAppliance && !isVmss) ShowTab(CustomFieldsEditPage = new CustomFieldsDisplayPage {AutoScroll = true}); if (isVm) diff --git a/XenAdmin/Dialogs/ServerUpdates/ConfigCdnUpdatesPage.cs b/XenAdmin/Dialogs/ServerUpdates/ConfigCdnUpdatesPage.cs index 15961d420c..dd47eb2e54 100644 --- a/XenAdmin/Dialogs/ServerUpdates/ConfigCdnUpdatesPage.cs +++ b/XenAdmin/Dialogs/ServerUpdates/ConfigCdnUpdatesPage.cs @@ -85,8 +85,8 @@ private void ToggleConfigPanelEditState() buttonApply.Enabled = buttonDiscard.Enabled = active; comboBoxRepo.Enabled = active; - textBoxProxyUrl.ReadOnly = textBoxProxyUsername.ReadOnly = textBoxProxyPassword.ReadOnly = !active; - checkBoxPeriodicSync.Enabled = radioButtonDaily.Enabled = radioButtonWeekly.Enabled = comboBoxWeekday.Enabled = active; + textBoxProxyUrl.Enabled = textBoxProxyUsername.Enabled = textBoxProxyPassword.Enabled = + checkBoxPeriodicSync.Enabled = radioButtonDaily.Enabled = radioButtonWeekly.Enabled = comboBoxWeekday.Enabled = active; if (!active) UpdateConfigPanel(); diff --git a/XenAdmin/Dialogs/ServerUpdates/ConfigUpdatesDialog.cs b/XenAdmin/Dialogs/ServerUpdates/ConfigUpdatesDialog.cs index e05a557e11..0eb304037f 100644 --- a/XenAdmin/Dialogs/ServerUpdates/ConfigUpdatesDialog.cs +++ b/XenAdmin/Dialogs/ServerUpdates/ConfigUpdatesDialog.cs @@ -113,6 +113,8 @@ public void SelectLcmTab() tabControl1.SelectTab(_configLcmTab); } + internal override string HelpName => "ConfigureUpdatesDialog"; + private sealed class OptionsTabPage : TabPage { diff --git a/XenAdmin/Help/HelpManager.resx b/XenAdmin/Help/HelpManager.resx index b0f5d4dc8a..61fa898ab3 100644 --- a/XenAdmin/Help/HelpManager.resx +++ b/XenAdmin/Help/HelpManager.resx @@ -190,7 +190,7 @@ pools-rootpassword - updates-applying + updates-applying-ch intro-start @@ -198,6 +198,9 @@ users-overview + + updates-autoconfig + templates-new @@ -271,7 +274,7 @@ vms-relocate - + systemalerts resources-customfields @@ -300,9 +303,6 @@ dr-testfailover - - 9830 - dr-testfailover @@ -411,9 +411,6 @@ vms-network-properties - - 6536 - vms-snapshotschedule-manage-policy @@ -588,6 +585,9 @@ dr-testfailover + + systemalerts + licensing-about @@ -603,8 +603,11 @@ storage-pools-add-hba - - updates-applying + + updates-applying-xs + + + updates-applying-ch systemalerts @@ -846,32 +849,14 @@ intro-options - - updates-applying - - - updates-applying - - - updates-applying - - - updates-applying - - - updates-applying - - - updates-applying - - - updates-applying + + systemalerts - - updates-applying + + updates-applying-ch - - updates-applying + + updates-applying-xs pools-add-host @@ -1074,9 +1059,6 @@ hosts-reconnect - - updates-applying - vms-properties @@ -1135,12 +1117,15 @@ updates-xencenter - updates-applying + updates-applying-ch - updates-applying + updates-applying-ch storage-readcaching - \ No newline at end of file + + systemalerts + + diff --git a/XenAdmin/Help/extract-help-numbers b/XenAdmin/Help/extract-help-numbers deleted file mode 100644 index 677ce4820f..0000000000 --- a/XenAdmin/Help/extract-help-numbers +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh - -dir=$(dirname "$0") - -cat $dir/HelpManager.resx | sed -e 's# ##g' | awk ' -/data name="/ { FS="\""; NAME=$2; } -/.*<\/value>/ { print "#define " NAME " " $1; }' | -sed -e 's# *# #g' | sed -e 's###g' | grep -v Icon1 | grep -v Bitmap1 | grep -v Name1 | sort -nk 3 diff --git a/XenAdmin/Help/extract-help-numbers-csv b/XenAdmin/Help/extract-help-numbers-csv deleted file mode 100644 index 6bf88ee75e..0000000000 --- a/XenAdmin/Help/extract-help-numbers-csv +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh - -dir=$(dirname "$0") - -cat $dir/HelpManager.resx | sed -e 's# ##g' | awk ' -/data name="/ { FS="\""; NAME=$2; } -/.*<\/value>/ { print NAME "," $1; }' | -sed -e 's# *# #g' | sed -e 's###g' | grep -v Icon1 | grep -v Bitmap1 | grep -v Name1 | sort -nk 3 diff --git a/XenAdmin/Images.cs b/XenAdmin/Images.cs index 320fe5a49f..8d74e5df14 100644 --- a/XenAdmin/Images.cs +++ b/XenAdmin/Images.cs @@ -971,6 +971,7 @@ public static class StaticImages public static Bitmap usb_16 = Properties.Resources.usb_16; public static Bitmap yinhekylin_16x = Properties.Resources.yinhekylin_16x; public static Bitmap rightArrowLong_Blue_16 = Properties.Resources.rightArrowLong_Blue_16; + public static Bitmap rpm_package = Properties.Resources.rpm_package; } } } \ No newline at end of file diff --git a/XenAdmin/Images/rpm_package.png b/XenAdmin/Images/rpm_package.png new file mode 100644 index 0000000000..4aba7643e3 Binary files /dev/null and b/XenAdmin/Images/rpm_package.png differ diff --git a/XenAdmin/MainWindow.cs b/XenAdmin/MainWindow.cs index 877295a737..49cbb80583 100755 --- a/XenAdmin/MainWindow.cs +++ b/XenAdmin/MainWindow.cs @@ -2563,7 +2563,7 @@ private string TabHelpID() foreach (var page in _notificationPages) { if (page.Visible) - return alertPage.HelpID; + return page.HelpID; } if (TheTabControl.SelectedTab.Controls.Count > 0 && TheTabControl.SelectedTab.Controls[0] is IControlWithHelp ctrl) @@ -2893,10 +2893,9 @@ private string GetLicenseStatusText(IXenObject xenObject, out Color foreColor) { foreColor = VerticalGradientPanel.TextColor; - var pool = xenObject as Pool; - if (pool != null && pool.Connection != null && pool.Connection.IsConnected && pool.Connection.CacheIsPopulated) + if (xenObject is Pool pool && pool.Connection != null && pool.Connection.IsConnected && pool.Connection.CacheIsPopulated) { - if (pool.IsFreeLicenseOrExpired()) + if (pool.IsFreeLicenseOrExpired() && !Helpers.NileOrGreater(xenObject.Connection)) { foreColor = Color.Red; return Messages.MAINWINDOW_HEADER_UNLICENSED; @@ -2905,10 +2904,9 @@ private string GetLicenseStatusText(IXenObject xenObject, out Color foreColor) return string.Format(Messages.MAINWINDOW_HEADER_LICENSED_WITH, Helpers.GetFriendlyLicenseName(pool)); } - var host = xenObject as Host; - if (host != null && host.Connection != null && host.Connection.IsConnected && host.Connection.CacheIsPopulated) + if (xenObject is Host host && host.Connection != null && host.Connection.IsConnected && host.Connection.CacheIsPopulated) { - if (host.IsFreeLicenseOrExpired()) + if (host.IsFreeLicenseOrExpired() && !Helpers.NileOrGreater(xenObject.Connection)) { foreColor = Color.Red; return Messages.MAINWINDOW_HEADER_UNLICENSED; diff --git a/XenAdmin/Program.cs b/XenAdmin/Program.cs index df3a70bf0e..ce5b95b63b 100644 --- a/XenAdmin/Program.cs +++ b/XenAdmin/Program.cs @@ -125,12 +125,12 @@ static Program() var logFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), BrandManager.ProductBrand, - BrandManager.BrandConsoleNoSpace, + BrandManager.BrandConsole, "logs"); - log4net.GlobalContext.Properties["LOG_FILE"] = Path.Combine(logFolder, $"{BrandManager.BrandConsoleNoSpace}.log"); - log4net.GlobalContext.Properties["AUDIT_TRAIL"] = Path.Combine(logFolder, $"{BrandManager.BrandConsoleNoSpace}-AuditTrail.log"); - log4net.GlobalContext.Properties["NETWORK_TRACE"] = Path.Combine(logFolder, $"{BrandManager.BrandConsoleNoSpace}-NetworkTrace.log"); + log4net.GlobalContext.Properties["LOG_FILE"] = Path.Combine(logFolder, $"{BrandManager.BrandConsole}.log"); + log4net.GlobalContext.Properties["AUDIT_TRAIL"] = Path.Combine(logFolder, $"{BrandManager.BrandConsole}-AuditTrail.log"); + log4net.GlobalContext.Properties["NETWORK_TRACE"] = Path.Combine(logFolder, $"{BrandManager.BrandConsole}-NetworkTrace.log"); log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Assembly.GetCallingAssembly().Location + ".config")); log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); @@ -145,7 +145,7 @@ static Program() public static void Main(string[] args) { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value; - _pipePath = string.Format(PIPE_PATH_PATTERN, BrandManager.BrandConsoleNoSpace, Process.GetCurrentProcess().SessionId, Environment.UserName, appGuid); + _pipePath = string.Format(PIPE_PATH_PATTERN, BrandManager.BrandConsole, Process.GetCurrentProcess().SessionId, Environment.UserName, appGuid); if (NamedPipes.Pipe.ExistsPipe(_pipePath)) { diff --git a/XenAdmin/Properties/Resources.Designer.cs b/XenAdmin/Properties/Resources.Designer.cs index a1fd394c49..d0f3824520 100755 --- a/XenAdmin/Properties/Resources.Designer.cs +++ b/XenAdmin/Properties/Resources.Designer.cs @@ -2906,6 +2906,16 @@ internal static System.Drawing.Bitmap rocky_16x { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap rpm_package { + get { + object obj = ResourceManager.GetObject("rpm_package", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// diff --git a/XenAdmin/Properties/Resources.resx b/XenAdmin/Properties/Resources.resx index 097720cdbe..58f0396a1c 100755 --- a/XenAdmin/Properties/Resources.resx +++ b/XenAdmin/Properties/Resources.resx @@ -1156,4 +1156,7 @@ ..\Images\livepatch_16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - + + ..\Images\rpm_package.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/CFUValidator/Updates/XmlRetrieverFactory.cs b/XenAdmin/RDP/IRdpClient.cs similarity index 68% rename from CFUValidator/Updates/XmlRetrieverFactory.cs rename to XenAdmin/RDP/IRdpClient.cs index 48c9264abb..e514d94d03 100644 --- a/CFUValidator/Updates/XmlRetrieverFactory.cs +++ b/XenAdmin/RDP/IRdpClient.cs @@ -28,21 +28,26 @@ * SUCH DAMAGE. */ +using AxMSTSCLib; using System; -using CFUValidator.CommandLineOptions; -namespace CFUValidator.Updates +namespace XenAdmin.RDP { - class XmlRetrieverFactory + /// + /// Interface used to address common fields of RPDClients without + /// changing AXMSTSCLib.cs + /// + internal interface IRdpClient { - public ICheckForUpdatesXMLSource GetAction(OptionUsage usage, string location) - { - if (usage == OptionUsage.Url) - return new AlternativeUrlDownloadUpdatesXmlSourceAction(location); - if (usage == OptionUsage.File) - return new ReadFromFileUpdatesXmlSource(location); + int DesktopWidth { get; set; } + string Server { get; set; } + int DesktopHeight { get; set; } + void Connect(); - throw new ArgumentException("No action was found for the provided usage"); - } + event EventHandler OnConnected; + event EventHandler OnConnecting; + event IMsTscAxEvents_OnDisconnectedEventHandler OnDisconnected; + event EventHandler OnAuthenticationWarningDisplayed; + event EventHandler OnAuthenticationWarningDismissed; } } diff --git a/XenAdmin/RDP/MsRdpClient6.cs b/XenAdmin/RDP/MsRdpClient6.cs index d8c0797ac9..166a07aaaf 100644 --- a/XenAdmin/RDP/MsRdpClient6.cs +++ b/XenAdmin/RDP/MsRdpClient6.cs @@ -30,14 +30,8 @@ namespace XenAdmin.RDP { - public class MsRdpClient6 : AxMSTSCLib.AxMsRdpClient6 + public class MsRdpClient6 : AxMSTSCLib.AxMsRdpClient6, IRdpClient { - //Fix for the missing focus issue on the rdp client component - public MsRdpClient6() - : base() - { - } - protected override void WndProc(ref System.Windows.Forms.Message m) { //Fix for the missing focus issue on the rdp client component diff --git a/XenAdmin/RDP/MsRdpClient9.cs b/XenAdmin/RDP/MsRdpClient9.cs index 2872055b2d..955c6af22c 100644 --- a/XenAdmin/RDP/MsRdpClient9.cs +++ b/XenAdmin/RDP/MsRdpClient9.cs @@ -30,13 +30,8 @@ namespace XenAdmin.RDP { - public class MsRdpClient9 : AxMSTSCLib.AxMsRdpClient9 + public class MsRdpClient9 : AxMSTSCLib.AxMsRdpClient9, IRdpClient { - public MsRdpClient9() - : base() - { - } - protected override void WndProc(ref System.Windows.Forms.Message m) { //Fix for the missing focus issue on the rdp client component diff --git a/XenAdmin/Settings.cs b/XenAdmin/Settings.cs index 9114b387af..e261d661db 100644 --- a/XenAdmin/Settings.cs +++ b/XenAdmin/Settings.cs @@ -781,7 +781,7 @@ private static void UpgradeFromPreviousInstallation() Version previousVersion = null; Version currentVersion = Program.Version; - var directories = companyFolder.GetDirectories($"{BrandManager.BrandConsoleNoSpace}*"); + var directories = companyFolder.GetDirectories($"{BrandManager.BrandConsole}*"); foreach (var dir in directories) { diff --git a/XenAdmin/SettingsPanels/CustomFieldsDisplayPage.cs b/XenAdmin/SettingsPanels/CustomFieldsDisplayPage.cs index 7b4f833a2a..d446acb2ba 100644 --- a/XenAdmin/SettingsPanels/CustomFieldsDisplayPage.cs +++ b/XenAdmin/SettingsPanels/CustomFieldsDisplayPage.cs @@ -342,7 +342,7 @@ private Label CreateNewLabel(CustomFieldDefinition customFieldDefinition) return new Label { Anchor = AnchorStyles.Left | AnchorStyles.Right, - Text = customFieldDefinition.Name.EscapeAmpersands().Ellipsise(25), + Text = customFieldDefinition.Name.EscapeAmpersands().Ellipsise(45), Font = Program.DefaultFont, AutoSize = true, AutoEllipsis = false diff --git a/XenAdmin/SettingsPanels/GpuEditPage.cs b/XenAdmin/SettingsPanels/GpuEditPage.cs index 37c0aa2194..9919783ec0 100644 --- a/XenAdmin/SettingsPanels/GpuEditPage.cs +++ b/XenAdmin/SettingsPanels/GpuEditPage.cs @@ -119,7 +119,7 @@ public string SubText if (Helpers.GpusAvailable(Connection)) { var vGpus = VGpus; - txt = vGpus.Count > 0 ? string.Join(",", vGpus.Select(v => v.VGpuTypeDescription())) : Messages.GPU_NONE; + txt = vGpus.Count > 0 ? string.Join(",", vGpus.Select(v => v.VGpuTypeDescription())) : Messages.NONE_UPPER; } return txt; diff --git a/XenAdmin/TabPages/CdnUpdates/CdnExpandableRow.cs b/XenAdmin/TabPages/CdnUpdates/CdnExpandableRow.cs index 6f4e93f33c..afe78cf43e 100644 --- a/XenAdmin/TabPages/CdnUpdates/CdnExpandableRow.cs +++ b/XenAdmin/TabPages/CdnUpdates/CdnExpandableRow.cs @@ -205,15 +205,18 @@ public HostUpdateInfoRow(IXenConnection connection, Host host, CdnPoolUpdateInfo SetValues(Host.Name(), Images.GetImage16For(Images.GetIconFor(Host)), channel: channel, lastSync: lastSyncTime, lastUpdate: lastUpdateTime); - if (poolUpdateInfo != null && hostUpdateInfo != null) + if (poolUpdateInfo != null && hostUpdateInfo != null && hostUpdateInfo.UpdateIDs.Length > 0) { - if (hostUpdateInfo.RecommendedGuidance.Length > 0) + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.EvacuateHost) || + hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) { - _childRows.Add(new PostUpdateActionRow(hostUpdateInfo.RecommendedGuidance)); + _childRows.Add(new PreUpdateActionRow()); + } + + _childRows.Add(new PostUpdateActionRow(hostUpdateInfo.RecommendedGuidance.Where(g => g != CdnGuidance.EvacuateHost).ToArray())); - if (hostUpdateInfo.LivePatches.Length > 0 && !hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) - _childRows.Add(new LivePatchActionRow()); - } + if (hostUpdateInfo.LivePatches.Length > 0 && !hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) + _childRows.Add(new LivePatchActionRow()); var categories = hostUpdateInfo.GetUpdateCategories(poolUpdateInfo); @@ -249,7 +252,7 @@ internal class RpmCategoryRow : CdnExpandableRow public RpmCategoryRow(params string[] rpms) { SetValues(string.Format(Messages.HOTFIX_RPMS_TO_INSTALL, rpms.Length), - Images.StaticImages._000_Patch_h32bit_16); + Images.StaticImages.rpm_package); ChildRows = new List { new RpmsRow(rpms) }; } @@ -282,11 +285,23 @@ public UpdateDetailRow(string detail) } } + internal class PreUpdateActionRow : CdnExpandableRow + { + public PreUpdateActionRow() + { + SetValues(Messages.HOTFIX_PRE_UPDATE_ACTIONS, Images.StaticImages.rightArrowLong_Blue_16); + } + } + internal class PostUpdateActionRow : CdnExpandableRow { public PostUpdateActionRow(CdnGuidance[] guidance) { - var text = string.Format(Messages.HOTFIX_POST_UPDATE_ACTIONS, string.Join(Environment.NewLine, guidance.Select(Cdn.FriendlyInstruction))); + var guidanceString = guidance.Length > 0 + ? string.Join(Environment.NewLine, guidance.Select(Cdn.FriendlyInstruction)) + : Messages.NONE_UPPER; + + var text = string.Format(Messages.HOTFIX_POST_UPDATE_ACTIONS, guidanceString); SetValues(text, Images.StaticImages.rightArrowLong_Blue_16); } } diff --git a/XenAdmin/TabPages/GeneralTabLicenseStatusStringifier.cs b/XenAdmin/TabPages/GeneralTabLicenseStatusStringifier.cs index 255e6c7faa..6faff89fb7 100644 --- a/XenAdmin/TabPages/GeneralTabLicenseStatusStringifier.cs +++ b/XenAdmin/TabPages/GeneralTabLicenseStatusStringifier.cs @@ -47,8 +47,8 @@ public string ExpiryDate { get { - if (Status != null && Status.LicensedHost != null && Status.LicenseExpiresIn != null - && !LicenseStatus.IsInfinite(Status.LicenseExpiresIn)) + if (Status?.LicensedHost != null && Status.LicenseExpiresIn != new TimeSpan() + && !LicenseStatus.IsInfinite(Status.LicenseExpiresIn)) { return HelpersGUI.DateTimeToString(Status.LicensedHost.LicenseExpiryUTC().ToLocalTime(), Messages.DATEFORMAT_DMY_LONG, true); @@ -74,20 +74,20 @@ public string ExpiryStatus return Messages.LICENSE_UNLICENSED; if (Status.CurrentState == LicenseStatus.HostState.Free) - return Messages.LICENSE_UNLICENSED; + return Helpers.NileOrGreater(Status.LicensedHost) ? Messages.LICENSE_MANAGER_TRIAL_LICENSE : Messages.LICENSE_UNLICENSED; TimeSpan s = Status.LicenseExpiresExactlyIn; if (s.TotalMinutes < 2) return Messages.LICENSE_EXPIRES_ONE_MIN; if (s.TotalHours < 2) - return String.Format(Messages.LICENSE_EXPIRES_MINUTES, Math.Floor(s.TotalMinutes)); + return string.Format(Messages.LICENSE_EXPIRES_MINUTES, Math.Floor(s.TotalMinutes)); if (s.TotalDays < 2) - return String.Format(Messages.LICENSE_EXPIRES_HOURS, Math.Floor(s.TotalHours)); + return string.Format(Messages.LICENSE_EXPIRES_HOURS, Math.Floor(s.TotalHours)); if (s.TotalDays < 30) - return String.Format(Messages.LICENSE_EXPIRES_DAYS, s.Days); + return string.Format(Messages.LICENSE_EXPIRES_DAYS, s.Days); return Messages.LICENSE_LICENSED; } diff --git a/XenAdmin/TabPages/GeneralTabPage.cs b/XenAdmin/TabPages/GeneralTabPage.cs index 548a3afb5c..d35dc6190f 100644 --- a/XenAdmin/TabPages/GeneralTabPage.cs +++ b/XenAdmin/TabPages/GeneralTabPage.cs @@ -116,7 +116,7 @@ private void licenseStatus_ItemUpdated() if (xenObject is Pool p) { - var additionalString = PoolAdditionalLicenseString(); + var additionalString = PoolAdditionalLicenseString(p); pdSectionGeneral.UpdateEntryValueWithKey( Messages.POOL_LICENSE, additionalString != string.Empty @@ -555,10 +555,9 @@ private void GeneratePoolUpdatesBox() var allHostCount = xenObject.Connection.Cache.HostCount; if (Helpers.CloudOrGreater(pool.Connection)) - { GenerateCdnUpdatesBox(pool); - } - else if (Helpers.ElyOrGreater(xenObject.Connection)) + + if (Helpers.ElyOrGreater(xenObject.Connection)) { foreach (var u in cache.Pool_updates) { @@ -1188,11 +1187,13 @@ private void GenerateVersionBox() if (host.software_version.ContainsKey("product_version")) { var hotfixEligibilityString = AdditionalVersionString(host); + var versionString = $"{host.ProductBrand()} {host.ProductVersionText()}"; + if (string.IsNullOrEmpty(hotfixEligibilityString)) - pdSectionVersion.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, host.ProductVersionText()); + pdSectionVersion.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, versionString); else pdSectionVersion.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, - string.Format(Messages.MAINWINDOW_CONTEXT_REASON, host.ProductVersionText(), hotfixEligibilityString), + string.Format(Messages.MAINWINDOW_CONTEXT_REASON, versionString, hotfixEligibilityString), Color.Red); } @@ -1498,7 +1499,7 @@ void LaunchProperties() if (xenObject is Pool p) { - var additionalString = PoolAdditionalLicenseString(); + var additionalString = PoolAdditionalLicenseString(p); s.AddEntry(Messages.POOL_LICENSE, additionalString != string.Empty ? string.Format(Messages.MAINWINDOW_CONTEXT_REASON, Helpers.GetFriendlyLicenseName(p), additionalString) @@ -1539,14 +1540,17 @@ void LaunchProperties() var coordinator = p.Connection.Resolve(p.master); if (coordinator != null) { + var versionString = $"{coordinator.ProductBrand()} {coordinator.ProductVersionText()}"; + if (p.IsPoolFullyUpgraded()) { var hotfixEligibilityString = AdditionalVersionString(coordinator); + if (string.IsNullOrEmpty(hotfixEligibilityString)) - s.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, coordinator.ProductVersionText()); + s.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, versionString); else s.AddEntry(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, - string.Format(Messages.MAINWINDOW_CONTEXT_REASON, coordinator.ProductVersionText(), hotfixEligibilityString), + string.Format(Messages.MAINWINDOW_CONTEXT_REASON, versionString, hotfixEligibilityString), Color.Red); } else @@ -1557,7 +1561,7 @@ void LaunchProperties() (sender, args) => cmd.Run()); s.AddEntryLink(Messages.SOFTWARE_VERSION_PRODUCT_VERSION, - string.Format(Messages.POOL_VERSIONS_LINK_TEXT, BrandManager.ProductBrand, coordinator.ProductVersionText()), + string.Format(Messages.POOL_VERSIONS_LINK_TEXT, versionString), cmd, runRpuWizard); } } @@ -1580,7 +1584,7 @@ void LaunchProperties() s.AddEntry(FriendlyName("host.uuid"), xenObject.Get("uuid") as string); } - private string PoolAdditionalLicenseString() + private string PoolAdditionalLicenseString(IXenObject pool) { if (licenseStatus == null) return string.Empty; @@ -1590,7 +1594,8 @@ private string PoolAdditionalLicenseString() case LicenseStatus.HostState.Expired: return Messages.LICENSE_EXPIRED; case LicenseStatus.HostState.Free: - return Messages.LICENSE_UNLICENSED; + // We don't show "Unlicensed" when the pool is in Trial edition + return Helpers.NileOrGreater(pool?.Connection) ? string.Empty : Messages.LICENSE_UNLICENSED; default: return string.Empty; } diff --git a/XenAdmin/TabPages/HAPage.cs b/XenAdmin/TabPages/HAPage.cs index bcde8fd3a8..9f7f43747a 100644 --- a/XenAdmin/TabPages/HAPage.cs +++ b/XenAdmin/TabPages/HAPage.cs @@ -211,7 +211,7 @@ private void Rebuild() else { buttonDisableHa.Visible = false; - labelStatus.Text = String.Format(Messages.HAPANEL_BLURB, Helpers.GetName(pool).Ellipsise(30)); + labelStatus.Text = String.Format(Messages.HA_PANEL_BLURB, Helpers.GetName(pool).Ellipsise(30)); } if ( xenObject is SR sr) diff --git a/XenAdmin/TabPages/ManageCdnUpdatesPage.cs b/XenAdmin/TabPages/ManageCdnUpdatesPage.cs index e829c6979e..0993038d3b 100644 --- a/XenAdmin/TabPages/ManageCdnUpdatesPage.cs +++ b/XenAdmin/TabPages/ManageCdnUpdatesPage.cs @@ -94,7 +94,7 @@ protected override void DeregisterEventHandlers() Updates.CdnUpdateInfoChanged -= Cdn_UpdateInfoChanged; } - public override string HelpID => "ManageUpdatesDialog"; + public override string HelpID => "ManageCdnUpdatesTabPage"; public override NotificationsSubMode NotificationsSubMode => NotificationsSubMode.UpdatesFromCdn; @@ -478,8 +478,12 @@ private void toolStripButtonExportAll_Click(object sender, EventArgs e) var connection = kvp.Key; var poolUpdateInfo = kvp.Value; - stream.WriteLine(connection.Name); - stream.WriteLine(); + // Don't need to print the pool name if it's a standalone host + if (Helpers.GetPool(connection) != null) + { + stream.WriteLine(connection.Name); + stream.WriteLine(); + } var hosts = poolUpdateInfo.HostsWithUpdates .Select(hui => connection.Resolve(new XenRef(hui.HostOpaqueRef))) @@ -492,7 +496,8 @@ private void toolStripButtonExportAll_Click(object sender, EventArgs e) continue; stream.WriteLine(host.Name()); - stream.WriteLine(string.Join("\n", hostUpdateInfo.RecommendedGuidance.Select(Cdn.FriendlyInstruction))); + stream.WriteLine(); + stream.WriteLine(Messages.HOTFIX_POST_UPDATE_ACTIONS, string.Join(Environment.NewLine, hostUpdateInfo.RecommendedGuidance.Select(Cdn.FriendlyInstruction))); stream.WriteLine(); var categories = hostUpdateInfo.GetUpdateCategories(poolUpdateInfo); diff --git a/XenAdmin/TabPages/ManageUpdatesPage.cs b/XenAdmin/TabPages/ManageUpdatesPage.cs index 68ab14916f..c8519d82c3 100644 --- a/XenAdmin/TabPages/ManageUpdatesPage.cs +++ b/XenAdmin/TabPages/ManageUpdatesPage.cs @@ -120,7 +120,7 @@ protected override void DeregisterEventHandlers() Updates.CheckForServerUpdatesCompleted -= CheckForUpdates_CheckForUpdatesCompleted; } - public override string HelpID => "ManageUpdatesDialog"; + public override string HelpID => "ManageUpdatesTabPage"; public override NotificationsSubMode NotificationsSubMode => NotificationsSubMode.Updates; diff --git a/XenAdmin/TabPages/PerformancePage.cs b/XenAdmin/TabPages/PerformancePage.cs index c31038afe4..a4531c08d0 100644 --- a/XenAdmin/TabPages/PerformancePage.cs +++ b/XenAdmin/TabPages/PerformancePage.cs @@ -48,18 +48,16 @@ public partial class PerformancePage : BaseTabPage private IXenObject _xenObject; private bool _disposed; private readonly CollectionChangeEventHandler Message_CollectionChangedWithInvoke; - private readonly ArchiveMaintainer ArchiveMaintainer = new ArchiveMaintainer(); + + private ArchiveMaintainer _archiveMaintainer; public PerformancePage() { InitializeComponent(); - - ArchiveMaintainer.ArchivesUpdated += ArchiveMaintainer_ArchivesUpdated; Message_CollectionChangedWithInvoke = Program.ProgramInvokeHandler(Message_CollectionChanged); - GraphList.ArchiveMaintainer = ArchiveMaintainer; GraphList.SelectedGraphChanged += GraphList_SelectedGraphChanged; GraphList.MouseDown += GraphList_MouseDown; - DataPlotNav.ArchiveMaintainer = ArchiveMaintainer; + this.DataEventList.SetPlotNav(this.DataPlotNav); SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); @@ -68,7 +66,7 @@ public PerformancePage() base.Text = Messages.PERFORMANCE_TAB_TITLE; UpdateMoveButtons(); } - + public override string HelpID => "TabPagePerformance"; /// @@ -80,14 +78,11 @@ protected override void Dispose(bool disposing) if (_disposed) return; - ArchiveMaintainer.Stop(); - if (disposing) { - ArchiveMaintainer.ArchivesUpdated -= ArchiveMaintainer_ArchivesUpdated; - - if (components != null) - components.Dispose(); + DeregisterEvents(); + _archiveMaintainer?.Dispose(); + components?.Dispose(); _disposed = true; } @@ -172,20 +167,31 @@ private get } set { - ArchiveMaintainer.Pause(); DataEventList.Clear(); - - DeregEvents(); + DeregisterEvents(); _xenObject = value; - RegEvents(); + RegisterEvents(); + + var newArchiveMaintainer = new ArchiveMaintainer(value); + newArchiveMaintainer.ArchivesUpdated += ArchiveMaintainer_ArchivesUpdated; + GraphList.ArchiveMaintainer = newArchiveMaintainer; + DataPlotNav.ArchiveMaintainer = newArchiveMaintainer; + try + { + _archiveMaintainer?.Dispose(); + } + catch (ObjectDisposedException) + { + // we have already called a dispose + } - ArchiveMaintainer.XenObject = value; + _archiveMaintainer = newArchiveMaintainer; if (_xenObject != null) { GraphList.LoadGraphs(XenObject); LoadEvents(); - ArchiveMaintainer.Start(); + newArchiveMaintainer.Start(); } RefreshAll(); } @@ -249,7 +255,7 @@ private void CheckMessage(XenAPI.Message m, CollectionChangeAction a) } } - private void RegEvents() + private void RegisterEvents() { if (XenObject == null) return; @@ -300,25 +306,28 @@ private void pool_PropertyChanged(object sender, PropertyChangedEventArgs e) } } - private void DeregEvents() + private void DeregisterEvents() { if (XenObject == null) return; - Pool pool = Helpers.GetPoolOfOne(XenObject.Connection); + var pool = Helpers.GetPoolOfOne(XenObject.Connection); if (pool != null) pool.PropertyChanged -= pool_PropertyChanged; + if (_archiveMaintainer != null) + { + _archiveMaintainer.ArchivesUpdated -= ArchiveMaintainer_ArchivesUpdated; + } + XenObject.Connection.Cache.DeregisterCollectionChanged(Message_CollectionChangedWithInvoke); } public override void PageHidden() { - DeregEvents(); - - if (ArchiveMaintainer != null) - ArchiveMaintainer.Pause(); + DeregisterEvents(); + _archiveMaintainer?.Dispose(); } private void ArchiveMaintainer_ArchivesUpdated() diff --git a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.Designer.cs b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.Designer.cs index e184760abb..2a54c07edf 100644 --- a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.Designer.cs +++ b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.Designer.cs @@ -36,7 +36,6 @@ private void InitializeComponent() this.columnImage = new System.Windows.Forms.DataGridViewImageColumn(); this.SelectButton = new System.Windows.Forms.Button(); this.ClearButton = new System.Windows.Forms.Button(); - this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.DescriptionLabel = new System.Windows.Forms.Label(); this.DescriptionValue = new System.Windows.Forms.Label(); @@ -110,15 +109,6 @@ private void InitializeComponent() this.ClearButton.UseVisualStyleBackColor = true; this.ClearButton.Click += new System.EventHandler(this.ClearButton_Click); // - // linkLabel1 - // - this.linkLabel1.AutoEllipsis = true; - resources.ApplyResources(this.linkLabel1, "linkLabel1"); - this.tableLayoutPanel3.SetColumnSpan(this.linkLabel1, 2); - this.linkLabel1.Name = "linkLabel1"; - this.linkLabel1.TabStop = true; - this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); - // // tableLayoutPanel4 // resources.ApplyResources(this.tableLayoutPanel4, "tableLayoutPanel4"); @@ -166,9 +156,8 @@ private void InitializeComponent() // resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3"); this.tableLayoutPanel3.Controls.Add(this.label1, 0, 0); - this.tableLayoutPanel3.Controls.Add(this.linkLabel1, 0, 2); this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel1, 0, 1); - this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 0, 1); + this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 1, 1); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; // // label1 @@ -203,15 +192,14 @@ private void InitializeComponent() private System.Windows.Forms.Label SizeValue; private System.Windows.Forms.Label TotalSizeLabel; private System.Windows.Forms.Label TotalSizeValue; - private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Button ClearButton; private System.Windows.Forms.Button SelectButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; - private System.Windows.Forms.Label label1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewItems; private System.Windows.Forms.DataGridViewCheckBoxColumn columnCheck; private System.Windows.Forms.DataGridViewTextBoxColumn columnItem; private System.Windows.Forms.DataGridViewImageColumn columnImage; + private System.Windows.Forms.Label label1; } } diff --git a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.cs b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.cs index 3e23acdb51..7d079aea5b 100644 --- a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.cs +++ b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.cs @@ -61,8 +61,6 @@ public partial class BugToolPageSelectCapabilities : XenTabPage public BugToolPageSelectCapabilities() { InitializeComponent(); - linkLabel1.Text = string.Format(linkLabel1.Text, BrandManager.Cis); - linkLabel1.Visible = !HiddenFeatures.LinkLabelHidden; } public override string Text => Messages.BUGTOOL_PAGE_CAPABILITIES_TEXT; @@ -421,19 +419,6 @@ private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArg OnCheckedCapabilitiesChanged(); } - private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - try - { - System.Diagnostics.Process.Start(InvisibleMessages.PRIVACY); - } - catch - { - using (var dlg = new ErrorDialog(Messages.HOMEPAGE_ERROR_MESSAGE)) - dlg.ShowDialog(this); - } - } - private void SelectButton_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridViewItems.Rows) diff --git a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.resx b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.resx index 9fbc743ccf..90a4988d88 100644 --- a/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.resx +++ b/XenAdmin/Wizards/BugToolWizard/BugToolPageSelectCapabilities.resx @@ -154,7 +154,7 @@ 3, 3 - 424, 318 + 424, 331 0 @@ -172,7 +172,7 @@ 0 - 271, 327 + 271, 340 75, 23 @@ -196,7 +196,7 @@ 1 - 352, 327 + 352, 340 75, 23 @@ -229,7 +229,7 @@ 2 - 430, 353 + 430, 366 1 @@ -244,56 +244,11 @@ tableLayoutPanel3 - 2 + 1 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="dataGridViewItems" Row="0" RowSpan="1" Column="0" ColumnSpan="3" /><Control Name="SelectButton" Row="1" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="ClearButton" Row="1" RowSpan="1" Column="2" ColumnSpan="1" /></Controls><Columns Styles="Percent,100,AutoSize,0,AutoSize,0" /><Rows Styles="Percent,100,AutoSize,0,Absolute,20" /></TableLayoutSettings> - - True - - - True - - - GrowAndShrink - - - 2 - - - True - - - Fill - - - 3, 0 - - - 3, 0, 3, 24 - - - 618, 26 - - - 0 - - - Choose which items you would like to include in your status report. You can see the size of your report, as well as specific details on each item to the right of the item list. - - - label1 - - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - tableLayoutPanel3 - - - 0 - 2 @@ -430,7 +385,7 @@ Microsoft Sans Serif, 8.25pt, style=Bold - 3, 337 + 3, 350 3, 3, 3, 3 @@ -463,7 +418,7 @@ True - 179, 337 + 179, 350 3, 3, 3, 3 @@ -499,7 +454,7 @@ 5 - 182, 353 + 182, 366 2 @@ -514,11 +469,56 @@ tableLayoutPanel3 - 3 + 2 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescriptionLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescriptionValue" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SizeLabel" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="SizeValue" Row="3" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="TotalSizeLabel" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="TotalSizeValue" Row="4" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,20" /></TableLayoutSettings> + + True + + + GrowAndShrink + + + 2 + + + True + + + Fill + + + NoControl + + + 3, 0 + + + 3, 0, 3, 24 + + + 618, 26 + + + 0 + + + Choose which items you would like to include in your status report. You can see the size of your report, as well as specific details on each item to the right of the item list. + + + label1 + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + tableLayoutPanel3 + + + 0 + Fill @@ -550,31 +550,7 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="label1" Row="0" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="linkLabel1" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="tableLayoutPanel1" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="tableLayoutPanel4" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,70,Percent,30" /><Rows Styles="AutoSize,0,Percent,100,AutoSize,0" /></TableLayoutSettings> - - - 3, 409 - - - 110, 13 - - - 3 - - - {0} Privacy Statement - - - linkLabel1 - - - System.Windows.Forms.LinkLabel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - tableLayoutPanel3 - - - 1 + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="label1" Row="0" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="tableLayoutPanel1" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="tableLayoutPanel4" Row="1" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="Percent,70,Percent,30" /><Rows Styles="AutoSize,0,Percent,100,AutoSize,0" /></TableLayoutSettings> True diff --git a/XenAdmin/Wizards/HAWizard_Pages/Intro.resx b/XenAdmin/Wizards/HAWizard_Pages/Intro.resx index 6111714d9a..aab5214556 100644 --- a/XenAdmin/Wizards/HAWizard_Pages/Intro.resx +++ b/XenAdmin/Wizards/HAWizard_Pages/Intro.resx @@ -140,7 +140,7 @@ Before you begin, ensure that the following requirements are satisfied for all servers and virtual machines in the pool: -• Shared storage must be available, including at least one iSCSI, NFS or Fibre Channel LUN of 356MB or greater. This LUN will be used for the heartbeat SR. +• Shared storage must be available, including at least one iSCSI, NFS or Fibre Channel LUN. This LUN will be used for the heartbeat SR. • All the virtual machines you want to protect with HA must be agile. @@ -212,4 +212,4 @@ To continue, click Next. XenAdmin.Controls.XenTabPage, XenCenterMain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - + \ No newline at end of file diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard.cs index 459b55732b..bfc4ab805b 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard.cs @@ -293,6 +293,11 @@ protected override void FinishWizard() base.FinishWizard(); } + protected override string WizardPaneHelpID() + { + return PatchingWizard_FirstPage.IsNewGeneration ? "PatchingWizard_xs" : "PatchingWizard_ch"; + } + private void CleanUploadedPatches(bool forceCleanSelectedPatch = false) { var list = new List(); diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs index e342d37dd2..b50f447cbf 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs @@ -32,6 +32,7 @@ using XenAPI; using System.Linq; using System.Text; +using XenAdmin.Actions; using XenAdmin.Core; using XenAdmin.Alerts; using XenAdmin.Wizards.PatchingWizard.PlanActions; @@ -61,8 +62,6 @@ public PatchingWizard_AutomatedUpdatesPage() public override string PageTitle => Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_TITLE; - public override string HelpID => string.Empty; - #endregion #region AutomatedUpdatesBesePage overrides @@ -172,28 +171,49 @@ protected override List GenerateHostPlans(Pool pool, out List ap private HostPlan GetCdnUpdatePlanActionsForHost(Host host, CdnPoolUpdateInfo poolUpdateInfo, CdnHostUpdateInfo hostUpdateInfo) { + // pre-update tasks and, last in the list, the update itself var planActionsPerHost = new List(); + // post-update tasks var delayedActionsPerHost = new List(); - if (hostUpdateInfo.RecommendedGuidance.Length > 0 && PostUpdateTasksAutomatically) + // hostUpdateInfo.RecommendedGuidance is what's prescribed by the metadata, + // host.pending_guidances is what's left there from previous updates + + // evacuate host is a pre-update task and needs to be done either the user has + // opted to carry out the post-update tasks automatically or manually, see CA-381225 + // restart toolstack should run before other post-update tasks, see CA-381718 + + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartToolstack) || + host.pending_guidances.Contains(update_guidances.restart_toolstack)) { - if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) - { - planActionsPerHost.Add(new EvacuateHostPlanAction(host)); - delayedActionsPerHost.Add(new RestartHostPlanAction(host, host.GetRunningVMs())); - } - else if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartToolstack)) - { + if (PostUpdateTasksAutomatically) delayedActionsPerHost.Add(new RestartAgentPlanAction(host)); - } - else if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.EvacuateHost)) - { - planActionsPerHost.Add(new EvacuateHostPlanAction(host)); - } - else if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartDeviceModel)) - { + } + + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost) || + host.pending_guidances.Contains(update_guidances.reboot_host) || + host.pending_guidances.Contains(update_guidances.reboot_host_on_livepatch_failure)) + { + planActionsPerHost.Add(new EvacuateHostPlanAction(host)); + + if (PostUpdateTasksAutomatically) + delayedActionsPerHost.Add(new RestartHostPlanAction(host, host.GetRunningVMs())); + } + + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.EvacuateHost) && + !planActionsPerHost.Any(a => a is EvacuateHostPlanAction)) + { + planActionsPerHost.Add(new EvacuateHostPlanAction(host)); + } + + if (PostUpdateTasksAutomatically) + delayedActionsPerHost.Add(new EnableHostPlanAction(host)); + + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartDeviceModel) || + host.pending_guidances.Contains(update_guidances.restart_device_model)) + { + if (PostUpdateTasksAutomatically) delayedActionsPerHost.Add(new RebootVMsPlanAction(host, host.GetRunningVMs())); - } } planActionsPerHost.Add(new ApplyCdnUpdatesPlanAction(host, poolUpdateInfo)); diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_FirstPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_FirstPage.cs index b96b739c1f..6e9c08388b 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_FirstPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_FirstPage.cs @@ -64,8 +64,6 @@ protected override void OnHandleCreated(EventArgs e) public override string PageTitle => Messages.BEFORE_YOU_START; - public override string HelpID => "Beforeyoustart"; - public bool IsNewGeneration { get => radioButtonCdn.Checked; diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.Designer.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.Designer.cs index 917e59a0de..16678126c1 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.Designer.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.Designer.cs @@ -1,5 +1,3 @@ -using System.Windows.Forms; - namespace XenAdmin.Wizards.PatchingWizard { partial class PatchingWizard_ModePage @@ -125,7 +123,7 @@ private void InitializeComponent() private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private XenAdmin.Controls.Common.AutoHeightLabel autoHeightLabel1; private System.Windows.Forms.CheckBox removeUpdateFileCheckBox; - private RadioButton AutomaticRadioButton; - private ToolTip automaticRadioButtonTooltip; + private System.Windows.Forms.RadioButton AutomaticRadioButton; + private System.Windows.Forms.ToolTip automaticRadioButtonTooltip; } } diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.cs index 054c90dcb8..fbd06fed8c 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_ModePage.cs @@ -57,8 +57,6 @@ public PatchingWizard_ModePage() public override string PageTitle => Messages.PATCHINGWIZARD_MODEPAGE_TITLE; - public override string HelpID => "UpdateMode"; - public override bool EnablePrevious() { return true; @@ -79,30 +77,31 @@ protected override void PageLoadedCore(PageLoadedDirection direction) bool someHostMayRequireRestart; bool automaticDisabled; - if (IsNewGeneration) - { - ManualTextInstructions = ModeCdnUpdates(); - automaticDisabled = anyPoolForbidsAutostart; - } - else + switch (SelectedUpdateType) { - switch (SelectedUpdateType) - { - case UpdateType.Legacy: + case UpdateType.Legacy: + if (IsNewGeneration) + { + ManualTextInstructions = ModeCdnUpdates(); + automaticDisabled = anyPoolForbidsAutostart; + } + else + { ManualTextInstructions = ModePoolPatch(out someHostMayRequireRestart); automaticDisabled = anyPoolForbidsAutostart && someHostMayRequireRestart; - break; - case UpdateType.ISO: - ManualTextInstructions = PoolUpdate != null - ? ModePoolUpdate(out someHostMayRequireRestart) - : ModeSuppPack(out someHostMayRequireRestart); - automaticDisabled = anyPoolForbidsAutostart && someHostMayRequireRestart; - break; - default: - ManualTextInstructions = null; - automaticDisabled = true; - break; - } + } + + break; + case UpdateType.ISO: + ManualTextInstructions = PoolUpdate != null + ? ModePoolUpdate(out someHostMayRequireRestart) + : ModeSuppPack(out someHostMayRequireRestart); + automaticDisabled = anyPoolForbidsAutostart && someHostMayRequireRestart; + break; + default: + ManualTextInstructions = null; + automaticDisabled = true; + break; } if (ManualTextInstructions == null || ManualTextInstructions.Count == 0) @@ -168,12 +167,6 @@ public override bool EnableNext() return AutomaticRadioButton.Checked || ManualRadioButton.Checked; } - private void UpdateEnablement() - { - textBoxLog.Enabled = ManualRadioButton.Checked; - OnPageUpdated(); - } - #region Accessors public WizardMode WizardMode { get; set; } @@ -196,12 +189,14 @@ private void UpdateEnablement() private void AutomaticRadioButton_CheckedChanged(object sender, EventArgs e) { - UpdateEnablement(); + if (AutomaticRadioButton.Checked) + OnPageUpdated(); } private void ManualRadioButton_CheckedChanged(object sender, EventArgs e) { - UpdateEnablement(); + if (ManualRadioButton.Checked) + OnPageUpdated(); } private void button1_Click(object sender, EventArgs e) @@ -296,24 +291,37 @@ private Dictionary ModeCdnUpdates() foreach (var hostUpdateInfo in poolUpdateInfo.HostsWithUpdates) { - if (hostUpdateInfo.RecommendedGuidance.Length > 0) + var host = pool.Connection.Resolve(new XenRef(hostUpdateInfo.HostOpaqueRef)); + if (host != null) { - var host = pool.Connection.Resolve(new XenRef(hostUpdateInfo.HostOpaqueRef)); - if (host != null) - { - var hostSb = new StringBuilder(); + var hostSb = new StringBuilder(); - var msg = host.IsCoordinator() ? $"{host.Name()} ({Messages.COORDINATOR})" : host.Name(); - hostSb.AppendIndented(msg).AppendLine(); + var msg = host.IsCoordinator() ? $"{host.Name()} ({Messages.COORDINATOR})" : host.Name(); + hostSb.AppendIndented(msg).AppendLine(); - foreach (var g in hostUpdateInfo.RecommendedGuidance) - hostSb.AppendIndented(Cdn.FriendlyInstruction(g), 4).AppendLine(); + //evacuate host is a pre-update task and will be done regardless the mode selected - if (hostUpdateInfo.LivePatches.Length > 0 && !hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) - hostSb.AppendIndented(Messages.HOTFIX_POST_UPDATE_LIVEPATCH_ACTIONS, 4).AppendLine(); + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartToolstack) || + host.pending_guidances.Contains(update_guidances.restart_toolstack)) + { + hostSb.AppendIndented(Cdn.FriendlyInstruction(CdnGuidance.RestartToolstack), 4).AppendLine(); + } - hostDict[host] = hostSb; + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost) || + host.pending_guidances.Contains(update_guidances.reboot_host) || + host.pending_guidances.Contains(update_guidances.reboot_host_on_livepatch_failure)) + { + hostSb.AppendIndented(Cdn.FriendlyInstruction(CdnGuidance.RebootHost), 4).AppendLine(); } + + if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartDeviceModel) || + host.pending_guidances.Contains(update_guidances.restart_device_model)) + hostSb.AppendIndented(Cdn.FriendlyInstruction(CdnGuidance.RestartDeviceModel), 4).AppendLine(); + + if (hostUpdateInfo.LivePatches.Length > 0 && !hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) + hostSb.AppendIndented(Messages.HOTFIX_POST_UPDATE_LIVEPATCH_ACTIONS, 4).AppendLine(); + + hostDict[host] = hostSb; } } diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PatchingPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PatchingPage.cs index 08782ea33e..9393aa4eb4 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PatchingPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PatchingPage.cs @@ -83,11 +83,6 @@ public override string PageTitle } } - public override string HelpID - { - get { return "InstallUpdate"; } - } - #endregion #region AutomatedUpdatesBesePage overrides diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs index 9cceb9c848..4bef97a927 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs @@ -104,8 +104,6 @@ public PatchingWizard_PrecheckPage() public override string Text => Messages.PATCHINGWIZARD_PRECHECKPAGE_TEXT; - public override string HelpID => "UpdatePrechecks"; - private void Connection_ConnectionStateChanged(IXenConnection conn) { Program.Invoke(this, RefreshRechecks); @@ -364,11 +362,9 @@ private List GenerateCommonChecks(List applicableServers) //HA checks var haChecks = new List(); - foreach (Host host in SelectedServers) - { - if (Helpers.HostIsCoordinator(host)) - haChecks.Add(new HAOffCheck(host)); - } + foreach (Pool pool in SelectedPools) + haChecks.Add(new HaWlbOffCheck(pool)); + groups.Add(new CheckGroup(Messages.CHECKING_HA_STATUS, haChecks)); //PBDsPluggedCheck @@ -414,16 +410,12 @@ private List GenerateCommonChecks(List applicableServers) if (host == null) continue; - if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RebootHost)) - { + var guidance = hostUpdateInfo.RecommendedGuidance; + + if (guidance.Contains(CdnGuidance.RebootHost)) rebootChecks.Add(new HostNeedsRebootCheck(host)); + if (guidance.Contains(CdnGuidance.RebootHost) || guidance.Contains(CdnGuidance.EvacuateHost)) evacuateChecks.Add(new AssertCanEvacuateCheck(host)); - } - else if (hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.EvacuateHost) || - hostUpdateInfo.RecommendedGuidance.Contains(CdnGuidance.RestartToolstack)) - { - evacuateChecks.Add(new AssertCanEvacuateCheck(host)); - } } } else diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectPatchPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectPatchPage.cs index 83055f54b1..8b0f54eba1 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectPatchPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectPatchPage.cs @@ -216,8 +216,6 @@ private void FinishCheckForUpdates() public override string PageTitle => Messages.PATCHINGWIZARD_SELECTPATCHPAGE_TITLE; - public override string HelpID => "SelectUpdate"; - protected override void PageLoadedCore(PageLoadedDirection direction) { RegisterEvents(); diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.Designer.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.Designer.cs index 518f13fc4c..ab6cc3de31 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.Designer.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.Designer.cs @@ -41,6 +41,7 @@ private void InitializeComponent() this.ColumnExpander = new System.Windows.Forms.DataGridViewImageColumn(); this.ColumnPoolIconHostCheck = new System.Windows.Forms.DataGridViewImageColumn(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnNotes = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnVersion = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label1 = new System.Windows.Forms.Label(); this.buttonSelectAll = new System.Windows.Forms.Button(); @@ -77,6 +78,7 @@ private void InitializeComponent() this.ColumnExpander, this.ColumnPoolIconHostCheck, this.ColumnName, + this.ColumnNotes, this.ColumnVersion}); this.tableLayoutPanel1.SetColumnSpan(this.dataGridViewHosts, 2); this.dataGridViewHosts.Name = "dataGridViewHosts"; @@ -105,11 +107,15 @@ private void InitializeComponent() // // ColumnName // - this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; - this.ColumnName.FillWeight = 110.2538F; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; // + // ColumnNotes + // + resources.ApplyResources(this.ColumnNotes, "ColumnNotes"); + this.ColumnNotes.Name = "ColumnNotes"; + this.ColumnNotes.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; + // // ColumnVersion // this.ColumnVersion.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; @@ -161,6 +167,7 @@ private void InitializeComponent() private DataGridViewImageColumn ColumnExpander; private DataGridViewImageColumn ColumnPoolIconHostCheck; private DataGridViewTextBoxColumn ColumnName; + private DataGridViewTextBoxColumn ColumnNotes; private DataGridViewTextBoxColumn ColumnVersion; private Label label1; private CheckBox applyUpdatesCheckBox; diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.cs index 7a877a58f2..d65cfba41d 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.cs @@ -72,8 +72,6 @@ public PatchingWizard_SelectServers() public override string PageTitle => Messages.PATCHINGWIZARD_SELECTSERVERPAGE_TITLE; - public override string HelpID => "SelectServers"; - protected override void PageLoadedCore(PageLoadedDirection direction) { poolSelectionOnly = WizardMode == WizardMode.AutomatedUpdates || @@ -152,9 +150,8 @@ protected override void PageLoadedCore(PageLoadedDirection direction) { var hostRow = new PatchingHostsDataGridViewRow(host, hasPool, !poolSelectionOnly) {ParentPoolRow = poolRow}; dataGridViewHosts.Rows.Add(hostRow); - string tooltipText; - hostRow.Enabled = CanEnableRow(host, out tooltipText); - hostRow.Cells[3].ToolTipText = tooltipText; + hostRow.Enabled = CanEnableRow(host, out var cannotEnableReason); + hostRow.Notes = cannotEnableReason; //Enable the pool row if (poolRow != null && hostRow.Enabled) @@ -165,7 +162,7 @@ protected override void PageLoadedCore(PageLoadedDirection direction) } if (poolRow != null && !poolRow.Enabled && coordinatorRow != null) - poolRow.Cells[3].ToolTipText = coordinatorRow.Cells[3].ToolTipText; + poolRow.Notes = coordinatorRow.Notes; } // restore server selection @@ -191,69 +188,90 @@ private bool CanEnableRow(Host host, out string tooltipText) : CanEnableRowNonAutomated(host, out tooltipText); } - private bool CanEnableRowAutomatedUpdates(Host host, out string tooltipText) + private bool CanEnableRowAutomatedUpdates(Host host, out string cannotEnableReason) { var poolOfOne = Helpers.GetPoolOfOne(host.Connection); // This check is first because it generally can't be fixed, it's a property of the host if (poolOfOne != null && poolOfOne.IsAutoUpdateRestartsForbidden()) // Forbids update auto restarts { - tooltipText = Messages.POOL_FORBIDS_AUTOMATED_UPDATES; + cannotEnableReason = Messages.POOL_FORBIDS_AUTOMATED_UPDATES; return false; } var pool = Helpers.GetPool(host.Connection); if (WizardMode != WizardMode.NewVersion && pool != null && !pool.IsPoolFullyUpgraded()) //partially upgraded pool is not supported { - tooltipText = string.Format(Messages.PATCHINGWIZARD_SELECTSERVERPAGE_AUTOMATED_UPDATES_NOT_SUPPORTED_PARTIALLY_UPGRADED, BrandManager.ProductBrand); + cannotEnableReason = string.Format(Messages.PATCHINGWIZARD_SELECTSERVERPAGE_AUTOMATED_UPDATES_NOT_SUPPORTED_PARTIALLY_UPGRADED, BrandManager.ProductBrand); return false; } if (Helpers.CloudOrGreater(host)) { + if (poolOfOne?.repositories.Count == 0) + { + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_CDN_REPOS_NOT_CONFIGURED; + return false; + } + + if (Helpers.XapiEqualOrGreater_23_18_0(host.Connection)) + { + if (poolOfOne?.last_update_sync == Util.GetUnixMinDateTime()) + { + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_CDN_NOT_SYNCHRONIZED; + return false; + } + + if (host.latest_synced_updates_applied == latest_synced_updates_applied_state.yes) + { + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_CDN_UPDATES_APPLIED; + return false; + } + } + if (!Updates.CdnUpdateInfoPerConnection.TryGetValue(host.Connection, out var updateInfo) || updateInfo.HostsWithUpdates.FirstOrDefault(u => u.HostOpaqueRef == host.opaque_ref) == null) { - tooltipText = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_UP_TO_DATE; + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_CDN_UPDATES_APPLIED; return false; } } else { - //check updgrade sequences + //check upgrade sequences var minimalPatches = WizardMode == WizardMode.NewVersion ? Updates.GetMinimalPatches(host) : Updates.GetMinimalPatches(host.Connection); if (minimalPatches == null) //version not supported or too new to have automated updates available { - tooltipText = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_UP_TO_DATE; + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_UP_TO_DATE; return false; } //check all hosts are licensed for automated updates (there may be restrictions on individual hosts) if (host.Connection.Cache.Hosts.Any(Host.RestrictBatchHotfixApply)) { - tooltipText = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_HOST_UNLICENSED_FOR_AUTOMATED_UPDATES; + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_HOST_UNLICENSED_FOR_AUTOMATED_UPDATES; return false; } var us = Updates.GetPatchSequenceForHost(host, minimalPatches); if (us == null) { - tooltipText = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_NOT_AUTO_UPGRADABLE; + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_NOT_AUTO_UPGRADABLE; return false; } //if host is up to date if (us.Count == 0) { - tooltipText = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_UP_TO_DATE; + cannotEnableReason = Messages.PATCHINGWIZARD_SELECTSERVERPAGE_SERVER_UP_TO_DATE; return false; } } - tooltipText = null; + cannotEnableReason = null; return true; } @@ -276,8 +294,7 @@ private bool CanEnableRowNonAutomated(Host host, out string tooltipText) return false; } - string reason; - if (!IsHostAmongApplicable(host, out reason)) + if (!IsHostAmongApplicable(host, out var reason)) { tooltipText = reason; return false; @@ -349,7 +366,7 @@ private bool IsHostAmongApplicable(Host host, out string tooltipText) { var nonApplicables = host.Connection.Cache.Hosts.Count(h => !applicableHosts.Contains(h) && !string.IsNullOrEmpty(patchUuidFromAlert) && - !isPatchApplied(patchUuidFromAlert, h)); + !IsPatchApplied(patchUuidFromAlert, h)); if (0 < nonApplicables && nonApplicables < host.Connection.Cache.Hosts.Length) { @@ -361,7 +378,7 @@ private bool IsHostAmongApplicable(Host host, out string tooltipText) if (!applicableHosts.Contains(host) && !string.IsNullOrEmpty(patchUuidFromAlert)) { - if (isPatchApplied(patchUuidFromAlert, host)) + if (IsPatchApplied(patchUuidFromAlert, host)) { if (ApplyUpdatesToNewVersion) return CanEnableRowAutomatedUpdates(host, out tooltipText); @@ -377,7 +394,7 @@ private bool IsHostAmongApplicable(Host host, out string tooltipText) return true; } - private bool isPatchApplied(string uuid, Host host) + private bool IsPatchApplied(string uuid, Host host) { if (Helpers.ElyOrGreater(host)) { @@ -654,26 +671,24 @@ private void applyUpdatesCheckBox_CheckedChanged(object sender, EventArgs e) foreach (PatchingHostsDataGridViewRow row in dataGridViewHosts.Rows) { - var host = row.Tag as Host; - if (host != null) + if (row.Tag is Host host) { - string tooltipText; - row.Enabled = CanEnableRow(host, out tooltipText); - row.Cells[3].ToolTipText = tooltipText; + row.Enabled = CanEnableRow(host, out var cannotEnableReason); + row.Notes = cannotEnableReason; if (row.ParentPoolRow != null) { if (row.Enabled) { row.ParentPoolRow.Enabled = true; - row.ParentPoolRow.Cells[3].ToolTipText = null; + row.Notes = null; } if (masterRow == null) { masterRow = row; if (!row.Enabled) - row.ParentPoolRow.Cells[3].ToolTipText = row.Cells[3].ToolTipText; + row.ParentPoolRow.Notes = row.Notes; } } } @@ -841,53 +856,49 @@ private class DataGridViewNameCell : DataGridViewTextBoxCell { protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { - Pool pool = value as Pool; - - if (pool != null) + if (value is Pool) + { base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); - else + } + else if (value is Host host) { - Host host = value as Host; - if (host != null) + PatchingHostsDataGridViewRow row = (PatchingHostsDataGridViewRow)DataGridView.Rows[RowIndex]; + if (row.HasPool) { - PatchingHostsDataGridViewRow row = (PatchingHostsDataGridViewRow)this.DataGridView.Rows[this.RowIndex]; - if (row.HasPool) - { - Image hostIcon = Images.GetImage16For(host); - base.Paint(graphics, clipBounds, - new Rectangle(cellBounds.X + 16, cellBounds.Y, cellBounds.Width - 16, - cellBounds.Height), rowIndex, cellState, value, formattedValue, - errorText, cellStyle, advancedBorderStyle, paintParts); - - if ((cellState & DataGridViewElementStates.Selected) != 0 && row.Enabled) - { - using (var brush = new SolidBrush(DataGridView.DefaultCellStyle.SelectionBackColor)) - graphics.FillRectangle( - brush, cellBounds.X, - cellBounds.Y, hostIcon.Width, cellBounds.Height); - } - else - { - using (var brush = new SolidBrush(DataGridView.DefaultCellStyle.BackColor)) - graphics.FillRectangle(brush, - cellBounds.X, cellBounds.Y, hostIcon.Width, cellBounds.Height); - } + Image hostIcon = Images.GetImage16For(host); + base.Paint(graphics, clipBounds, + new Rectangle(cellBounds.X + 16, cellBounds.Y, cellBounds.Width - 16, + cellBounds.Height), rowIndex, cellState, value, formattedValue, + errorText, cellStyle, advancedBorderStyle, paintParts); - if (row.Enabled) - graphics.DrawImage(hostIcon, cellBounds.X, cellBounds.Y + 3, hostIcon.Width, - hostIcon.Height); - else - graphics.DrawImage(hostIcon, - new Rectangle(cellBounds.X, cellBounds.Y + 3, - hostIcon.Width, hostIcon.Height), - 0, 0, hostIcon.Width, hostIcon.Height, GraphicsUnit.Pixel, - Drawing.GreyScaleAttributes); + if ((cellState & DataGridViewElementStates.Selected) != 0 && row.Enabled) + { + using (var brush = new SolidBrush(DataGridView.DefaultCellStyle.SelectionBackColor)) + graphics.FillRectangle( + brush, cellBounds.X, + cellBounds.Y, hostIcon.Width, cellBounds.Height); } else { - base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, - errorText, cellStyle, advancedBorderStyle, paintParts); + using (var brush = new SolidBrush(DataGridView.DefaultCellStyle.BackColor)) + graphics.FillRectangle(brush, + cellBounds.X, cellBounds.Y, hostIcon.Width, cellBounds.Height); } + + if (row.Enabled) + graphics.DrawImage(hostIcon, cellBounds.X, cellBounds.Y + 3, hostIcon.Width, + hostIcon.Height); + else + graphics.DrawImage(hostIcon, + new Rectangle(cellBounds.X, cellBounds.Y + 3, + hostIcon.Width, hostIcon.Height), + 0, 0, hostIcon.Width, hostIcon.Height, GraphicsUnit.Pixel, + Drawing.GreyScaleAttributes); + } + else + { + base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, + errorText, cellStyle, advancedBorderStyle, paintParts); } } } @@ -927,7 +938,7 @@ protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle private DataGridViewCell _poolIconHostCheckCell; private DataGridViewTextBoxCell _versionCell; - + private DataGridViewTextBoxCell _notesCell; private readonly bool _showHostCheckBox = true; public PatchingHostsDataGridViewRow(Pool pool) @@ -943,22 +954,15 @@ public PatchingHostsDataGridViewRow(Host host, bool hasPool, bool showHostCheckB SetupCells(); } - public int VersionCellIndex - { - get { return Cells.IndexOf(_versionCell); } - } + public PatchingHostsDataGridViewRow ParentPoolRow { get; set; } - public override bool IsCheckable - { - get { return !HasPool; } - } + public int VersionCellIndex => Cells.IndexOf(_versionCell); + + public override bool IsCheckable => !HasPool; public override bool Enabled { - get - { - return base.Enabled; - } + get => base.Enabled; set { base.Enabled = value; @@ -966,23 +970,18 @@ public override bool Enabled } } - public int CheckValue - { - get { - return IsPoolOrStandaloneHost - ? (int) Cells[POOL_CHECKBOX_COL].Value - : (int) Cells[POOL_ICON_HOST_CHECKBOX_COL].Value; - } - } + public int CheckValue => IsPoolOrStandaloneHost + ? (int)Cells[POOL_CHECKBOX_COL].Value + : (int)Cells[POOL_ICON_HOST_CHECKBOX_COL].Value; - public bool IsSelectableHost - { - get { return IsAHostRow && Enabled && (_showHostCheckBox || !HasPool); } - } + public bool IsSelectableHost => IsAHostRow && Enabled && (_showHostCheckBox || !HasPool); - public bool IsSelectablePool + public bool IsSelectablePool => IsAPoolRow && Enabled; + + public string Notes { - get { return IsAPoolRow && Enabled; } + get => _notesCell.Value as string; + set => _notesCell.Value = value; } private void SetupCells() @@ -996,10 +995,11 @@ private void SetupCells() _nameCell = new DataGridViewNameCell(); _versionCell = new DataGridViewTextBoxCell(); + _notesCell = new DataGridViewTextBoxCell(); - Cells.AddRange(_expansionCell, _poolCheckBoxCell, _poolIconHostCheckCell, _nameCell, _versionCell); + Cells.AddRange(_expansionCell, _poolCheckBoxCell, _poolIconHostCheckCell, _nameCell, _notesCell, _versionCell); - this.UpdateDetails(); + UpdateDetails(); } private void UpdateDetails() @@ -1040,8 +1040,6 @@ internal void UpdateIcon() _poolIconHostCheckCell.Value = Images.GetImage16For((IXenObject)Tag); } } - - public PatchingHostsDataGridViewRow ParentPoolRow { get; set; } } #endregion diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.resx b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.resx index d3328372ff..9ed0e86018 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.resx +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectServers.resx @@ -198,6 +198,12 @@ Name + + True + + + Notes + True @@ -378,6 +384,12 @@ System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + ColumnNotes + + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + ColumnVersion diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs index fdf26412c1..3bf130ffb7 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs @@ -120,14 +120,9 @@ public Dictionary SuppPackVdis #region XenTabPage overrides - public override string Text { get { return Messages.PATCHINGWIZARD_UPLOADPAGE_TEXT; } } + public override string Text => Messages.PATCHINGWIZARD_UPLOADPAGE_TEXT; - public override string PageTitle - { - get { return Messages.PATCHINGWIZARD_UPLOADPAGE_TITLE_ONLY_UPLOAD; } - } - - public override string HelpID { get { return "UploadPatch"; } } + public override string PageTitle => Messages.PATCHINGWIZARD_UPLOADPAGE_TITLE_ONLY_UPLOAD; public override bool EnableNext() { diff --git a/XenAdmin/Wizards/PatchingWizard/PlanActions/ApplyCdnUpdatesPlanAction.cs b/XenAdmin/Wizards/PatchingWizard/PlanActions/ApplyCdnUpdatesPlanAction.cs index 15a9d68de8..4d56439242 100644 --- a/XenAdmin/Wizards/PatchingWizard/PlanActions/ApplyCdnUpdatesPlanAction.cs +++ b/XenAdmin/Wizards/PatchingWizard/PlanActions/ApplyCdnUpdatesPlanAction.cs @@ -57,6 +57,7 @@ protected override void RunWithSession(ref Session session) log.DebugFormat("Disabling host {0}", host.Name()); AddProgressStep(string.Format(Messages.UPDATES_WIZARD_ENTERING_MAINTENANCE_MODE, host.Name())); Host.disable(session, HostXenRef.opaque_ref); + Connection.WaitFor(() => !host.enabled, null); } AddProgressStep(string.Format(Messages.UPDATES_WIZARD_APPLYING_UPDATES_FROM_CDN, host.Name())); diff --git a/XenAdmin/Wizards/PatchingWizard/PlanActions/EvacuateHostPlanAction.cs b/XenAdmin/Wizards/PatchingWizard/PlanActions/EvacuateHostPlanAction.cs deleted file mode 100644 index 92a90b708b..0000000000 --- a/XenAdmin/Wizards/PatchingWizard/PlanActions/EvacuateHostPlanAction.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using XenAPI; - - -namespace XenAdmin.Wizards.PatchingWizard.PlanActions -{ - public class EvacuateHostPlanAction : HostPlanAction - { - public EvacuateHostPlanAction(Host host) - : base(host) - { - } - - protected override void RunWithSession(ref Session session) - { - EvacuateHost(ref session); - } - } -} diff --git a/XenAdmin/Wizards/PatchingWizard/PlanActions/HostPlanAction.cs b/XenAdmin/Wizards/PatchingWizard/PlanActions/HostPlanAction.cs index 5cf6477229..8f3dde9521 100644 --- a/XenAdmin/Wizards/PatchingWizard/PlanActions/HostPlanAction.cs +++ b/XenAdmin/Wizards/PatchingWizard/PlanActions/HostPlanAction.cs @@ -67,6 +67,7 @@ protected void EvacuateHost(ref Session session) AddProgressStep(string.Format(Messages.UPDATES_WIZARD_ENTERING_MAINTENANCE_MODE, hostObj.Name())); log.DebugFormat("Disabling host {0}", hostObj.Name()); Host.disable(session, HostXenRef.opaque_ref); + Connection.WaitFor(() => !hostObj.enabled, null); } if (vms.Count > 0) @@ -225,4 +226,51 @@ protected void WaitForHostToBecomeEnabled(Session session, bool attemptEnable) } } } + + + public class BringBabiesBackAction : HostPlanAction + { + private readonly List> _vms; + private readonly bool _enableOnly; + + public BringBabiesBackAction(List> vms, Host host, bool enableOnly) + : base(host) + { + _vms = vms; + _enableOnly = enableOnly; + } + + protected override void RunWithSession(ref Session session) + { + BringBabiesBack(ref session, _vms, _enableOnly); + } + } + + + public class EvacuateHostPlanAction : HostPlanAction + { + public EvacuateHostPlanAction(Host host) + : base(host) + { + } + + protected override void RunWithSession(ref Session session) + { + EvacuateHost(ref session); + } + } + + + public class EnableHostPlanAction : HostPlanAction + { + public EnableHostPlanAction(Host host) + : base(host) + { + } + + protected override void RunWithSession(ref Session session) + { + WaitForHostToBecomeEnabled(session, true); + } + } } diff --git a/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs b/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs index 74c5de2d9f..877dd915b3 100644 --- a/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs +++ b/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs @@ -260,9 +260,8 @@ where check.CanRun() groups.Add(new CheckGroup(Messages.CHECKING_PV_GUESTS, pvChecks)); //HA checks - for each pool - var haChecks = (from Host server in SelectedCoordinators - select new HAOffCheck(server) as Check).ToList(); - + var haChecks = (from Pool pool in SelectedPools + select new HaWlbOffCheck(pool) as Check).ToList(); if (haChecks.Count > 0) groups.Add(new CheckGroup(Messages.CHECKING_HA_STATUS, haChecks)); diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index d1705f644a..6f449aa5cd 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU @@ -9,7 +9,7 @@ WinExe Properties XenAdmin - [XenCenter_No_Space] + [XenCenter] ..\Branding\Images\AppIcon.ico v4.8 publish\ @@ -458,6 +458,7 @@ True Resources.resx + UserControl @@ -710,7 +711,7 @@ - + @@ -4245,7 +4246,6 @@ PatchingWizard_FirstPage.cs - Form @@ -4282,7 +4282,6 @@ PatchingWizard_SelectServers.cs - @@ -4575,6 +4574,7 @@ + @@ -6796,7 +6796,6 @@ - - - - - - + diff --git a/XenAdminTests/ArchiveTests/ArchiveIteratorTests.cs b/XenAdminTests/ArchiveTests/ArchiveIteratorTests.cs index 57adc2ba21..040ed9ba17 100644 --- a/XenAdminTests/ArchiveTests/ArchiveIteratorTests.cs +++ b/XenAdminTests/ArchiveTests/ArchiveIteratorTests.cs @@ -32,6 +32,7 @@ using System.IO; using System.Text; using NUnit.Framework; +using XenCenterLib; using XenCenterLib.Archive; namespace XenAdminTests.ArchiveTests @@ -55,7 +56,7 @@ public Stream ExtractedFileReturn disposed = false; } } - public string CurrentFileNameReturn { private get; set; } + public string CurrentFileNameReturn { get; set; } public long CurrentFileSizeReturn { private get; set; } public DateTime ModTimeReturn { private get; set; } public bool IsDirectoryReturn { private get; set; } @@ -97,10 +98,10 @@ public override void ExtractCurrentFile(Stream extractedFileContents, Action can public override string CurrentFileName() { - if (String.IsNullOrEmpty(CurrentFileNameReturn)) + if (string.IsNullOrEmpty(CurrentFileNameReturn)) return CurrentFileNameReturn; - return NumberOfCallsLeftReturn + CurrentFileNameReturn; + return CurrentFileNameReturn + NumberOfCallsLeftReturn; } public override long CurrentFileSize() @@ -121,19 +122,15 @@ public override bool IsDirectory() protected override void Dispose(bool disposing) { base.Dispose(disposing); - if( !disposed ) - { - if( disposing ) - { - if(extractedFile != null) - extractedFile.Dispose(); - } - } + + if (!disposed && disposing) + extractedFile?.Dispose(); } } #endregion private ArchiveIteratorFake fakeIterator; + private string tempPath; [OneTimeSetUp] public void Setup() @@ -150,66 +147,101 @@ public void TearDown() [SetUp] public void TestSetup() { + tempPath = null; fakeIterator.Reset(); } + [TearDown] + public void TestTearDown() + { + if (Directory.Exists(tempPath)) + Directory.Delete(tempPath, true); + } + [Test] - public void AnExceptionIsThrownForNullArgumentWhenCallingExtractAllContents() + public void TestExtractToNullDestinationPath() { Assert.Throws(typeof(ArgumentNullException), () => fakeIterator.ExtractAllContents(null)); } [Test] - public void AnExceptionIsThrownForANullFileNameWhenCallingExtractAllContents() + public void TestExtractNullFile() { fakeIterator.CurrentFileNameReturn = null; - Assert.Throws(typeof(ArgumentNullException), () => fakeIterator.ExtractAllContents(Path.GetTempPath())); + Assert.Throws(typeof(NullReferenceException), () => fakeIterator.ExtractAllContents(Path.GetTempPath())); } - - [Test] - public void VerifyAFileIsWrittenWhenCallingExtractAllContents() + + [TestCase(true, true)] + [TestCase(true, false)] + [TestCase(false, true)] + [TestCase(false, false)] + public void TestExtractFile(bool longDirectoryPath, bool longFilePath) { - string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + + var dirCharNumber = (longDirectoryPath ? 248 : 247) - tempPath.Length - 2; + //2 was removed for the combining slash between tempPath and dir, and the combining slash between dir and filename + var dir = new string('A', dirCharNumber); + var fileCharNumber = (longFilePath ? 260 : 259) - Path.Combine(tempPath, dir).Length - 2; + //2 was removed for the combining slash between the full dir path and filename, and the NumberOfCallsLeftReturn + var fileName = new string('B', fileCharNumber); + const int numberOfFiles = 3; fakeIterator.NumberOfCallsLeftReturn = numberOfFiles; + fakeIterator.CurrentFileNameReturn = Path.Combine(dir, fileName); fakeIterator.ExtractAllContents(tempPath); - //Test file has been created - string targetFile = Path.Combine(tempPath, fakeIterator.CurrentFileName()); - Assert.IsTrue(File.Exists(targetFile), "File Exists"); + for (var i = 0; i < 3; i++) + { + string targetFile = Path.Combine(tempPath, fakeIterator.CurrentFileNameReturn + i); - Assert.IsTrue(File.ReadAllBytes(targetFile).Length > 1, "File length > 1"); + if (longDirectoryPath || longFilePath) + targetFile = StringUtility.ToLongWindowsPathUnchecked(targetFile); - //Check recursively that there are only the correct number of files - Assert.IsTrue(Directory.GetFiles(tempPath, "*.*", SearchOption.AllDirectories).Length == numberOfFiles, "File number is correct"); + Assert.IsTrue(File.Exists(targetFile), "File should exist"); + Assert.IsNotEmpty(File.ReadAllBytes(targetFile), "File should not be empty"); - Assert.IsFalse((File.GetAttributes(targetFile) & FileAttributes.Directory) == FileAttributes.Directory, "Is not a dir"); + Assert.IsFalse((File.GetAttributes(targetFile) & FileAttributes.Directory) == FileAttributes.Directory, + "It should not have directory attributes"); + } + + //Check recursively that there are only the correct number of files + var actualFileNumber = Directory.GetFiles(tempPath, "*.*", SearchOption.AllDirectories).Length; + Assert.AreEqual(numberOfFiles, actualFileNumber, $"There should be {numberOfFiles}"); - Directory.Delete(tempPath,true); + if (longDirectoryPath || longFilePath) + tempPath = StringUtility.ToLongWindowsPathUnchecked(tempPath); } - [Test] - public void VerifyADirectoryIsWrittenWhenCallingExtractAllContents() + + [TestCase(true)] + [TestCase(false)] + public void TestExtractDirectory(bool longDirectoryPath) { - string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var dirCharNumber = (longDirectoryPath ? 248 : 247) - tempPath.Length - 2; + //2 was removed for the combining slash between tempPath and dir, and the NumberOfCallsLeftReturn + var dir = new string('A', dirCharNumber); + fakeIterator.IsDirectoryReturn = true; - fakeIterator.CurrentFileNameReturn = "FakePath" + Path.DirectorySeparatorChar; + fakeIterator.CurrentFileNameReturn = dir; fakeIterator.ExtractAllContents(tempPath); - //Test file has been created string targetPath = Path.Combine(tempPath, fakeIterator.CurrentFileName()); - Assert.IsFalse(File.Exists(targetPath), "No files exist"); - Assert.IsTrue(Directory.Exists(targetPath), "Directories exist"); - //No files - just a directory - Assert.IsTrue(Directory.GetFiles(tempPath).Length < 1, "No file in the directory" ); + if (longDirectoryPath) + targetPath = StringUtility.ToLongWindowsPathUnchecked(targetPath); - //Check it's a directory - Assert.IsTrue((File.GetAttributes(targetPath) & FileAttributes.Directory) == FileAttributes.Directory, "Has directory attributes"); + Assert.IsFalse(File.Exists(targetPath), "Files should not exist"); + Assert.IsEmpty(Directory.GetFiles(tempPath), "Directory should not have files"); - Directory.Delete(tempPath, true); - } + Assert.IsTrue(Directory.Exists(targetPath), "Directory should exist"); + Assert.IsTrue((File.GetAttributes(targetPath) & FileAttributes.Directory) == FileAttributes.Directory, + "It should have directory attributes"); + if (longDirectoryPath) + tempPath = StringUtility.ToLongWindowsPathUnchecked(tempPath); + } } } diff --git a/XenAdminTests/ArchiveTests/ArchiveWriterTests.cs b/XenAdminTests/ArchiveTests/ArchiveWriterTests.cs index 91a9d23bed..a47b481ddf 100644 --- a/XenAdminTests/ArchiveTests/ArchiveWriterTests.cs +++ b/XenAdminTests/ArchiveTests/ArchiveWriterTests.cs @@ -34,6 +34,7 @@ using System.Linq; using System.Text; using NUnit.Framework; +using XenCenterLib; using XenCenterLib.Archive; namespace XenAdminTests.ArchiveTests @@ -68,18 +69,18 @@ private void DisposeStreamList() { if (AddedStreamData != null) { - foreach (Stream stream in AddedStreamData) + foreach (Stream stream in AddedStreamData) { - if( stream != null ) + if (stream != null) stream.Dispose(); - } + } } } - public override void Add(Stream filetoAdd, string fileName, DateTime modificationTime, Action cancellingDelegate) + public override void Add(Stream fileToAdd, string fileName, DateTime modificationTime, Action cancellingDelegate) { disposed = false; - AddedStreamData.Add(filetoAdd); + AddedStreamData.Add(fileToAdd); AddedFileNameData.Add(fileName); AddedDates.Add(modificationTime); } @@ -93,9 +94,9 @@ public override void AddDirectory(string directoryName, DateTime modificationTim protected override void Dispose(bool disposing) { base.Dispose(disposing); - if(disposing) + if (disposing) { - if( !disposed ) + if (!disposed) { DisposeStreamList(); } @@ -136,20 +137,10 @@ public void DatelessAddCallsImplementation() Assert.AreEqual(1, fakeWriter.AddedDates.Count); Assert.AreEqual(fileName, fakeWriter.AddedFileNameData[0], "File name"); Assert.IsTrue(fakeWriter.AddedStreamData[0].Length == 14, "Stream has data"); - AssertCurrentDateIsPlausible(fakeWriter.AddedDates[0]); + Assert.That(fakeWriter.AddedDates[0], Is.EqualTo(DateTime.Now).Within(TimeSpan.FromSeconds(5))); } } - private void AssertCurrentDateIsPlausible(DateTime currentDate) - { - //If this is failing check that the number of seconds is enough - const double seconds = 5.0; - DateTime maxDate = DateTime.Now.AddSeconds(seconds); - DateTime minDate = DateTime.Now.AddSeconds(-1.0 * seconds); - Assert.IsTrue(currentDate > minDate, "Date is > minimum"); - Assert.IsTrue(currentDate < maxDate, "Date is < maximum"); - } - [Test] public void DatelessAddDirectoryCallsImplementation() { @@ -164,7 +155,7 @@ public void DatelessAddDirectoryCallsImplementation() Assert.AreEqual(0, fakeWriter.AddedStreamData.Count); Assert.AreEqual(totalAdded, fakeWriter.AddedDates.Count); Assert.AreEqual(dirName, fakeWriter.AddedFileNameData[0], "File name"); - AssertCurrentDateIsPlausible(fakeWriter.AddedDates[0]); + Assert.That(fakeWriter.AddedDates[0], Is.EqualTo(DateTime.Now).Within(TimeSpan.FromSeconds(5))); } [Test] @@ -173,6 +164,96 @@ public void CreateArchiveThrowsWithBadPath() Assert.Throws(typeof(FileNotFoundException), () => fakeWriter.CreateArchive("Yellow brick road - not a path!")); } + [TestCase(true, true)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(false, false)] + public void CreateArchiveWithLongPath(bool longDirectoryPath, bool longFilePath) + { + //set up the path to zip + var zipPath = PopulateLongPathArchive(true, longDirectoryPath, longFilePath, out var addedData); + + fakeWriter.CreateArchive(zipPath); + + foreach (var datum in addedData) + Assert.Contains(datum, fakeWriter.AddedFileNameData); + + // 2 folders and one file + Assert.AreEqual(addedData.Count, fakeWriter.AddedFileNameData.Count); + + //clean up: we need to ensure we're deleting the folder + if (longDirectoryPath || longFilePath) + zipPath = StringUtility.ToLongWindowsPathUnchecked(zipPath); + + Directory.Delete(zipPath, true); + } + + [Test] + public void CreateArchiveWithLongPath_PathTooLong() + { + //! N.B.: If this test fails it might be because the project has moved to a version of .NET Core + //! that does not require calls to `StringUtils.ToLongWindowsPath`. Please review its uses + //! and remove it from the codebase if possible. + + // this test ensures PopulateLongPathArchive's correctness + // since CreateArchiveWithLongPath depends on it + + Assert.DoesNotThrow(() => PopulateLongPathArchive(false, false, false, out _)); + Assert.Throws(() => PopulateLongPathArchive(false, false, true, out _)); + Assert.Throws(() => PopulateLongPathArchive(false, true, true, out _)); + Assert.Throws(() => PopulateLongPathArchive(false, true, false, out _)); + } + + /// + /// Set up method creating a directory containing 2 subdirectories one of which has a file + /// + /// set to true to ensure folders and files are prepended with \\?\ + /// the path to the folder + private string PopulateLongPathArchive(bool createValidPaths, bool longDirectoryPath, bool longFilePath, out List addedData) + { + var zipPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + Directory.CreateDirectory(zipPath); + + var dirCharNumber1 = (longDirectoryPath ? 248 : 247) - zipPath.Length - 2; + //2 was removed for the combining slash between tempPath and dir, and the first character + var relativeDirectoryPath1 = 0 + new string('A', dirCharNumber1); + + var dirCharNumber2 = (longDirectoryPath ? 248 : 247) - zipPath.Length - 3; + //3 was removed for the combining slash between zipPath and dir, the first character, + //and the combining slash between dir and filename + var relativeDirectoryPath2 = 1 + new string('A', dirCharNumber2); + + var fileCharNumber = (longFilePath ? 260 : 259) - Path.Combine(zipPath, relativeDirectoryPath2).Length - 1; + //1 was removed for the combining slash between the full dir path and filename + var fileName = new string('B', fileCharNumber); + var relativeFilePath = Path.Combine(relativeDirectoryPath2, fileName); + + addedData = new List + { + relativeDirectoryPath1.Replace(@"\", "/"), + relativeDirectoryPath2.Replace(@"\", "/"), + relativeFilePath.Replace(@"\", "/") + }; + + var directoryPath1 = Path.Combine(zipPath, relativeDirectoryPath1); + var directoryPath2 = Path.Combine(zipPath, relativeDirectoryPath2); + var filePath = Path.Combine(directoryPath2, fileName); + + if (createValidPaths) + { + directoryPath1 = StringUtility.ToLongWindowsPathUnchecked(directoryPath1); + directoryPath2 = StringUtility.ToLongWindowsPathUnchecked(directoryPath2); + filePath = StringUtility.ToLongWindowsPathUnchecked(filePath); + } + + Directory.CreateDirectory(directoryPath1); + Directory.CreateDirectory(directoryPath2); + File.WriteAllText(filePath, "Hello, World!"); + + + return zipPath; + } + [Test] public void CreateArchiveWorksWithValidDirectoryStructure() { @@ -184,17 +265,17 @@ public void CreateArchiveWorksWithValidDirectoryStructure() { string subfolder = Path.Combine(tempPath, Path.GetRandomFileName()); Directory.CreateDirectory(subfolder); - CreateFiles( subfolder, i); + CreateFiles(subfolder, i); } fakeWriter.CreateArchive(tempPath); - Assert.AreEqual(12, fakeWriter.AddedDates.Count ); + Assert.AreEqual(12, fakeWriter.AddedDates.Count); Assert.AreEqual(12, fakeWriter.AddedFileNameData.Count); Assert.AreEqual(8, fakeWriter.AddedStreamData.Count); - - foreach( DateTime date in fakeWriter.AddedDates ) - AssertCurrentDateIsPlausible(date); + + foreach (DateTime date in fakeWriter.AddedDates) + Assert.That(date, Is.EqualTo(DateTime.Now).Within(TimeSpan.FromSeconds(5))); foreach (string name in fakeWriter.AddedFileNameData) Assert.AreEqual(-1, name.IndexOfAny(@":\".ToArray()), "Unwanted chars found in path"); @@ -206,7 +287,7 @@ private void CreateFiles(string tempPath, int numberOfFiles) { for (int i = 0; i < numberOfFiles; i++) { - using( FileStream fs = File.OpenWrite(Path.Combine(tempPath, Path.GetRandomFileName()))) + using (FileStream fs = File.OpenWrite(Path.Combine(tempPath, Path.GetRandomFileName()))) { fs.Write(Encoding.ASCII.GetBytes("This is a test"), 0, 14); fs.Flush(); diff --git a/XenAdminTests/CodeTests/AssemblyTests.cs b/XenAdminTests/CodeTests/AssemblyTests.cs index b926443d68..3b104b882c 100644 --- a/XenAdminTests/CodeTests/AssemblyTests.cs +++ b/XenAdminTests/CodeTests/AssemblyTests.cs @@ -44,7 +44,7 @@ namespace XenAdminTests.CodeTests [TestFixture, Category(TestCategories.Unit)] public class AssemblyTests { - private static readonly string MainAssemblyName = BrandManager.BrandConsoleNoSpace; + private static readonly string MainAssemblyName = BrandManager.BrandConsole; public class TestDataClass { diff --git a/XenAdminTests/XenAdminTests.csproj b/XenAdminTests/XenAdminTests.csproj index cca8d873c8..f736e827e9 100644 --- a/XenAdminTests/XenAdminTests.csproj +++ b/XenAdminTests/XenAdminTests.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU diff --git a/XenCenterLib/Archive/ArchiveIterator.cs b/XenCenterLib/Archive/ArchiveIterator.cs index b0c29cd552..91eb87f485 100644 --- a/XenCenterLib/Archive/ArchiveIterator.cs +++ b/XenCenterLib/Archive/ArchiveIterator.cs @@ -47,21 +47,30 @@ public abstract class ArchiveIterator : IDisposable /// If while combining path and current file name a null arises public void ExtractAllContents(string pathToExtractTo, Action cancellingDelegate = null) { - if (String.IsNullOrEmpty(pathToExtractTo)) + if (string.IsNullOrEmpty(pathToExtractTo)) throw new ArgumentNullException(); while (HasNext()) { - //Make the file path from the details in the archive making the path windows friendly - string conflatedPath = Path.Combine(pathToExtractTo, CurrentFileName()).Replace('/', Path.DirectorySeparatorChar); + //make the path Windows friendly + var fileName = CurrentFileName(); + var isDirectory = IsDirectory(); - //Create directories - empty ones will be made too - Directory.CreateDirectory(Path.GetDirectoryName(conflatedPath)); + var sanitizedName = fileName.Replace('/', Path.DirectorySeparatorChar); + var conflatedPath = Path.Combine(pathToExtractTo, sanitizedName); + + var dir = isDirectory ? conflatedPath : Path.GetDirectoryName(conflatedPath); + dir = StringUtility.ToLongWindowsPath(dir, true); + + //Create directory - empty one will be made too + Directory.CreateDirectory(dir); //If we have a file extract the contents - if (!IsDirectory()) + if (!isDirectory) { - using (FileStream fs = File.Create(conflatedPath)) + conflatedPath = StringUtility.ToLongWindowsPath(conflatedPath, false); + + using (var fs = File.Create(conflatedPath)) ExtractCurrentFile(fs, cancellingDelegate); } } diff --git a/XenCenterLib/Archive/ArchiveWriter.cs b/XenCenterLib/Archive/ArchiveWriter.cs index 5ad3221de1..c27b7363ae 100644 --- a/XenCenterLib/Archive/ArchiveWriter.cs +++ b/XenCenterLib/Archive/ArchiveWriter.cs @@ -35,59 +35,100 @@ namespace XenCenterLib.Archive { public abstract class ArchiveWriter : IDisposable { - public abstract void Add(Stream filetoAdd, string fileName, DateTime modificationTime, Action cancellingDelegate); + private int _progressTracker; + + public abstract void Add(Stream fileToAdd, string fileName, DateTime modificationTime, Action cancellingDelegate); + public abstract void AddDirectory(string directoryName, DateTime modificationTime); public virtual void SetBaseStream(Stream outputStream) { throw new NotImplementedException(); } - public abstract void AddDirectory(string directoryName, DateTime modificationTime); + protected virtual void Dispose(bool disposing) + { + } - /// - /// Disposal hook - /// - /// - protected virtual void Dispose(bool disposing){ } + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } public void CreateArchive(string pathToArchive, Action cancellingDelegate = null, Action progressDelegate = null) { + // We look recursively and do not use Directory.GetDirectories and Directory.GetFiles with + // AllDirectories options because in .NET 4.8 they do not enumerate all elements if they + // have paths longer than 260 characters (248 for directories). + // If moving to .NET Core, please consider reverting this. + + _progressTracker = 0; + PopulateArchive(pathToArchive, pathToArchive, cancellingDelegate, progressDelegate); + } + + /// + /// Populate the archive by recursively calling the overridden and . + /// + /// The path to the root of the folder we're archiving + /// Keeps track of the current directory we're archiving. In the first recursive call it should be the same as + /// Action cal led for cancelling + /// Action for reporting progress. Method will populate its parameter with the current progress of the recursive operation + /// Total progress that needs to be added for archiving this directory. In the first recursive call it should be 100. If the folder we're adding should add 18 percentage points to the total progress, set this value to 18. + /// Offset to the progress. This is added to when setting the progress for this directory. If this folder should add 18 percentage points to the total progress, but it's for a folder past the 50% mark of the total progress (i.e.: completing this folder should set the total to 68), set this value to 50. + /// A directory could not be found. + private void PopulateArchive(string pathToArchive, string pathToCurrentDirectory, Action cancellingDelegate = null, Action progressDelegate = null, float totalProgressIncrease = 100, float progressOffset = 0) + { + cancellingDelegate?.Invoke(); + + pathToArchive = StringUtility.ToLongWindowsPath(pathToArchive, true); if (!Directory.Exists(pathToArchive)) - throw new FileNotFoundException("The path " + pathToArchive + " does not exist"); + throw new FileNotFoundException($"The path {pathToArchive} does not exist"); + + pathToCurrentDirectory = StringUtility.ToLongWindowsPath(pathToCurrentDirectory, true); + + //add the current directory except when it's the root directory + if (pathToArchive != pathToCurrentDirectory) + AddDirectory(CleanRelativePathName(pathToArchive, pathToCurrentDirectory), Directory.GetCreationTime(pathToCurrentDirectory)); + + var files = Directory.GetFiles(pathToCurrentDirectory); - var files = Directory.GetFiles(pathToArchive, "*.*", SearchOption.AllDirectories); - for (var i = 0; i < files.Length; i++) + foreach (var file in files) { - string filePath = files[i]; cancellingDelegate?.Invoke(); - using (FileStream fs = File.OpenRead(filePath)) - { + var filePath = StringUtility.ToLongWindowsPath(file, false); + + using (var fs = File.OpenRead(filePath)) Add(fs, CleanRelativePathName(pathToArchive, filePath), File.GetCreationTime(filePath), cancellingDelegate); - progressDelegate?.Invoke((int)50.0 * i / files.Length); - } } - var directories = Directory.GetDirectories(pathToArchive, "*.*", SearchOption.AllDirectories); - for (var j = 0; j < directories.Length; j++) + if (_progressTracker != (int)progressOffset) { - string dirPath = directories[j]; - cancellingDelegate?.Invoke(); - AddDirectory(CleanRelativePathName(pathToArchive, dirPath), Directory.GetCreationTime(dirPath)); - progressDelegate?.Invoke(50 + (int)50.0 * j / directories.Length); + _progressTracker = (int)progressOffset; + progressDelegate?.Invoke(_progressTracker); } - } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); + var directories = Directory.GetDirectories(pathToCurrentDirectory); + if (directories.Length == 0) + return; + + float increment = totalProgressIncrease / directories.Length; + + for (var i = 0; i < directories.Length; i++) + { + PopulateArchive(pathToArchive, directories[i], cancellingDelegate, progressDelegate, + increment, i * increment + progressOffset); + } } private string CleanRelativePathName(string rootPath, string pathName) { - return pathName.Replace(rootPath, "").Replace('\\', '/').TrimStart('/'); + var cleanedRootPath = rootPath.Replace(@"\\?\", string.Empty); + return pathName + .Replace(@"\\?\", string.Empty) + .Replace(cleanedRootPath, string.Empty) + .Replace('\\', '/') + .TrimStart('/'); } - } } diff --git a/XenCenterLib/Archive/TarArchiveWriter.cs b/XenCenterLib/Archive/TarArchiveWriter.cs index 7137da1c7b..56b36e3e31 100644 --- a/XenCenterLib/Archive/TarArchiveWriter.cs +++ b/XenCenterLib/Archive/TarArchiveWriter.cs @@ -77,10 +77,10 @@ public override void AddDirectory(string directoryName, DateTime modificationTim tar.CloseEntry(); } - public override void Add(Stream filetoAdd, string fileName, DateTime modificationTime, Action cancellingDelegate) + public override void Add(Stream fileToAdd, string fileName, DateTime modificationTime, Action cancellingDelegate) { TarEntry entry = TarEntry.CreateTarEntry(fileName); - entry.Size = filetoAdd.Length; + entry.Size = fileToAdd.Length; entry.ModTime = modificationTime; tar.PutNextEntry(entry); @@ -89,9 +89,9 @@ public override void Add(Stream filetoAdd, string fileName, DateTime modificatio //You have to do this because if using a memory stream the pointer will be at the end it //it's just been read and this will cause nothing to be written out - filetoAdd.Position = 0; + fileToAdd.Position = 0; - while ((n = filetoAdd.Read(buffer, 0, buffer.Length)) > 0) + while ((n = fileToAdd.Read(buffer, 0, buffer.Length)) > 0) { cancellingDelegate?.Invoke(); tar.Write(buffer, 0, n); diff --git a/XenCenterLib/NamedPipes.cs b/XenCenterLib/NamedPipes.cs index 1cd7b53b8a..2ff0ecf829 100644 --- a/XenCenterLib/NamedPipes.cs +++ b/XenCenterLib/NamedPipes.cs @@ -266,7 +266,38 @@ public Pipe(string path) public static bool ExistsPipe(string pipePath) { log.Debug($"Checking {pipePath} exists"); - return Directory.GetFiles(@"\\.\pipe\").Contains(pipePath); + + // CA-382850: We iterate manually in order to catch ArgumentExceptions + // when listing files. Pipes can be created with invalid characters in + // their names. This throws exception when those files are accessed. + // Other processes might create these pipes and inadvertently prevent + // XenCenter from starting + + var e = Directory.EnumerateFiles(@"\\.\pipe\"); + using (var enumerator = e.GetEnumerator()) + { + while (true) + { + try + { + if (!enumerator.MoveNext()) + { + break; + } + + if (enumerator.Current != null && enumerator.Current.Contains(pipePath)) + { + return true; + } + } + catch (ArgumentException) + { + // ignore, the pipe's name contains invalid characters + } + } + } + + return false; } /// diff --git a/XenCenterLib/StringUtility.cs b/XenCenterLib/StringUtility.cs index c084aaecb4..110d0859cf 100644 --- a/XenCenterLib/StringUtility.cs +++ b/XenCenterLib/StringUtility.cs @@ -33,6 +33,8 @@ using System.Text.RegularExpressions; using System.Linq; using System.Collections; +using System.IO; + namespace XenCenterLib { @@ -218,5 +220,39 @@ public static bool IsIPAddress(string s) return true; } + + /// + /// To be used to format file and directory paths for File streams.
+ /// Prepends \\?\ to path if it is longer than (MAX_PATH - 12) in Windows. This is the legacy directory length limit.

+ /// See CreateFileA and Maximum Path Length Limitation for more info. + ///
+ /// The input path + /// Whether the input path is a directory + public static string ToLongWindowsPath(string inputPath, bool isDirectory) + { + if (string.IsNullOrEmpty(inputPath) || inputPath.StartsWith(@"\\?\")) + return inputPath; + + if (isDirectory) + return inputPath.Length >= 248 ? ToLongWindowsPathUnchecked(inputPath) : inputPath; + + var dir = Path.GetDirectoryName(inputPath); + if (string.IsNullOrEmpty(dir)) + return inputPath; + + return dir.Length >= 248 || inputPath.Length >= 260 ? ToLongWindowsPathUnchecked(inputPath) : inputPath; + } + + /// + /// To be used to format file and directory paths for File streams.
+ /// Prepends \\?\ to path if it is longer than (MAX_PATH - 12) in Windows. This is the legacy directory length limit.

+ /// See CreateFileA and + /// Maximum Path Length Limitation for more info. + ///
+ /// The input path + public static string ToLongWindowsPathUnchecked(string inputPath) + { + return $@"\\?\{inputPath}"; + } } } \ No newline at end of file diff --git a/XenCenterLib/XenCenterLib.csproj b/XenCenterLib/XenCenterLib.csproj index 0cf1b59ff8..ec5ac3badc 100644 --- a/XenCenterLib/XenCenterLib.csproj +++ b/XenCenterLib/XenCenterLib.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU diff --git a/XenModel/Actions/Host/HostPowerOnAction.cs b/XenModel/Actions/Host/HostPowerOnAction.cs index c23817db64..ca6734a58a 100644 --- a/XenModel/Actions/Host/HostPowerOnAction.cs +++ b/XenModel/Actions/Host/HostPowerOnAction.cs @@ -39,9 +39,9 @@ namespace XenAdmin.Actions.HostActions { public class HostPowerOnAction : AsyncAction { - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - public HostPowerOnAction(XenAPI.Host host) + + public HostPowerOnAction(Host host) : base(host.Connection, Messages.HOST_POWER_ON) { Host = host; @@ -55,47 +55,43 @@ protected override void Run() { bool succeeded = false; string name = Helpers.GetName(Host); - XenAPI.Host coordinator = Helpers.GetCoordinator(Connection); + Host coordinator = Helpers.GetCoordinator(Connection); AppliesTo.Add(coordinator.opaque_ref); Title = string.Format(Messages.ACTION_HOST_START_TITLE, name); Description = Messages.ACTION_HOST_STARTING; + try { - XenAPI.Host.power_on(Session, Host.opaque_ref); + Host.power_on(Session, Host.opaque_ref); Description = Messages.ACTION_HOST_STARTED; succeeded = true; - - /* WLB: Below code doesn't work, becasue RelatedTask is not set. - * Need to explore other option when enabling set poweron task value for wlb reporting - if (Helpers.IsWLBEnabled(this.Connection) - && Host.other_config.ContainsKey(WlbOptimizePoolAction.OPTIMIZINGPOOL)) - { - // set host poweroff task key values for wlb reporting purpose - Task.add_to_other_config(this.Session, this.RelatedTask.opaque_ref, "wlb_advised", Host.other_config[WlbOptimizePoolAction.OPTIMIZINGPOOL]); - Task.add_to_other_config(this.Session, this.RelatedTask.opaque_ref, "wlb_action", "host_poweron"); - Task.add_to_other_config(this.Session, this.RelatedTask.opaque_ref, "wlb_action_obj_ref", Host.opaque_ref); - Task.add_to_other_config(this.Session, this.RelatedTask.opaque_ref, "wlb_action_obj_type", "host"); - } - */ } catch (Exception e) { - Failure f = e as Failure; - if (f != null) + if (e is Failure f) { - string msg = f.ErrorDescription.Count > 2 ? Messages.ResourceManager.GetString(f.ErrorDescription[2]) : null; - if (msg != null) - throw new Exception(msg); - else + if (f.ErrorDescription.Count > 2) { - throw new Exception(string.Format(Messages.POWER_ON_REQUEST_FAILED, this.Host)); + switch (f.ErrorDescription[2]) + { + case "DRAC_NO_SUPP_PACK": + throw new Exception(Messages.DRAC_NO_SUPP_PACK); + case "DRAC_POWERON_FAILED": + throw new Exception(Messages.DRAC_POWERON_FAILED); + case "ILO_CONNECTION_ERROR": + throw new Exception(Messages.ILO_CONNECTION_ERROR); + case "ILO_POWERON_FAILED": + throw new Exception(Messages.ILO_POWERON_FAILED); + } } + + throw new Exception(string.Format(Messages.POWER_ON_REQUEST_FAILED, Host)); } throw; } finally { - if (Helpers.WlbConfigured(this.Connection) && Helpers.WlbEnabledAndConfigured(this.Connection)) + if (Helpers.WlbConfigured(Connection) && Helpers.WlbEnabledAndConfigured(Connection)) { UpdateHostLastPowerOnSucceeded(succeeded, Host); } @@ -105,18 +101,18 @@ protected override void Run() /// /// Attempts to set the LastPowerOnSucceeded flag in the WLB Host configuration /// - private void UpdateHostLastPowerOnSucceeded(bool succeeded, XenAPI.Host host) + private void UpdateHostLastPowerOnSucceeded(bool succeeded, Host host) { try { - //Helpers.SetOtherConfig(this.Host.Connection.Session, this.Host, "LastPowerOnsucceeded", successful.ToString()); WlbHostConfiguration hostConfig = new WlbHostConfiguration(host.uuid); hostConfig.LastPowerOnSucceeded = succeeded; if (!succeeded) { hostConfig.ParticipatesInPowerManagement = false; } - XenAPI.Pool pool = Helpers.GetPoolOfOne(host.Connection); + + Pool pool = Helpers.GetPoolOfOne(host.Connection); if (null != pool) { SendWlbConfigurationAction action = new SendWlbConfigurationAction(pool, hostConfig.ToDictionary(), SendWlbConfigurationKind.SetHostConfiguration); diff --git a/XenModel/Actions/StatusReport/ClientSideStatusReportAction.cs b/XenModel/Actions/StatusReport/ClientSideStatusReportAction.cs index 9db566bede..cd1ba8379b 100644 --- a/XenModel/Actions/StatusReport/ClientSideStatusReportAction.cs +++ b/XenModel/Actions/StatusReport/ClientSideStatusReportAction.cs @@ -82,7 +82,7 @@ protected override void Run() private void CopyClientLogs() { - string logDestination = string.Format("{0}\\{1}-{2}.log", filePath, timeString, BrandManager.BrandConsoleNoSpace); + string logDestination = string.Format("{0}\\{1}-{2}.log", filePath, timeString, BrandManager.BrandConsole); if (includeClientLogs) { string logPath = XenAdminConfigManager.Provider.GetLogFile(); diff --git a/XenModel/Actions/StatusReport/ZipStatusReportAction.cs b/XenModel/Actions/StatusReport/ZipStatusReportAction.cs index 2ac7370b30..9e23ee9666 100644 --- a/XenModel/Actions/StatusReport/ZipStatusReportAction.cs +++ b/XenModel/Actions/StatusReport/ZipStatusReportAction.cs @@ -30,6 +30,7 @@ using System; using System.IO; +using XenCenterLib; using XenCenterLib.Archive; @@ -65,7 +66,7 @@ public class ZipStatusReportAction : StatusReportAction public ZipStatusReportAction(string tempFolder, string destFile, string timeString = null, bool suppressHistory = true) : base(null, Messages.BUGTOOL_SAVING, destFile, timeString, suppressHistory) { - _inputTempFolder = tempFolder; + _inputTempFolder = StringUtility.ToLongWindowsPathUnchecked(tempFolder); _destFile = destFile; } @@ -74,7 +75,7 @@ protected override void Run() Status = ReportStatus.inProgress; do { - _extractTempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + _extractTempDir = StringUtility.ToLongWindowsPathUnchecked(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); } while (Directory.Exists(_extractTempDir)); Directory.CreateDirectory(_extractTempDir); diff --git a/XenModel/Actions/Updates/ApplyUpdatesFromCdnAction.cs b/XenModel/Actions/Updates/ApplyUpdatesFromCdnAction.cs index b3cac208a7..0c0d2d6c63 100644 --- a/XenModel/Actions/Updates/ApplyUpdatesFromCdnAction.cs +++ b/XenModel/Actions/Updates/ApplyUpdatesFromCdnAction.cs @@ -49,6 +49,9 @@ public ApplyUpdatesFromCdnAction(Host host, CdnPoolUpdateInfo updateInfo) protected override void Run() { + //this waits for 1 minute + Connection.WaitFor(() => Host.allowed_operations.Contains(host_allowed_operations.apply_updates), null); + try { RelatedTask = Host.async_apply_updates(Session, Host.opaque_ref, _updateInfo.Checksum); diff --git a/XenModel/Actions/Updates/CheckForCdnUpdatesAction.cs b/XenModel/Actions/Updates/CheckForCdnUpdatesAction.cs index f42e64a93f..b2e869eb70 100644 --- a/XenModel/Actions/Updates/CheckForCdnUpdatesAction.cs +++ b/XenModel/Actions/Updates/CheckForCdnUpdatesAction.cs @@ -40,6 +40,8 @@ namespace XenAdmin.Actions { public class CheckForCdnUpdatesAction : AsyncAction { + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + public CheckForCdnUpdatesAction(IXenConnection connection) : base(connection, string.Empty) { @@ -51,7 +53,16 @@ public CheckForCdnUpdatesAction(IXenConnection connection) protected override void Run() { - var coordinator = Connection.Resolve(Helpers.GetPoolOfOne(Connection)?.master); + var pool = Helpers.GetPoolOfOne(Connection); + if (pool == null) + return; + + //this waits for 1 minute + Connection.WaitFor(() => pool.allowed_operations.Contains(pool_allowed_operations.get_updates), null); + if (!pool.allowed_operations.Contains(pool_allowed_operations.get_updates)) + return; + + var coordinator = Connection.Resolve(pool.master); if (coordinator == null) return; @@ -67,15 +78,29 @@ protected override void Run() Query = $"session_id={Uri.EscapeDataString(Session.opaque_ref)}" }; - string json; + try + { + string json; + + using (Stream httpStream = HTTPHelper.GET(builder.Uri, Connection, true)) + { + using (var streamReader = new StreamReader(httpStream)) + json = streamReader.ReadToEnd(); + } - using (Stream httpStream = HTTPHelper.GET(builder.Uri, Connection, true)) + Updates = JsonConvert.DeserializeObject(json); + } + catch (HTTP.BadServerResponseException ex) { - using (var streamReader = new StreamReader(httpStream)) - json = streamReader.ReadToEnd(); + if (ex.Message.Contains("404 Not Found") || ex.Message.Contains("500 Internal Server Error") || + ex.Message.Contains("500 Internal Error")) //seems xapi shows this too + { + log.Warn(ex.Message); + log.Warn("Failed to retrieve available updates. See the server side logs for details."); + } + else + throw; } - - Updates = JsonConvert.DeserializeObject(json); } } } diff --git a/XenModel/Actions/Updates/DownloadUpdatesXmlAction.cs b/XenModel/Actions/Updates/DownloadUpdatesXmlAction.cs index 86a6884382..39c4fd3cca 100644 --- a/XenModel/Actions/Updates/DownloadUpdatesXmlAction.cs +++ b/XenModel/Actions/Updates/DownloadUpdatesXmlAction.cs @@ -393,7 +393,7 @@ protected DownloadUpdatesXmlAction(string userAgent, string xmlLocationUrl, bool _checkForUpdatesUrl = xmlLocationUrl; } - protected virtual XmlDocument FetchCheckForUpdatesXml() + protected XmlDocument FetchCheckForUpdatesXml() { var checkForUpdatesXml = new XmlDocument(); var uriBuilder = new UriBuilder(_checkForUpdatesUrl); diff --git a/XenModel/Actions/WLB/InitializeWLBAction.cs b/XenModel/Actions/WLB/InitializeWLBAction.cs index 6aa2774afa..d444dcffc5 100644 --- a/XenModel/Actions/WLB/InitializeWLBAction.cs +++ b/XenModel/Actions/WLB/InitializeWLBAction.cs @@ -29,6 +29,7 @@ */ using XenAdmin.Core; +using XenAdmin.Wlb; using XenAPI; @@ -42,12 +43,12 @@ public class InitializeWLBAction : AsyncAction private readonly string _wlbPassword; private readonly string _xenServerUserName; private readonly string _xenServerPassword; - private static string OPTIMIZINGPOOL = "wlb_optimizing_pool"; + private const string OPTIMIZING_POOL = "wlb_optimizing_pool"; public InitializeWLBAction(Pool pool, string wlbUrl, string wlbUserName, string wlbPassword, string xenServerUserName, string xenServerPassword) : base(pool.Connection, string.Format(Messages.INITIALIZING_WLB_ON, Helpers.GetName(pool).Ellipsise(50)), Messages.INITIALIZING_WLB, false) { - this.Pool = pool; + Pool = pool; _wlbUrl = wlbUrl; _wlbUserName = wlbUserName; _wlbPassword = wlbPassword; @@ -55,8 +56,8 @@ public InitializeWLBAction(Pool pool, string wlbUrl, string wlbUserName, string _xenServerPassword = xenServerPassword; #region RBAC Dependencies - ApiMethodsToRoleCheck.Add("vm.assert_agile"); - ApiMethodsToRoleCheck.Add("pool.initialize_wlb"); + + ApiMethodsToRoleCheck.AddRange("vm.assert_agile", "pool.initialize_wlb"); ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList); ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList); #endregion @@ -68,29 +69,29 @@ protected override void Run() try { log.Debug("Initializing Workload Balancing for pool " + Pool.Name()); - RelatedTask = XenAPI.Pool.async_initialize_wlb(this.Session, _wlbUrl, _wlbUserName, _wlbPassword, _xenServerUserName, _xenServerPassword); + RelatedTask = Pool.async_initialize_wlb(Session, _wlbUrl, _wlbUserName, _wlbPassword, _xenServerUserName, _xenServerPassword); PollToCompletion(); log.Debug("Success initializing WLB on pool " + Pool.Name()); - this.Description = Messages.COMPLETED; + Description = Messages.COMPLETED; //Clear the Optimizing Pool flag in case it was left behind - Helpers.SetOtherConfig(this.Session, this.Pool, OPTIMIZINGPOOL, string.Empty); + Helpers.SetOtherConfig(Session, Pool, OPTIMIZING_POOL, string.Empty); } catch (Failure e) { if (e.Message == FriendlyErrorNames.WLB_INTERNAL_ERROR) { - Failure f = new Failure(new string[] { Messages.ResourceManager.GetString("WLB_ERROR_" + e.ErrorDescription[1]) }); - throw (f); + var wlbError = WlbServerState.ConvertWlbError(e.ErrorDescription[1]); + + if (wlbError != null) + throw new Failure(wlbError); } else if (e.ErrorDescription[0] == FriendlyErrorNames.INTERNAL_ERROR) { - Failure f = new Failure(new string[] { Messages.ResourceManager.GetString("WLB_ERROR_SERVER_NOT_FOUND") }); - } - else - { - throw (e); + throw new Failure(Messages.WLB_ERROR_SERVER_NOT_FOUND); } + + throw; } } diff --git a/XenModel/WLB/RetrieveWlbConfigurationAction.cs b/XenModel/Actions/WLB/RetrieveWlbConfigurationAction.cs similarity index 92% rename from XenModel/WLB/RetrieveWlbConfigurationAction.cs rename to XenModel/Actions/WLB/RetrieveWlbConfigurationAction.cs index f619c3a426..9887dba457 100644 --- a/XenModel/WLB/RetrieveWlbConfigurationAction.cs +++ b/XenModel/Actions/WLB/RetrieveWlbConfigurationAction.cs @@ -78,8 +78,13 @@ protected override void Run() WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, ex); if (ex.Message == FriendlyErrorNames.WLB_INTERNAL_ERROR) - throw new Failure(Messages.ResourceManager.GetString("WLB_ERROR_" + ex.ErrorDescription[1])); - + { + var wlbError = WlbServerState.ConvertWlbError(ex.ErrorDescription[1]); + + if (wlbError != null) + throw new Failure(wlbError); + } + throw; } } diff --git a/XenModel/Actions/WLB/SendWlbConfigurationAction.cs b/XenModel/Actions/WLB/SendWlbConfigurationAction.cs index 97912a327d..3c3b310933 100644 --- a/XenModel/Actions/WLB/SendWlbConfigurationAction.cs +++ b/XenModel/Actions/WLB/SendWlbConfigurationAction.cs @@ -38,7 +38,7 @@ namespace XenAdmin.Actions.Wlb { [Flags] - public enum SendWlbConfigurationKind : int + public enum SendWlbConfigurationKind { None = 0, SetPoolConfiguration = 1, @@ -47,26 +47,26 @@ public enum SendWlbConfigurationKind : int SetReportSubscription = 8, DeleteReportSubscription = 16, SetHostConfiguration = 32 - }; + } public class SendWlbConfigurationAction : AsyncAction { - private static string SET_HOST_CONFIGURATION = "set_host_configuration"; - private static string SET_SCHEDULED_TASK = "set_scheduled_task"; - private static string DELETE_SCHEDULED_TASK = "delete_scheduled_task"; - private static string SET_REPORT_SUBSCRIPTIONS = "set_report_subscription"; - private static string DELETE_REPORT_SUBSCRIPTIONS = "delete_report_subscription"; + private const string SET_HOST_CONFIGURATION = "set_host_configuration"; + private const string SET_SCHEDULED_TASK = "set_scheduled_task"; + private const string DELETE_SCHEDULED_TASK = "delete_scheduled_task"; + private const string SET_REPORT_SUBSCRIPTIONS = "set_report_subscription"; + private const string DELETE_REPORT_SUBSCRIPTIONS = "delete_report_subscription"; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly SendWlbConfigurationKind _kind; - private Dictionary WlbConfiguration = new Dictionary(); + private readonly Dictionary _wlbConfiguration; public SendWlbConfigurationAction(Pool pool, Dictionary configuration, SendWlbConfigurationKind kind) : base(pool.Connection, string.Format(Messages.SAVING_WLB_CONFIGURATION_FOR, Helpers.GetName(pool).Ellipsise(50)), Messages.SAVING_WLB_CONFIGURATION, false) { - this.Pool = pool; - this.WlbConfiguration = configuration; - this._kind = kind; + Pool = pool; + _wlbConfiguration = configuration; + _kind = kind; #region RBAC Dependencies ApiMethodsToRoleCheck.Add("pool.send_wlb_configuration"); @@ -81,59 +81,59 @@ protected override void Run() ClearKeys(); - if ((_kind & SendWlbConfigurationKind.SetHostConfiguration) == SendWlbConfigurationKind.SetHostConfiguration) + if (_kind.HasFlag(SendWlbConfigurationKind.SetHostConfiguration)) { - this.WlbConfiguration.Add(SET_HOST_CONFIGURATION, "true"); + _wlbConfiguration.Add(SET_HOST_CONFIGURATION, "true"); } - if ((_kind & SendWlbConfigurationKind.SetScheduledTask) == SendWlbConfigurationKind.SetScheduledTask) + if (_kind.HasFlag(SendWlbConfigurationKind.SetScheduledTask)) { - this.WlbConfiguration.Add(SET_SCHEDULED_TASK, "true"); + _wlbConfiguration.Add(SET_SCHEDULED_TASK, "true"); } - if ((_kind & SendWlbConfigurationKind.DeleteScheduledTask) == SendWlbConfigurationKind.DeleteScheduledTask) + if (_kind.HasFlag(SendWlbConfigurationKind.DeleteScheduledTask)) { - this.WlbConfiguration.Add(DELETE_SCHEDULED_TASK, "true"); + _wlbConfiguration.Add(DELETE_SCHEDULED_TASK, "true"); } - if ((_kind & SendWlbConfigurationKind.SetReportSubscription) == SendWlbConfigurationKind.SetReportSubscription) + if (_kind.HasFlag(SendWlbConfigurationKind.SetReportSubscription)) { - this.WlbConfiguration.Add(SET_REPORT_SUBSCRIPTIONS, "true"); + _wlbConfiguration.Add(SET_REPORT_SUBSCRIPTIONS, "true"); } - if ((_kind & SendWlbConfigurationKind.DeleteReportSubscription) == SendWlbConfigurationKind.DeleteReportSubscription) + if (_kind.HasFlag(SendWlbConfigurationKind.DeleteReportSubscription)) { - this.WlbConfiguration.Add(DELETE_REPORT_SUBSCRIPTIONS, "true"); + _wlbConfiguration.Add(DELETE_REPORT_SUBSCRIPTIONS, "true"); } try { - XenAPI.Pool.send_wlb_configuration(this.Session, this.WlbConfiguration); + Pool.send_wlb_configuration(Session, _wlbConfiguration); log.Debug("Successfully sent Workload Balancing configuration on pool " + Pool.Name()); - this.Description = Messages.COMPLETED; + Description = Messages.COMPLETED; } catch (Exception ex) { - if (ex is Failure) + if (ex is Failure f) { - WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, (Failure)ex); + WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, f); - if (((Failure)ex).Message == FriendlyErrorNames.WLB_INTERNAL_ERROR) - { - Failure f = new Failure(new string[] { Messages.ResourceManager.GetString("WLB_ERROR_" + ((Failure)ex).ErrorDescription[1]) }); - throw (f); - } - else + if (f.Message == FriendlyErrorNames.WLB_INTERNAL_ERROR) { - throw (ex); + var wlbError = WlbServerState.ConvertWlbError(f.ErrorDescription[1]); + + if (wlbError != null) + throw new Failure(wlbError); } } + + throw; } } private void ClearKeys() { - this.WlbConfiguration.Remove(SET_HOST_CONFIGURATION); - this.WlbConfiguration.Remove(SET_SCHEDULED_TASK); - this.WlbConfiguration.Remove(DELETE_SCHEDULED_TASK); - this.WlbConfiguration.Remove(SET_REPORT_SUBSCRIPTIONS); - this.WlbConfiguration.Remove(DELETE_REPORT_SUBSCRIPTIONS); + _wlbConfiguration.Remove(SET_HOST_CONFIGURATION); + _wlbConfiguration.Remove(SET_SCHEDULED_TASK); + _wlbConfiguration.Remove(DELETE_SCHEDULED_TASK); + _wlbConfiguration.Remove(SET_REPORT_SUBSCRIPTIONS); + _wlbConfiguration.Remove(DELETE_REPORT_SUBSCRIPTIONS); } } } diff --git a/XenModel/WLB/WlbReportAction.cs b/XenModel/Actions/WLB/WlbReportAction.cs similarity index 100% rename from XenModel/WLB/WlbReportAction.cs rename to XenModel/Actions/WLB/WlbReportAction.cs diff --git a/XenModel/BrandManager.cs b/XenModel/BrandManager.cs index 4eb0245004..e22b52b86d 100644 --- a/XenModel/BrandManager.cs +++ b/XenModel/BrandManager.cs @@ -47,7 +47,6 @@ static BrandManager() var customBranding = (CustomBrandingAttribute)assembly.GetCustomAttribute(typeof(CustomBrandingAttribute)); BrandConsole = customBranding.BrandConsole; - BrandConsoleNoSpace = customBranding.BrandConsoleNoSpace; CompanyNameShort = customBranding.CompanyNameShort; ProductBrand = customBranding.ProductBrand; ProductVersionPost82 = customBranding.ProductVersionText; @@ -66,8 +65,6 @@ static BrandManager() public static readonly string BrandConsole; - public static readonly string BrandConsoleNoSpace; - public static readonly string Cis = Get("CIS"); public static readonly string CompanyNameLegacy = Get("COMPANY_NAME_LEGACY"); diff --git a/XenModel/InvisibleMessages.Designer.cs b/XenModel/InvisibleMessages.Designer.cs index de5a02ed96..56caace06a 100644 --- a/XenModel/InvisibleMessages.Designer.cs +++ b/XenModel/InvisibleMessages.Designer.cs @@ -97,7 +97,7 @@ public static string DEPRECATION_URL { } /// - /// Looks up a localized string similar to https://docs.xenserver.com/. + /// Looks up a localized string similar to https://docs.xenserver.com/en-us/. /// public static string DOCS_URL { get { @@ -168,15 +168,6 @@ public static string PLUGINS_URL { } } - /// - /// Looks up a localized string similar to http://citrix.com/English/aboutCitrix/legal/privacyStatement.asp?ntref=hp_nav_US. - /// - public static string PRIVACY { - get { - return ResourceManager.GetString("PRIVACY", resourceCulture); - } - } - /// /// Looks up a localized string similar to https://docs.xenserver.com/en-us/xenserver/8/system-requirements/guest-os-support.html. /// diff --git a/XenModel/InvisibleMessages.resx b/XenModel/InvisibleMessages.resx index 7f217ef03e..3ff214dac4 100644 --- a/XenModel/InvisibleMessages.resx +++ b/XenModel/InvisibleMessages.resx @@ -130,7 +130,7 @@ https://docs.xenserver.com/en-us/xenserver/8/whats-new/removed-features.html - https://docs.xenserver.com/ + https://docs.xenserver.com/en-us/ ?utm_campaign={0}&utm_medium=ui_link&utm_source={1} @@ -153,9 +153,6 @@ https://github.com/xenserver/xencenter-samples - - http://citrix.com/English/aboutCitrix/legal/privacyStatement.asp?ntref=hp_nav_US - https://docs.xenserver.com/en-us/xenserver/8/system-requirements/guest-os-support.html diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index e30d7bed52..2d47ae38ce 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -4993,6 +4993,15 @@ public static string ALERT_CAP_LABEL { } } + /// + /// Looks up a localized string similar to You have never synchronized with the update channel.. + /// + public static string ALERT_CDN_NEVER_SYNC_TITLE { + get { + return ResourceManager.GetString("ALERT_CDN_NEVER_SYNC_TITLE", resourceCulture); + } + } + /// /// Looks up a localized string similar to The last synchronization with the update channel took place on {0}.. /// @@ -11880,60 +11889,6 @@ public static string CREDENTIALS_CHECKING { } } - /// - /// Looks up a localized string similar to Dell EqualLogic. - /// - public static string CSLG_DELL_DIRECT { - get { - return ResourceManager.GetString("CSLG_DELL_DIRECT", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Direct Connection. - /// - public static string CSLG_DIRECT_CONNECTION { - get { - return ResourceManager.GetString("CSLG_DIRECT_CONNECTION", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to NetApp. - /// - public static string CSLG_NETAPP_DIRECT { - get { - return ResourceManager.GetString("CSLG_NETAPP_DIRECT", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to &Storage adapter:. - /// - public static string CSLG_STORAGEADAPTER { - get { - return ResourceManager.GetString("CSLG_STORAGEADAPTER", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to StorageLink adapters. - /// - public static string CSLG_STORAGELINK_ADAPTERS { - get { - return ResourceManager.GetString("CSLG_STORAGELINK_ADAPTERS", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to StorageLink Server ({0}). - /// - public static string CSLG_STORAGELINK_SERVER { - get { - return ResourceManager.GetString("CSLG_STORAGELINK_SERVER", resourceCulture); - } - } - /// /// Looks up a localized string similar to Comma Separated Value. /// @@ -18508,15 +18463,6 @@ public static string GPU_GROUP_NAME_AND_NO_OF_GPUS_ONE { } } - /// - /// Looks up a localized string similar to None. - /// - public static string GPU_NONE { - get { - return ResourceManager.GetString("GPU_NONE", resourceCulture); - } - } - /// /// Looks up a localized string similar to On {0}:. /// @@ -18889,15 +18835,6 @@ public static string HA_CANNOT_EVACUATE_COORDINATOR { } } - /// - /// Looks up a localized string similar to HA and WLB check. - /// - public static string HA_CHECK_DESCRIPTION { - get { - return ResourceManager.GetString("HA_CHECK_DESCRIPTION", resourceCulture); - } - } - /// /// Looks up a localized string similar to Choose a heartbeat SR. /// @@ -19420,6 +19357,17 @@ public static string HA_PAGE_ENABLING { } } + /// + /// Looks up a localized string similar to HA is not currently enabled for pool '{0}'. + /// + ///Click Configure HA to enable HA for this pool and allow your virtual machines to be automatically restarted in the event of unexpected server failure.. + /// + public static string HA_PANEL_BLURB { + get { + return ResourceManager.GetString("HA_PANEL_BLURB", resourceCulture); + } + } + /// /// Looks up a localized string similar to HA restart priority. /// @@ -19551,13 +19499,11 @@ public static string HA_WIZARD_FINISH_PAGE_TITLE { } /// - /// Looks up a localized string similar to HA is not currently enabled for pool '{0}'. - /// - ///Click Configure HA to enable HA for this pool and allow your virtual machines to be automatically restarted in the event of unexpected server failure.. + /// Looks up a localized string similar to HA and WLB check. /// - public static string HAPANEL_BLURB { + public static string HA_WLB_CHECK_DESCRIPTION { get { - return ResourceManager.GetString("HAPANEL_BLURB", resourceCulture); + return ResourceManager.GetString("HA_WLB_CHECK_DESCRIPTION", resourceCulture); } } @@ -20531,6 +20477,15 @@ public static string HOTFIX_POST_UPDATE_LIVEPATCH_ACTIONS { } } + /// + /// Looks up a localized string similar to This server will be evacuated prior to installing updates. + /// + public static string HOTFIX_PRE_UPDATE_ACTIONS { + get { + return ResourceManager.GetString("HOTFIX_PRE_UPDATE_ACTIONS", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} packages will be updated. /// @@ -20613,7 +20568,7 @@ public static string HOTFIX_TYPE_NEW_FEATURE_ONE { } /// - /// Looks up a localized string similar to {0} feature previews. + /// Looks up a localized string similar to {0} preview features. /// public static string HOTFIX_TYPE_PREVIEW_FEATURE_MANY { get { @@ -20622,7 +20577,7 @@ public static string HOTFIX_TYPE_PREVIEW_FEATURE_MANY { } /// - /// Looks up a localized string similar to 1 new feature preview. + /// Looks up a localized string similar to 1 preview feature. /// public static string HOTFIX_TYPE_PREVIEW_FEATURE_ONE { get { @@ -28619,6 +28574,15 @@ public static string NONE_PARENS { } } + /// + /// Looks up a localized string similar to None. + /// + public static string NONE_UPPER { + get { + return ResourceManager.GetString("NONE_UPPER", resourceCulture); + } + } + /// /// Looks up a localized string similar to The VM is not using a shared network. Restart cannot be guaranteed.. /// @@ -30247,6 +30211,33 @@ public static string PATCHINGWIZARD_SELECTSERVERPAGE_CANNOT_INSTALL_UPDATE_COORD } } + /// + /// Looks up a localized string similar to You have never synchronized with the update channel.. + /// + public static string PATCHINGWIZARD_SELECTSERVERPAGE_CDN_NOT_SYNCHRONIZED { + get { + return ResourceManager.GetString("PATCHINGWIZARD_SELECTSERVERPAGE_CDN_NOT_SYNCHRONIZED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You have not configured an update channel.. + /// + public static string PATCHINGWIZARD_SELECTSERVERPAGE_CDN_REPOS_NOT_CONFIGURED { + get { + return ResourceManager.GetString("PATCHINGWIZARD_SELECTSERVERPAGE_CDN_REPOS_NOT_CONFIGURED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to All updates available at the last synchronization have been applied.. + /// + public static string PATCHINGWIZARD_SELECTSERVERPAGE_CDN_UPDATES_APPLIED { + get { + return ResourceManager.GetString("PATCHINGWIZARD_SELECTSERVERPAGE_CDN_UPDATES_APPLIED", resourceCulture); + } + } + /// /// Looks up a localized string similar to Subscription Advantage required. /// @@ -30739,15 +30730,6 @@ public static string PIF_NIC { } } - /// - /// Looks up a localized string similar to None. - /// - public static string PIF_NONE { - get { - return ResourceManager.GetString("PIF_NONE", resourceCulture); - } - } - /// /// Looks up a localized string similar to Static. /// @@ -31468,7 +31450,7 @@ public static string POOL_UPDATE_GONE { } /// - /// Looks up a localized string similar to Pool partially upgraded to {0} {1}. + /// Looks up a localized string similar to Pool partially upgraded to {0}. /// public static string POOL_VERSIONS_LINK_TEXT { get { @@ -41734,6 +41716,15 @@ public static string WLB_ERROR_4005 { } } + /// + /// Looks up a localized string similar to WLB received an argument from the server that is not implemented.. + /// + public static string WLB_ERROR_4006 { + get { + return ResourceManager.GetString("WLB_ERROR_4006", resourceCulture); + } + } + /// /// Looks up a localized string similar to WLB received an invalid argument from the server.. /// @@ -42287,15 +42278,6 @@ public static string WLB_OPT_REASON_NETWORKWRITE { } } - /// - /// Looks up a localized string similar to None. - /// - public static string WLB_OPT_REASON_NONE { - get { - return ResourceManager.GetString("WLB_OPT_REASON_NONE", resourceCulture); - } - } - /// /// Looks up a localized string similar to Release Resource. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 1a9ed17fdd..2e4f0691d1 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -1834,6 +1834,9 @@ This alarm is set to be triggered when the total throughput exceeds {4}. (Showing first {0} entries) + + You have never synchronized with the update channel. + The last synchronization with the update channel took place on {0}. @@ -4233,24 +4236,6 @@ For optimal performance and reliability during VM migration, ensure that the net Checking user name and password... - - Dell EqualLogic - - - Direct Connection - - - NetApp - - - &Storage adapter: - - - StorageLink adapters - - - StorageLink Server ({0}) - Comma Separated Value @@ -6463,9 +6448,6 @@ Would you like to eject these ISOs before continuing? {0} (1 GPU) - - None - On {0}: @@ -6598,9 +6580,6 @@ not currently live: Server '{0}' cannot be placed in Maintenance Mode because it is the coordinator of an HA-enabled pool. - - HA and WLB check - Choose a heartbeat SR @@ -6787,6 +6766,11 @@ Reduce protection levels, or bring more servers online to increase the maximum s HA is currently being enabled for '{0}'. + + HA is not currently enabled for pool '{0}'. + +Click Configure HA to enable HA for this pool and allow your virtual machines to be automatically restarted in the event of unexpected server failure. + HA restart priority @@ -6833,10 +6817,8 @@ Click Configure HA to alter the settings displayed below. Review configuration and activate HA - - HA is not currently enabled for pool '{0}'. - -Click Configure HA to enable HA for this pool and allow your virtual machines to be automatically restarted in the event of unexpected server failure. + + HA and WLB check Has any custom field @@ -7167,6 +7149,9 @@ This might result in failure to migrate VMs to this server during the RPU or to This server will be live patched. If live patch fails, a server reboot will be required. + + This server will be evacuated prior to installing updates + {0} packages will be updated @@ -7195,10 +7180,10 @@ This might result in failure to migrate VMs to this server during the RPU or to 1 new feature - {0} feature previews + {0} preview features - 1 new feature preview + 1 preview feature {0} security fixes @@ -9939,6 +9924,9 @@ When you configure an NFS storage repository, you simply provide the host name o (None) + + None + The VM is not using a shared network. Restart cannot be guaranteed. @@ -10486,6 +10474,15 @@ This will cancel the update process and may leave your system in an unstable sta Cannot install updates on this host because the coordinator is running a version higher than {0} + + You have never synchronized with the update channel. + + + You have not configured an update channel. + + + All updates available at the last synchronization have been applied. + Subscription Advantage required @@ -10654,9 +10651,6 @@ This will cancel the upload process. NIC {0} - - None - Static @@ -10903,7 +10897,7 @@ If this value does not correspond to a server within the selected resource pool Could not find the pool update in {0}'s cache. - Pool partially upgraded to {0} {1} + Pool partially upgraded to {0} Partially upgraded @@ -14386,6 +14380,9 @@ A {1} user cannot alter the Workload Balancing settings. WLB registry key is missing. + + WLB received an argument from the server that is not implemented. + WLB received an invalid argument from the server. @@ -14573,9 +14570,6 @@ A {1} user cannot alter the Workload Balancing settings. Network Writes - - None - Release Resource diff --git a/XenModel/Properties/AssemblyInfo.cs b/XenModel/Properties/AssemblyInfo.cs index 9042d02054..7d94ae0e47 100644 --- a/XenModel/Properties/AssemblyInfo.cs +++ b/XenModel/Properties/AssemblyInfo.cs @@ -34,7 +34,7 @@ using System.Runtime.InteropServices; using XenAdmin.Properties; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. @@ -43,8 +43,8 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("[XenCenter]")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] @@ -55,7 +55,6 @@ [assembly: CustomBranding( "[XenCenter]", - "[XenCenter_No_Space]", "[Vendor]", "[XenServerProduct]", "[XenServer version]", @@ -77,7 +76,6 @@ public class CustomBrandingAttribute : Attribute { public CustomBrandingAttribute( string brandConsole, - string brandConsoleNoSpace, string companyNameShort, string productBrand, string productVersionText, @@ -94,7 +92,6 @@ string yumRepoNormalSource ) { BrandConsole = brandConsole; - BrandConsoleNoSpace = brandConsoleNoSpace; CompanyNameShort = companyNameShort; ProductBrand = productBrand; ProductVersionText = productVersionText; @@ -111,7 +108,6 @@ string yumRepoNormalSource } public string BrandConsole { get; } - public string BrandConsoleNoSpace { get; } public string CompanyNameShort { get; } public string ProductBrand { get; } public string ProductVersionText { get; } diff --git a/XenModel/WLB/WlbOptimizationRecommendation.cs b/XenModel/WLB/WlbOptimizationRecommendation.cs index 3021a7a132..41713a568e 100644 --- a/XenModel/WLB/WlbOptimizationRecommendation.cs +++ b/XenModel/WLB/WlbOptimizationRecommendation.cs @@ -99,7 +99,6 @@ internal WlbOptimizationRecommendation(VM vm, Host fromHost, Host toHost, string this.optId = optId; this.powerOperation = powerOperation; } - } @@ -110,7 +109,6 @@ public WlbOptimizationRecommendationCollection(Pool pool, Dictionary, LoadSortedRecommendationList(pool, recommendations); } - private void LoadSortedRecommendationList(Pool pool, Dictionary, string[]> recommendations) { // When there are host powerOn recommendations, the toHost of the recommended move vms are disabled, @@ -122,30 +120,15 @@ private void LoadSortedRecommendationList(Pool pool, Dictionary, stri { if (rec.Value[0].Trim().ToLower() == "wlb") { - int recId = 0; - int optId = 0; - int.TryParse(rec.Value[(int)RecProperties.RecId], out recId); - int.TryParse(rec.Value[(int)RecProperties.OptId], out optId); + int.TryParse(rec.Value[(int)RecProperties.RecId], out var recId); + int.TryParse(rec.Value[(int)RecProperties.OptId], out var optId); - //XenObject toHost = (!vm.Server.is_control_domain || (vm.Server.is_control_domain && (String.Compare(rec.Value[(int)WlbOptimizePool.RecProperties.Reason].ToString(), "PowerOn", true) == 0))) ? pool.Connection.Cache.Find_by_Uuid(rec.Value[(int)WlbOptimizePool.RecProperties.ToHost]) : null; - //XenObject fromHost = (!vm.Server.is_control_domain || (vm.Server.is_control_domain && (String.Compare(rec.Value[(int)WlbOptimizePool.RecProperties.Reason].ToString(), "PowerOff", true) == 0))) ? pool.Connection.Resolve(vm.Server.resident_on) : null; VM vm = pool.Connection.Resolve(rec.Key); - Host toHost = (!vm.is_control_domain) ? pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]) : null; - Host fromHost = (!vm.is_control_domain) ? pool.Connection.Resolve(vm.resident_on) : pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]); - - string powerOperation = Messages.ResourceManager.GetString(String.Format("WLB_OPT_OPERATION_HOST_{0}", rec.Value[(int)RecProperties.Reason].ToString().ToUpper())); - - string resourcedReasonOutput = Messages.ResourceManager.GetString(String.Format("WLB_OPT_REASON_{0}", rec.Value[(int)RecProperties.Reason].ToString().ToUpper())); - if (resourcedReasonOutput == null) - { - resourcedReasonOutput = Messages.UNKNOWN; - } + Host toHost = !vm.is_control_domain ? pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]) : null; + Host fromHost = !vm.is_control_domain ? pool.Connection.Resolve(vm.resident_on) : pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]); + + ParseRecommendationReason(rec.Value[(int)RecProperties.Reason], out var powerOperation, out var resourcedReasonOutput); - /* Only vms or host have below criteria can be potentially added into recommendation collection - * - if it is a control_domain (powerOn/powerOff host) - * Or - * - if the moving vm is running, toHost not equal to fromHost, and toHost is disable but it's a powerOnHost or toHost is enabled - */ if ((vm.is_control_domain && fromHost != null) || (vm.power_state == vm_power_state.Running && toHost != fromHost @@ -153,19 +136,11 @@ private void LoadSortedRecommendationList(Pool pool, Dictionary, stri || (toHost != null && toHost.enabled)))) { - // If it's a powerOn host, add it to the powerOnHosts list - //if (vm.Server.is_control_domain && (powerOperation == Messages.WLB_OPT_OPERATION_HOST_POWERON)&& !fromHost.Server.IsLive) - /*if(IsHostPowerOn(vm, powerOperation, fromHost)) - { - powerOnHosts.Add(fromHost); - } - */ - WlbOptimizationRecommendation optVmSetting = new WlbOptimizationRecommendation(vm, fromHost, toHost, resourcedReasonOutput, recId, optId, powerOperation); - /* Clear the recommendation collection if the number of vms on a power off host - * doesn't match the vms in the recommendations - */ + // Clear the recommendation collection if the number of vms on a power off host + // doesn't match the vms in the recommendations + if (IsHostPowerOff(vm, powerOperation, fromHost) && !VmsOnPowerOffHostAreInRecommendations(fromHost, recommendations)) { @@ -173,15 +148,9 @@ private void LoadSortedRecommendationList(Pool pool, Dictionary, stri break; } - /* Add to the recommendation collection if: - * - it's a vm (not power on/off host) - * Or - * - it's a power on/off host - */ - //if (!vm.Server.is_control_domain || (vm.Server.is_control_domain && (((powerOperation == Messages.WLB_OPT_OPERATION_HOST_POWERON) && !fromHost.Server.IsLive) || ((powerOperation == Messages.WLB_OPT_OPERATION_HOST_POWEROFF) && fromHost.Server.IsLive)))) if (!vm.is_control_domain || IsHostPowerOnOff(vm, fromHost, powerOperation, recommendations)) { - this.Add(optVmSetting); + Add(optVmSetting); } } } @@ -189,15 +158,14 @@ private void LoadSortedRecommendationList(Pool pool, Dictionary, stri if (clearList) { - this.Clear(); + Clear(); } else { - this.Sort(SortByRecommendationId); + Sort(SortByRecommendationId); } } - private List GetAllPowerOnHosts(Pool pool, Dictionary, string[]> recommendations) { List powerOnHosts = new List(); @@ -207,11 +175,11 @@ private List GetAllPowerOnHosts(Pool pool, Dictionary, string[] if (rec.Value[0].Trim().ToLower() == "wlb") { VM vm = pool.Connection.Resolve(rec.Key); - Host fromHost = (!vm.is_control_domain) ? pool.Connection.Resolve(vm.resident_on) : pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]); + Host fromHost = !vm.is_control_domain ? pool.Connection.Resolve(vm.resident_on) : pool.Connection.Cache.Find_By_Uuid(rec.Value[(int)RecProperties.ToHost]); - string powerOperation = Messages.ResourceManager.GetString(String.Format("WLB_OPT_OPERATION_HOST_{0}", rec.Value[(int)RecProperties.Reason].ToString().ToUpper())); + ParseRecommendationReason(rec.Value[(int)RecProperties.Reason], out var powerOperation, out _); - if (vm.is_control_domain && fromHost!=null && IsHostPowerOn(vm, powerOperation, fromHost)) + if (vm.is_control_domain && fromHost != null && IsHostPowerOn(vm, powerOperation, fromHost)) { powerOnHosts.Add(fromHost); } @@ -221,13 +189,64 @@ private List GetAllPowerOnHosts(Pool pool, Dictionary, string[] return powerOnHosts; } + private void ParseRecommendationReason(string reason, out string powerOperation, out string resourcedReasonOutput) + { + powerOperation = null; + + switch (reason.ToUpper()) + { + case "POWERON": + powerOperation = Messages.WLB_OPT_OPERATION_HOST_POWERON; + resourcedReasonOutput = Messages.WLB_OPT_REASON_POWERON; + break; + case "POWEROFF": + powerOperation = Messages.WLB_OPT_OPERATION_HOST_POWEROFF; + resourcedReasonOutput = Messages.WLB_OPT_REASON_POWEROFF; + break; + case "CONSOLIDATE": + resourcedReasonOutput = Messages.WLB_OPT_REASON_CONSOLIDATE; + break; + case "CPU": + resourcedReasonOutput = Messages.WLB_OPT_REASON_CPU; + break; + case "DISK": + resourcedReasonOutput = Messages.WLB_OPT_REASON_DISK; + break; + case "DISKREAD": + resourcedReasonOutput = Messages.WLB_OPT_REASON_DISKREAD; + break; + case "DISKWRITE": + resourcedReasonOutput = Messages.WLB_OPT_REASON_DISKWRITE; + break; + case "LOADAVERAGE": + resourcedReasonOutput = Messages.WLB_OPT_REASON_LOADAVERAGE; + break; + case "MEMORY": + resourcedReasonOutput = Messages.WLB_OPT_REASON_MEMORY; + break; + case "NETWORK": + resourcedReasonOutput = Messages.WLB_OPT_REASON_NETWORK; + break; + case "NETWORKREAD": + resourcedReasonOutput = Messages.WLB_OPT_REASON_NETWORKREAD; + break; + case "NETWORKWRITE": + resourcedReasonOutput = Messages.WLB_OPT_REASON_NETWORKWRITE; + break; + case "NONE": + resourcedReasonOutput = Messages.NONE_UPPER; + break; + default: + resourcedReasonOutput = Messages.UNKNOWN; + break; + } + } private int SortByRecommendationId(WlbOptimizationRecommendation x, WlbOptimizationRecommendation y) { return x.recId.CompareTo(y.recId); } - private bool IsHostPowerOnOff(VM vm, Host fromHost, string powerOperation, Dictionary, string[]> recommendations) { if (vm.is_control_domain && fromHost!=null) @@ -247,7 +266,6 @@ private bool IsHostPowerOnOff(VM vm, Host fromHost, string powerOperation, Dicti return false; } - private bool IsHostPowerOn(VM vm, string powerOperation, Host fromHost) { if (vm != null && !String.IsNullOrEmpty(powerOperation) && fromHost != null) @@ -258,7 +276,6 @@ private bool IsHostPowerOn(VM vm, string powerOperation, Host fromHost) return false; } - private bool IsHostPowerOff(VM vm, string powerOperation, Host fromHost) { if (vm != null && !String.IsNullOrEmpty(powerOperation) && fromHost != null) @@ -269,13 +286,11 @@ private bool IsHostPowerOff(VM vm, string powerOperation, Host fromHost) return false; } - private bool VmsOnPowerOffHostAreInRecommendations(Host fromHost, Dictionary, string[]> recommendations) { - foreach (XenRef vm in fromHost.resident_VMs) { - if(!(recommendations.ContainsKey(vm))) + if (!recommendations.ContainsKey(vm)) { return false; } @@ -283,6 +298,5 @@ private bool VmsOnPowerOffHostAreInRecommendations(Host fromHost, Dictionary - /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// The current state of the pool's Wlb Server State public static void SetState(Pool pool, ServerState state) { @@ -81,7 +81,7 @@ public static void SetState(Pool pool, ServerState state) /// Public method for updating the Wlb Server state. If the state is ConnectionFailure and /// a Failure is supplied, it's message is stored in the OtherConfig ///
- /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// The current state of the pool's Wlb Server State /// The Failure (if any) describing the Connection Error public static void SetState(Pool pool, ServerState state, Failure failure) @@ -93,7 +93,7 @@ public static void SetState(Pool pool, ServerState state, Failure failure) /// This method clears any existing failure message for the connection ///
/// The User session use to do this operation - /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// The current state of the pool's Wlb Server State public static void SetState(Session session, Pool pool, ServerState state) { @@ -104,7 +104,7 @@ public static void SetState(Session session, Pool pool, ServerState state) /// a Failure is supplied, it's message is stored in the OtherConfig ///
/// The User session use to do this operation - /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// The current state of the pool's Wlb Server State /// The Failure (if any) describing the Connection Error public static void SetState(Session session, Pool pool, ServerState state, Failure failure) @@ -120,15 +120,16 @@ public static void SetState(Session session, Pool pool, ServerState state, Failu if (null != failure && state == ServerState.ConnectionError) { - string error = String.Empty; + string error = failure.Message; + if (failure.Message == FriendlyErrorNames.WLB_INTERNAL_ERROR) { - error = Messages.ResourceManager.GetString("WLB_ERROR_" + failure.ErrorDescription[1]); - } - else - { - error = failure.Message; + var wlbError = ConvertWlbError(failure.ErrorDescription[1]); + + if (wlbError != null) + error = wlbError; } + Helpers.SetOtherConfig(session, pool, WLB_CONNECTION_ERROR, error); } else @@ -142,7 +143,7 @@ public static void SetState(Session session, Pool pool, ServerState state, Failu /// /// Public method for retrieving the current state of a Pool's Wlb server connection /// - /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// ServerState enumeration representing the current Wlb server conection state public static ServerState GetState(Pool pool) { @@ -167,7 +168,7 @@ public static ServerState GetState(Pool pool) /// Private method for determining (initializing) the state of the WlbConnectin when there is /// nothing yet stored in OtherConfig /// - /// The pool who's Wlb connection state we are updating + /// The pool whose Wlb connection state we are updating /// Bool denoting whether we were able to ascertain the current server state private static bool CheckForKnownState(Pool pool) { @@ -189,7 +190,7 @@ private static bool CheckForKnownState(Pool pool) /// /// Public method for retrieving the Failure message string stored in OtherConfig for the pool /// - /// The pool who's Wlb connection state we are retrieving + /// The pool whose Wlb connection state we are retrieving /// A string containing the Failure message, or an empty string public static string GetFailureMessage(Pool pool) { @@ -202,5 +203,69 @@ public static string GetFailureMessage(Pool pool) return message; } + + public static string ConvertWlbError(string codeString) + { + if (!int.TryParse(codeString, out var code)) + return null; + + switch (code) + { + case 5: + return Messages.WLB_ERROR_5; + case 6: + return Messages.WLB_ERROR_6; + case 4000: + return Messages.WLB_ERROR_4000; + case 4001: + return Messages.WLB_ERROR_4001; + case 4002: + return Messages.WLB_ERROR_4002; + case 4003: + return Messages.WLB_ERROR_4003; + case 4004: + return Messages.WLB_ERROR_4004; + case 4005: + return Messages.WLB_ERROR_4005; + case 4006: + return Messages.WLB_ERROR_4006; + case 4007: + return Messages.WLB_ERROR_4007; + case 4008: + return Messages.WLB_ERROR_4008; + case 4009: + return Messages.WLB_ERROR_4009; + case 4010: + return Messages.WLB_ERROR_4010; + case 4011: + return Messages.WLB_ERROR_4011; + case 4012: + return Messages.WLB_ERROR_4012; + case 4013: + return Messages.WLB_ERROR_4013; + case 4014: + return Messages.WLB_ERROR_4014; + case 4015: + return Messages.WLB_ERROR_4015; + case 4016: + return Messages.WLB_ERROR_4016; + case 4017: + return Messages.WLB_ERROR_4017; + case 4018: + return Messages.WLB_ERROR_4018; + case 4019: + return Messages.WLB_ERROR_4019; + case 4020: + return Messages.WLB_ERROR_4020; + case 4021: + return Messages.WLB_ERROR_4021; + case 4022: + return Messages.WLB_ERROR_4022; + case 4023: + return Messages.WLB_ERROR_4023; + default: + return null; + } + } } } diff --git a/XenModel/XenAPI-Extensions/Host.cs b/XenModel/XenAPI-Extensions/Host.cs index 191ceb0ede..b5ceab9dff 100644 --- a/XenModel/XenAPI-Extensions/Host.cs +++ b/XenModel/XenAPI-Extensions/Host.cs @@ -651,19 +651,14 @@ public virtual string ProductVersion() return Get(software_version, "product_version"); } - private string MarketingVersion(string field) - { - string s = Get(software_version, field); - return string.IsNullOrEmpty(s) ? ProductVersion() : s; - } - /// /// Return this host's marketing version number (e.g. 5.6 Feature Pack 1), /// or ProductVersion (which can still be null) if it can't be found, including pre-Cowley hosts. /// public string ProductVersionText() { - return MarketingVersion("product_version_text"); + string s = Get(software_version, "product_version_text"); + return string.IsNullOrEmpty(s) ? ProductVersion() : s; } /// @@ -672,7 +667,8 @@ public string ProductVersionText() /// public string ProductVersionTextShort() { - return MarketingVersion("product_version_text_short"); + string s = Get(software_version, "product_version_text_short"); + return string.IsNullOrEmpty(s) ? ProductVersion() : s; } /// diff --git a/XenModel/XenAPI-Extensions/PIF.cs b/XenModel/XenAPI-Extensions/PIF.cs index 224794bdf8..b4c0e46fed 100644 --- a/XenModel/XenAPI-Extensions/PIF.cs +++ b/XenModel/XenAPI-Extensions/PIF.cs @@ -362,7 +362,7 @@ public string IpConfigurationModeString() switch (ip_configuration_mode) { case ip_configuration_mode.None: - return Messages.PIF_NONE; + return Messages.NONE_UPPER; case ip_configuration_mode.DHCP: return Messages.PIF_DHCP; case ip_configuration_mode.Static: diff --git a/XenModel/XenAPI/Blob.cs b/XenModel/XenAPI/Blob.cs index 45c56719c0..88e21b1790 100644 --- a/XenModel/XenAPI/Blob.cs +++ b/XenModel/XenAPI/Blob.cs @@ -128,13 +128,13 @@ public bool DeepEquals(Blob other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._size, other._size) && - Helper.AreEqual2(this._pubblic, other._pubblic) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._mime_type, other._mime_type); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_size, other._size) && + Helper.AreEqual2(_pubblic, other._pubblic) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_mime_type, other._mime_type); } public override string SaveChanges(Session session, string opaqueRef, Blob server) diff --git a/XenModel/XenAPI/Bond.cs b/XenModel/XenAPI/Bond.cs index 70ba3fddc7..ef7a92fbbf 100644 --- a/XenModel/XenAPI/Bond.cs +++ b/XenModel/XenAPI/Bond.cs @@ -118,13 +118,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("slaves")) slaves = Marshalling.ParseSetRef(table, "slaves"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("primary_slave")) primary_slave = Marshalling.ParseRef(table, "primary_slave"); if (table.ContainsKey("mode")) mode = (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), Marshalling.ParseString(table, "mode")); if (table.ContainsKey("properties")) - properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "properties")); + properties = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "properties")); if (table.ContainsKey("links_up")) links_up = Marshalling.ParseLong(table, "links_up"); if (table.ContainsKey("auto_update_mac")) @@ -138,15 +138,15 @@ public bool DeepEquals(Bond other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._master, other._master) && - Helper.AreEqual2(this._slaves, other._slaves) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._primary_slave, other._primary_slave) && - Helper.AreEqual2(this._mode, other._mode) && - Helper.AreEqual2(this._properties, other._properties) && - Helper.AreEqual2(this._links_up, other._links_up) && - Helper.AreEqual2(this._auto_update_mac, other._auto_update_mac); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_master, other._master) && + Helper.AreEqual2(_slaves, other._slaves) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_primary_slave, other._primary_slave) && + Helper.AreEqual2(_mode, other._mode) && + Helper.AreEqual2(_properties, other._properties) && + Helper.AreEqual2(_links_up, other._links_up) && + Helper.AreEqual2(_auto_update_mac, other._auto_update_mac); } public override string SaveChanges(Session session, string opaqueRef, Bond server) diff --git a/XenModel/XenAPI/Certificate.cs b/XenModel/XenAPI/Certificate.cs index b37ae8eb50..905eafa0d9 100644 --- a/XenModel/XenAPI/Certificate.cs +++ b/XenModel/XenAPI/Certificate.cs @@ -128,13 +128,13 @@ public bool DeepEquals(Certificate other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name, other._name) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._not_before, other._not_before) && - Helper.AreEqual2(this._not_after, other._not_after) && - Helper.AreEqual2(this._fingerprint, other._fingerprint); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name, other._name) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_not_before, other._not_before) && + Helper.AreEqual2(_not_after, other._not_after) && + Helper.AreEqual2(_fingerprint, other._fingerprint); } public override string SaveChanges(Session session, string opaqueRef, Certificate server) diff --git a/XenModel/XenAPI/Cluster.cs b/XenModel/XenAPI/Cluster.cs index e82d8d3c7c..cb0beded3e 100644 --- a/XenModel/XenAPI/Cluster.cs +++ b/XenModel/XenAPI/Cluster.cs @@ -133,7 +133,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_cluster_operation(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_cluster_operation(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("pool_auto_join")) pool_auto_join = Marshalling.ParseBool(table, "pool_auto_join"); if (table.ContainsKey("token_timeout")) @@ -141,9 +141,9 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("token_timeout_coefficient")) token_timeout_coefficient = Marshalling.ParseDouble(table, "token_timeout_coefficient"); if (table.ContainsKey("cluster_config")) - cluster_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cluster_config")); + cluster_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "cluster_config")); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Cluster other, bool ignoreCurrentOperations) @@ -153,20 +153,20 @@ public bool DeepEquals(Cluster other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._cluster_hosts, other._cluster_hosts) && - Helper.AreEqual2(this._pending_forget, other._pending_forget) && - Helper.AreEqual2(this._cluster_token, other._cluster_token) && - Helper.AreEqual2(this._cluster_stack, other._cluster_stack) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._pool_auto_join, other._pool_auto_join) && - Helper.AreEqual2(this._token_timeout, other._token_timeout) && - Helper.AreEqual2(this._token_timeout_coefficient, other._token_timeout_coefficient) && - Helper.AreEqual2(this._cluster_config, other._cluster_config) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_cluster_hosts, other._cluster_hosts) && + Helper.AreEqual2(_pending_forget, other._pending_forget) && + Helper.AreEqual2(_cluster_token, other._cluster_token) && + Helper.AreEqual2(_cluster_stack, other._cluster_stack) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_pool_auto_join, other._pool_auto_join) && + Helper.AreEqual2(_token_timeout, other._token_timeout) && + Helper.AreEqual2(_token_timeout_coefficient, other._token_timeout_coefficient) && + Helper.AreEqual2(_cluster_config, other._cluster_config) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Cluster server) diff --git a/XenModel/XenAPI/Cluster_host.cs b/XenModel/XenAPI/Cluster_host.cs index c420a4b144..4762efeee9 100644 --- a/XenModel/XenAPI/Cluster_host.cs +++ b/XenModel/XenAPI/Cluster_host.cs @@ -126,9 +126,9 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_cluster_host_operation(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_cluster_host_operation(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Cluster_host other, bool ignoreCurrentOperations) @@ -138,17 +138,17 @@ public bool DeepEquals(Cluster_host other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._cluster, other._cluster) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._enabled, other._enabled) && - Helper.AreEqual2(this._PIF, other._PIF) && - Helper.AreEqual2(this._joined, other._joined) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_cluster, other._cluster) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_enabled, other._enabled) && + Helper.AreEqual2(_PIF, other._PIF) && + Helper.AreEqual2(_joined, other._joined) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Cluster_host server) diff --git a/XenModel/XenAPI/Console.cs b/XenModel/XenAPI/Console.cs index 8aa66be728..4fceff91dc 100644 --- a/XenModel/XenAPI/Console.cs +++ b/XenModel/XenAPI/Console.cs @@ -108,7 +108,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("VM")) VM = Marshalling.ParseRef(table, "VM"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Console other) @@ -118,11 +118,11 @@ public bool DeepEquals(Console other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._protocol, other._protocol) && - Helper.AreEqual2(this._location, other._location) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_protocol, other._protocol) && + Helper.AreEqual2(_location, other._location) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Console server) diff --git a/XenModel/XenAPI/Crashdump.cs b/XenModel/XenAPI/Crashdump.cs index 5130cacaa5..8db6111ce0 100644 --- a/XenModel/XenAPI/Crashdump.cs +++ b/XenModel/XenAPI/Crashdump.cs @@ -103,7 +103,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("VDI")) VDI = Marshalling.ParseRef(table, "VDI"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Crashdump other) @@ -113,10 +113,10 @@ public bool DeepEquals(Crashdump other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._VDI, other._VDI) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_VDI, other._VDI) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Crashdump server) diff --git a/XenModel/XenAPI/DR_task.cs b/XenModel/XenAPI/DR_task.cs index bcaca1e0b6..31e48f2410 100644 --- a/XenModel/XenAPI/DR_task.cs +++ b/XenModel/XenAPI/DR_task.cs @@ -103,8 +103,8 @@ public bool DeepEquals(DR_task other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._introduced_SRs, other._introduced_SRs); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_introduced_SRs, other._introduced_SRs); } public override string SaveChanges(Session session, string opaqueRef, DR_task server) diff --git a/XenModel/XenAPI/Data_source.cs b/XenModel/XenAPI/Data_source.cs index 91d1a7d150..b80aed693e 100644 --- a/XenModel/XenAPI/Data_source.cs +++ b/XenModel/XenAPI/Data_source.cs @@ -133,14 +133,14 @@ public bool DeepEquals(Data_source other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._enabled, other._enabled) && - Helper.AreEqual2(this._standard, other._standard) && - Helper.AreEqual2(this._units, other._units) && - Helper.AreEqual2(this._min, other._min) && - Helper.AreEqual2(this._max, other._max) && - Helper.AreEqual2(this._value, other._value); + return Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_enabled, other._enabled) && + Helper.AreEqual2(_standard, other._standard) && + Helper.AreEqual2(_units, other._units) && + Helper.AreEqual2(_min, other._min) && + Helper.AreEqual2(_max, other._max) && + Helper.AreEqual2(_value, other._value); } public override string SaveChanges(Session session, string opaqueRef, Data_source server) diff --git a/XenModel/XenAPI/Feature.cs b/XenModel/XenAPI/Feature.cs index 3ad13a1101..3b5d40d1db 100644 --- a/XenModel/XenAPI/Feature.cs +++ b/XenModel/XenAPI/Feature.cs @@ -128,13 +128,13 @@ public bool DeepEquals(Feature other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._enabled, other._enabled) && - Helper.AreEqual2(this._experimental, other._experimental) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._host, other._host); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_enabled, other._enabled) && + Helper.AreEqual2(_experimental, other._experimental) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_host, other._host); } public override string SaveChanges(Session session, string opaqueRef, Feature server) diff --git a/XenModel/XenAPI/FriendlyErrorNames.Designer.cs b/XenModel/XenAPI/FriendlyErrorNames.Designer.cs index b0824753a5..92b362a184 100755 --- a/XenModel/XenAPI/FriendlyErrorNames.Designer.cs +++ b/XenModel/XenAPI/FriendlyErrorNames.Designer.cs @@ -3143,15 +3143,6 @@ public static string REPOSYNC_FAILED { } } - /// - /// Looks up a localized string similar to The pool is syncing with the enabled remote YUM repository.. - /// - public static string REPOSYNC_IN_PROGRESS { - get { - return ResourceManager.GetString("REPOSYNC_IN_PROGRESS", resourceCulture); - } - } - /// /// Looks up a localized string similar to The operation you requested cannot be performed because the specified PIF is currently unplugged.. /// diff --git a/XenModel/XenAPI/FriendlyErrorNames.resx b/XenModel/XenAPI/FriendlyErrorNames.resx index 6d8a0aebba..b84cc3f459 100755 --- a/XenModel/XenAPI/FriendlyErrorNames.resx +++ b/XenModel/XenAPI/FriendlyErrorNames.resx @@ -1148,9 +1148,6 @@ Authorized Roles: {1} Syncing with remote YUM repository failed. - - The pool is syncing with the enabled remote YUM repository. - The operation you requested cannot be performed because the specified PIF is currently unplugged. diff --git a/XenModel/XenAPI/GPU_group.cs b/XenModel/XenAPI/GPU_group.cs index e2a70d6807..468ec89407 100644 --- a/XenModel/XenAPI/GPU_group.cs +++ b/XenModel/XenAPI/GPU_group.cs @@ -127,7 +127,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("GPU_types")) GPU_types = Marshalling.ParseStringArray(table, "GPU_types"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("allocation_algorithm")) allocation_algorithm = (allocation_algorithm)Helper.EnumParseDefault(typeof(allocation_algorithm), Marshalling.ParseString(table, "allocation_algorithm")); if (table.ContainsKey("supported_VGPU_types")) @@ -143,16 +143,16 @@ public bool DeepEquals(GPU_group other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._PGPUs, other._PGPUs) && - Helper.AreEqual2(this._VGPUs, other._VGPUs) && - Helper.AreEqual2(this._GPU_types, other._GPU_types) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._allocation_algorithm, other._allocation_algorithm) && - Helper.AreEqual2(this._supported_VGPU_types, other._supported_VGPU_types) && - Helper.AreEqual2(this._enabled_VGPU_types, other._enabled_VGPU_types); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_PGPUs, other._PGPUs) && + Helper.AreEqual2(_VGPUs, other._VGPUs) && + Helper.AreEqual2(_GPU_types, other._GPU_types) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_allocation_algorithm, other._allocation_algorithm) && + Helper.AreEqual2(_supported_VGPU_types, other._supported_VGPU_types) && + Helper.AreEqual2(_enabled_VGPU_types, other._enabled_VGPU_types); } public override string SaveChanges(Session session, string opaqueRef, GPU_group server) diff --git a/XenModel/XenAPI/Host.cs b/XenModel/XenAPI/Host.cs index adb0f0a72c..00f1242a67 100755 --- a/XenModel/XenAPI/Host.cs +++ b/XenModel/XenAPI/Host.cs @@ -116,7 +116,6 @@ public Host(string uuid, bool tls_verification_enabled, DateTime last_software_update, bool https_only, - List recommended_guidances, latest_synced_updates_applied_state latest_synced_updates_applied) { this.uuid = uuid; @@ -184,7 +183,6 @@ public Host(string uuid, this.tls_verification_enabled = tls_verification_enabled; this.last_software_update = last_software_update; this.https_only = https_only; - this.recommended_guidances = recommended_guidances; this.latest_synced_updates_applied = latest_synced_updates_applied; } @@ -273,7 +271,6 @@ public override void UpdateFrom(Host record) tls_verification_enabled = record.tls_verification_enabled; last_software_update = record.last_software_update; https_only = record.https_only; - recommended_guidances = record.recommended_guidances; latest_synced_updates_applied = record.latest_synced_updates_applied; } @@ -296,7 +293,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_host_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_host_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("API_version_major")) API_version_major = Marshalling.ParseLong(table, "API_version_major"); if (table.ContainsKey("API_version_minor")) @@ -304,17 +301,17 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("API_version_vendor")) API_version_vendor = Marshalling.ParseString(table, "API_version_vendor"); if (table.ContainsKey("API_version_vendor_implementation")) - API_version_vendor_implementation = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "API_version_vendor_implementation")); + API_version_vendor_implementation = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "API_version_vendor_implementation")); if (table.ContainsKey("enabled")) enabled = Marshalling.ParseBool(table, "enabled"); if (table.ContainsKey("software_version")) - software_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "software_version")); + software_version = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "software_version")); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("capabilities")) capabilities = Marshalling.ParseStringArray(table, "capabilities"); if (table.ContainsKey("cpu_configuration")) - cpu_configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cpu_configuration")); + cpu_configuration = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "cpu_configuration")); if (table.ContainsKey("sched_policy")) sched_policy = Marshalling.ParseString(table, "sched_policy"); if (table.ContainsKey("supported_bootloaders")) @@ -322,7 +319,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("resident_VMs")) resident_VMs = Marshalling.ParseSetRef(table, "resident_VMs"); if (table.ContainsKey("logging")) - logging = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "logging")); + logging = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "logging")); if (table.ContainsKey("PIFs")) PIFs = Marshalling.ParseSetRef(table, "PIFs"); if (table.ContainsKey("suspend_image_sr")) @@ -340,7 +337,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("host_CPUs")) host_CPUs = Marshalling.ParseSetRef(table, "host_CPUs"); if (table.ContainsKey("cpu_info")) - cpu_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cpu_info")); + cpu_info = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "cpu_info")); if (table.ContainsKey("hostname")) hostname = Marshalling.ParseString(table, "hostname"); if (table.ContainsKey("address")) @@ -348,13 +345,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("metrics")) metrics = Marshalling.ParseRef(table, "metrics"); if (table.ContainsKey("license_params")) - license_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "license_params")); + license_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "license_params")); if (table.ContainsKey("ha_statefiles")) ha_statefiles = Marshalling.ParseStringArray(table, "ha_statefiles"); if (table.ContainsKey("ha_network_peers")) ha_network_peers = Marshalling.ParseStringArray(table, "ha_network_peers"); if (table.ContainsKey("blobs")) - blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); + blobs = Maps.ToDictionary_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("external_auth_type")) @@ -362,21 +359,21 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("external_auth_service_name")) external_auth_service_name = Marshalling.ParseString(table, "external_auth_service_name"); if (table.ContainsKey("external_auth_configuration")) - external_auth_configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "external_auth_configuration")); + external_auth_configuration = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "external_auth_configuration")); if (table.ContainsKey("edition")) edition = Marshalling.ParseString(table, "edition"); if (table.ContainsKey("license_server")) - license_server = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "license_server")); + license_server = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "license_server")); if (table.ContainsKey("bios_strings")) - bios_strings = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "bios_strings")); + bios_strings = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "bios_strings")); if (table.ContainsKey("power_on_mode")) power_on_mode = Marshalling.ParseString(table, "power_on_mode"); if (table.ContainsKey("power_on_config")) - power_on_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "power_on_config")); + power_on_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "power_on_config")); if (table.ContainsKey("local_cache_sr")) local_cache_sr = Marshalling.ParseRef(table, "local_cache_sr"); if (table.ContainsKey("chipset_info")) - chipset_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "chipset_info")); + chipset_info = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "chipset_info")); if (table.ContainsKey("PCIs")) PCIs = Marshalling.ParseSetRef(table, "PCIs"); if (table.ContainsKey("PGPUs")) @@ -386,7 +383,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("ssl_legacy")) ssl_legacy = Marshalling.ParseBool(table, "ssl_legacy"); if (table.ContainsKey("guest_VCPUs_params")) - guest_VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "guest_VCPUs_params")); + guest_VCPUs_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "guest_VCPUs_params")); if (table.ContainsKey("display")) display = (host_display)Helper.EnumParseDefault(typeof(host_display), Marshalling.ParseString(table, "display")); if (table.ContainsKey("virtual_hardware_platform_versions")) @@ -415,8 +412,6 @@ public void UpdateFrom(Hashtable table) last_software_update = Marshalling.ParseDateTime(table, "last_software_update"); if (table.ContainsKey("https_only")) https_only = Marshalling.ParseBool(table, "https_only"); - if (table.ContainsKey("recommended_guidances")) - recommended_guidances = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "recommended_guidances")); if (table.ContainsKey("latest_synced_updates_applied")) latest_synced_updates_applied = (latest_synced_updates_applied_state)Helper.EnumParseDefault(typeof(latest_synced_updates_applied_state), Marshalling.ParseString(table, "latest_synced_updates_applied")); } @@ -428,75 +423,74 @@ public bool DeepEquals(Host other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._memory_overhead, other._memory_overhead) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._API_version_major, other._API_version_major) && - Helper.AreEqual2(this._API_version_minor, other._API_version_minor) && - Helper.AreEqual2(this._API_version_vendor, other._API_version_vendor) && - Helper.AreEqual2(this._API_version_vendor_implementation, other._API_version_vendor_implementation) && - Helper.AreEqual2(this._enabled, other._enabled) && - Helper.AreEqual2(this._software_version, other._software_version) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._capabilities, other._capabilities) && - Helper.AreEqual2(this._cpu_configuration, other._cpu_configuration) && - Helper.AreEqual2(this._sched_policy, other._sched_policy) && - Helper.AreEqual2(this._supported_bootloaders, other._supported_bootloaders) && - Helper.AreEqual2(this._resident_VMs, other._resident_VMs) && - Helper.AreEqual2(this._logging, other._logging) && - Helper.AreEqual2(this._PIFs, other._PIFs) && - Helper.AreEqual2(this._suspend_image_sr, other._suspend_image_sr) && - Helper.AreEqual2(this._crash_dump_sr, other._crash_dump_sr) && - Helper.AreEqual2(this._crashdumps, other._crashdumps) && - Helper.AreEqual2(this._patches, other._patches) && - Helper.AreEqual2(this._updates, other._updates) && - Helper.AreEqual2(this._PBDs, other._PBDs) && - Helper.AreEqual2(this._host_CPUs, other._host_CPUs) && - Helper.AreEqual2(this._cpu_info, other._cpu_info) && - Helper.AreEqual2(this._hostname, other._hostname) && - Helper.AreEqual2(this._address, other._address) && - Helper.AreEqual2(this._metrics, other._metrics) && - Helper.AreEqual2(this._license_params, other._license_params) && - Helper.AreEqual2(this._ha_statefiles, other._ha_statefiles) && - Helper.AreEqual2(this._ha_network_peers, other._ha_network_peers) && - Helper.AreEqual2(this._blobs, other._blobs) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._external_auth_type, other._external_auth_type) && - Helper.AreEqual2(this._external_auth_service_name, other._external_auth_service_name) && - Helper.AreEqual2(this._external_auth_configuration, other._external_auth_configuration) && - Helper.AreEqual2(this._edition, other._edition) && - Helper.AreEqual2(this._license_server, other._license_server) && - Helper.AreEqual2(this._bios_strings, other._bios_strings) && - Helper.AreEqual2(this._power_on_mode, other._power_on_mode) && - Helper.AreEqual2(this._power_on_config, other._power_on_config) && - Helper.AreEqual2(this._local_cache_sr, other._local_cache_sr) && - Helper.AreEqual2(this._chipset_info, other._chipset_info) && - Helper.AreEqual2(this._PCIs, other._PCIs) && - Helper.AreEqual2(this._PGPUs, other._PGPUs) && - Helper.AreEqual2(this._PUSBs, other._PUSBs) && - Helper.AreEqual2(this._ssl_legacy, other._ssl_legacy) && - Helper.AreEqual2(this._guest_VCPUs_params, other._guest_VCPUs_params) && - Helper.AreEqual2(this._display, other._display) && - Helper.AreEqual2(this._virtual_hardware_platform_versions, other._virtual_hardware_platform_versions) && - Helper.AreEqual2(this._control_domain, other._control_domain) && - Helper.AreEqual2(this._updates_requiring_reboot, other._updates_requiring_reboot) && - Helper.AreEqual2(this._features, other._features) && - Helper.AreEqual2(this._iscsi_iqn, other._iscsi_iqn) && - Helper.AreEqual2(this._multipathing, other._multipathing) && - Helper.AreEqual2(this._uefi_certificates, other._uefi_certificates) && - Helper.AreEqual2(this._certificates, other._certificates) && - Helper.AreEqual2(this._editions, other._editions) && - Helper.AreEqual2(this._pending_guidances, other._pending_guidances) && - Helper.AreEqual2(this._tls_verification_enabled, other._tls_verification_enabled) && - Helper.AreEqual2(this._last_software_update, other._last_software_update) && - Helper.AreEqual2(this._https_only, other._https_only) && - Helper.AreEqual2(this._recommended_guidances, other._recommended_guidances) && - Helper.AreEqual2(this._latest_synced_updates_applied, other._latest_synced_updates_applied); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_memory_overhead, other._memory_overhead) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_API_version_major, other._API_version_major) && + Helper.AreEqual2(_API_version_minor, other._API_version_minor) && + Helper.AreEqual2(_API_version_vendor, other._API_version_vendor) && + Helper.AreEqual2(_API_version_vendor_implementation, other._API_version_vendor_implementation) && + Helper.AreEqual2(_enabled, other._enabled) && + Helper.AreEqual2(_software_version, other._software_version) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_capabilities, other._capabilities) && + Helper.AreEqual2(_cpu_configuration, other._cpu_configuration) && + Helper.AreEqual2(_sched_policy, other._sched_policy) && + Helper.AreEqual2(_supported_bootloaders, other._supported_bootloaders) && + Helper.AreEqual2(_resident_VMs, other._resident_VMs) && + Helper.AreEqual2(_logging, other._logging) && + Helper.AreEqual2(_PIFs, other._PIFs) && + Helper.AreEqual2(_suspend_image_sr, other._suspend_image_sr) && + Helper.AreEqual2(_crash_dump_sr, other._crash_dump_sr) && + Helper.AreEqual2(_crashdumps, other._crashdumps) && + Helper.AreEqual2(_patches, other._patches) && + Helper.AreEqual2(_updates, other._updates) && + Helper.AreEqual2(_PBDs, other._PBDs) && + Helper.AreEqual2(_host_CPUs, other._host_CPUs) && + Helper.AreEqual2(_cpu_info, other._cpu_info) && + Helper.AreEqual2(_hostname, other._hostname) && + Helper.AreEqual2(_address, other._address) && + Helper.AreEqual2(_metrics, other._metrics) && + Helper.AreEqual2(_license_params, other._license_params) && + Helper.AreEqual2(_ha_statefiles, other._ha_statefiles) && + Helper.AreEqual2(_ha_network_peers, other._ha_network_peers) && + Helper.AreEqual2(_blobs, other._blobs) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_external_auth_type, other._external_auth_type) && + Helper.AreEqual2(_external_auth_service_name, other._external_auth_service_name) && + Helper.AreEqual2(_external_auth_configuration, other._external_auth_configuration) && + Helper.AreEqual2(_edition, other._edition) && + Helper.AreEqual2(_license_server, other._license_server) && + Helper.AreEqual2(_bios_strings, other._bios_strings) && + Helper.AreEqual2(_power_on_mode, other._power_on_mode) && + Helper.AreEqual2(_power_on_config, other._power_on_config) && + Helper.AreEqual2(_local_cache_sr, other._local_cache_sr) && + Helper.AreEqual2(_chipset_info, other._chipset_info) && + Helper.AreEqual2(_PCIs, other._PCIs) && + Helper.AreEqual2(_PGPUs, other._PGPUs) && + Helper.AreEqual2(_PUSBs, other._PUSBs) && + Helper.AreEqual2(_ssl_legacy, other._ssl_legacy) && + Helper.AreEqual2(_guest_VCPUs_params, other._guest_VCPUs_params) && + Helper.AreEqual2(_display, other._display) && + Helper.AreEqual2(_virtual_hardware_platform_versions, other._virtual_hardware_platform_versions) && + Helper.AreEqual2(_control_domain, other._control_domain) && + Helper.AreEqual2(_updates_requiring_reboot, other._updates_requiring_reboot) && + Helper.AreEqual2(_features, other._features) && + Helper.AreEqual2(_iscsi_iqn, other._iscsi_iqn) && + Helper.AreEqual2(_multipathing, other._multipathing) && + Helper.AreEqual2(_uefi_certificates, other._uefi_certificates) && + Helper.AreEqual2(_certificates, other._certificates) && + Helper.AreEqual2(_editions, other._editions) && + Helper.AreEqual2(_pending_guidances, other._pending_guidances) && + Helper.AreEqual2(_tls_verification_enabled, other._tls_verification_enabled) && + Helper.AreEqual2(_last_software_update, other._last_software_update) && + Helper.AreEqual2(_https_only, other._https_only) && + Helper.AreEqual2(_latest_synced_updates_applied, other._latest_synced_updates_applied); } public override string SaveChanges(Session session, string opaqueRef, Host server) @@ -1331,17 +1325,6 @@ public static bool get_https_only(Session session, string _host) return session.JsonRpcClient.host_get_https_only(session.opaque_ref, _host); } - /// - /// Get the recommended_guidances field of the given host. - /// Experimental. First published in 23.18.0. - /// - /// The session - /// The opaque_ref of the given host - public static List get_recommended_guidances(Session session, string _host) - { - return session.JsonRpcClient.host_get_recommended_guidances(session.opaque_ref, _host); - } - /// /// Get the latest_synced_updates_applied field of the given host. /// Experimental. First published in 23.18.0. @@ -4277,24 +4260,6 @@ public virtual bool https_only } private bool _https_only = false; - /// - /// The set of recommended guidances after applying updates - /// Experimental. First published in 23.18.0. - /// - public virtual List recommended_guidances - { - get { return _recommended_guidances; } - set - { - if (!Helper.AreEqual(value, _recommended_guidances)) - { - _recommended_guidances = value; - NotifyPropertyChanged("recommended_guidances"); - } - } - } - private List _recommended_guidances = new List() {}; - /// /// Default as 'unknown', 'yes' if the host is up to date with updates synced from remote CDN, otherwise 'no' /// Experimental. First published in 23.18.0. diff --git a/XenModel/XenAPI/Host_cpu.cs b/XenModel/XenAPI/Host_cpu.cs index 6effbc8b11..c859612f0e 100644 --- a/XenModel/XenAPI/Host_cpu.cs +++ b/XenModel/XenAPI/Host_cpu.cs @@ -148,7 +148,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("utilisation")) utilisation = Marshalling.ParseDouble(table, "utilisation"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_cpu other) @@ -158,19 +158,19 @@ public bool DeepEquals(Host_cpu other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._number, other._number) && - Helper.AreEqual2(this._vendor, other._vendor) && - Helper.AreEqual2(this._speed, other._speed) && - Helper.AreEqual2(this._modelname, other._modelname) && - Helper.AreEqual2(this._family, other._family) && - Helper.AreEqual2(this._model, other._model) && - Helper.AreEqual2(this._stepping, other._stepping) && - Helper.AreEqual2(this._flags, other._flags) && - Helper.AreEqual2(this._features, other._features) && - Helper.AreEqual2(this._utilisation, other._utilisation) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_number, other._number) && + Helper.AreEqual2(_vendor, other._vendor) && + Helper.AreEqual2(_speed, other._speed) && + Helper.AreEqual2(_modelname, other._modelname) && + Helper.AreEqual2(_family, other._family) && + Helper.AreEqual2(_model, other._model) && + Helper.AreEqual2(_stepping, other._stepping) && + Helper.AreEqual2(_flags, other._flags) && + Helper.AreEqual2(_features, other._features) && + Helper.AreEqual2(_utilisation, other._utilisation) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_cpu server) diff --git a/XenModel/XenAPI/Host_crashdump.cs b/XenModel/XenAPI/Host_crashdump.cs index f15fb4722a..8f763d661d 100644 --- a/XenModel/XenAPI/Host_crashdump.cs +++ b/XenModel/XenAPI/Host_crashdump.cs @@ -108,7 +108,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("size")) size = Marshalling.ParseLong(table, "size"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_crashdump other) @@ -118,11 +118,11 @@ public bool DeepEquals(Host_crashdump other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._timestamp, other._timestamp) && - Helper.AreEqual2(this._size, other._size) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_timestamp, other._timestamp) && + Helper.AreEqual2(_size, other._size) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_crashdump server) diff --git a/XenModel/XenAPI/Host_metrics.cs b/XenModel/XenAPI/Host_metrics.cs index 2b163a7e49..5ae1a0943a 100644 --- a/XenModel/XenAPI/Host_metrics.cs +++ b/XenModel/XenAPI/Host_metrics.cs @@ -113,7 +113,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_metrics other) @@ -123,12 +123,12 @@ public bool DeepEquals(Host_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._memory_total, other._memory_total) && - Helper.AreEqual2(this._memory_free, other._memory_free) && - Helper.AreEqual2(this._live, other._live) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_memory_total, other._memory_total) && + Helper.AreEqual2(_memory_free, other._memory_free) && + Helper.AreEqual2(_live, other._live) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_metrics server) diff --git a/XenModel/XenAPI/Host_patch.cs b/XenModel/XenAPI/Host_patch.cs index f7fd7370ac..cefcfca9c6 100644 --- a/XenModel/XenAPI/Host_patch.cs +++ b/XenModel/XenAPI/Host_patch.cs @@ -133,7 +133,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("pool_patch")) pool_patch = Marshalling.ParseRef(table, "pool_patch"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_patch other) @@ -143,16 +143,16 @@ public bool DeepEquals(Host_patch other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._applied, other._applied) && - Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) && - Helper.AreEqual2(this._size, other._size) && - Helper.AreEqual2(this._pool_patch, other._pool_patch) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_applied, other._applied) && + Helper.AreEqual2(_timestamp_applied, other._timestamp_applied) && + Helper.AreEqual2(_size, other._size) && + Helper.AreEqual2(_pool_patch, other._pool_patch) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_patch server) diff --git a/XenModel/XenAPI/JsonRpcClient.cs b/XenModel/XenAPI/JsonRpcClient.cs index 2d95f24171..bad088d014 100755 --- a/XenModel/XenAPI/JsonRpcClient.cs +++ b/XenModel/XenAPI/JsonRpcClient.cs @@ -3377,13 +3377,6 @@ public List vm_get_pending_guidances(string session, string _v return Rpc>("VM.get_pending_guidances", new JArray(session, _vm ?? ""), serializer); } - public List vm_get_recommended_guidances(string session, string _vm) - { - var converters = new List {}; - var serializer = CreateSerializer(converters); - return Rpc>("VM.get_recommended_guidances", new JArray(session, _vm ?? ""), serializer); - } - public void vm_set_name_label(string session, string _vm, string _label) { var converters = new List {}; @@ -6394,13 +6387,6 @@ public bool host_get_https_only(string session, string _host) return Rpc("host.get_https_only", new JArray(session, _host ?? ""), serializer); } - public List host_get_recommended_guidances(string session, string _host) - { - var converters = new List {}; - var serializer = CreateSerializer(converters); - return Rpc>("host.get_recommended_guidances", new JArray(session, _host ?? ""), serializer); - } - public latest_synced_updates_applied_state host_get_latest_synced_updates_applied(string session, string _host) { var converters = new List {new latest_synced_updates_applied_stateConverter()}; @@ -6408,13 +6394,6 @@ public latest_synced_updates_applied_state host_get_latest_synced_updates_applie return Rpc("host.get_latest_synced_updates_applied", new JArray(session, _host ?? ""), serializer); } - public bool host_get_toolstack_restart_required_after_update(string session, string _host) - { - var converters = new List {}; - var serializer = CreateSerializer(converters); - return Rpc("host.get_toolstack_restart_required_after_update", new JArray(session, _host ?? ""), serializer); - } - public void host_set_name_label(string session, string _host, string _label) { var converters = new List {}; diff --git a/XenModel/XenAPI/LVHD.cs b/XenModel/XenAPI/LVHD.cs index 45331ac9d8..2ce2eff732 100644 --- a/XenModel/XenAPI/LVHD.cs +++ b/XenModel/XenAPI/LVHD.cs @@ -98,7 +98,7 @@ public bool DeepEquals(LVHD other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid); + return Helper.AreEqual2(_uuid, other._uuid); } public override string SaveChanges(Session session, string opaqueRef, LVHD server) diff --git a/XenModel/XenAPI/Maps.cs b/XenModel/XenAPI/Maps.cs index a1f0b899a3..28d4b911ae 100644 --- a/XenModel/XenAPI/Maps.cs +++ b/XenModel/XenAPI/Maps.cs @@ -36,9 +36,8 @@ namespace XenAPI { internal class Maps { - internal static Dictionary convert_from_proxy_string_string(Object o) + internal static Dictionary ToDictionary_string_string(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -59,32 +58,9 @@ internal static Dictionary convert_from_proxy_string_string(Obje return result; } - internal static Hashtable convert_to_proxy_string_string(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = table[key] ?? ""; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_long(Object o) + internal static Dictionary ToDictionary_string_long(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -105,32 +81,9 @@ internal static Dictionary convert_from_proxy_string_long(Object o return result; } - internal static Hashtable convert_to_proxy_string_long(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = table[key].ToString(); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_cluster_host_operation(Object o) + internal static Dictionary ToDictionary_string_cluster_host_operation(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -151,32 +104,9 @@ internal static Dictionary convert_from_proxy_st return result; } - internal static Hashtable convert_to_proxy_string_cluster_host_operation(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = cluster_host_operation_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_cluster_operation(Object o) + internal static Dictionary ToDictionary_string_cluster_operation(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -197,32 +127,9 @@ internal static Dictionary convert_from_proxy_string_ return result; } - internal static Hashtable convert_to_proxy_string_cluster_operation(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = cluster_operation_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_host_allowed_operations(Object o) + internal static Dictionary ToDictionary_string_host_allowed_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -243,32 +150,9 @@ internal static Dictionary convert_from_proxy_s return result; } - internal static Hashtable convert_to_proxy_string_host_allowed_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = host_allowed_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_network_operations(Object o) + internal static Dictionary ToDictionary_string_network_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -289,32 +173,9 @@ internal static Dictionary convert_from_proxy_string return result; } - internal static Hashtable convert_to_proxy_string_network_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = network_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_pool_allowed_operations(Object o) + internal static Dictionary ToDictionary_string_pool_allowed_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -335,32 +196,9 @@ internal static Dictionary convert_from_proxy_s return result; } - internal static Hashtable convert_to_proxy_string_pool_allowed_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = pool_allowed_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_storage_operations(Object o) + internal static Dictionary ToDictionary_string_storage_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -381,32 +219,9 @@ internal static Dictionary convert_from_proxy_string return result; } - internal static Hashtable convert_to_proxy_string_storage_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = storage_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_task_allowed_operations(Object o) + internal static Dictionary ToDictionary_string_task_allowed_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -427,32 +242,9 @@ internal static Dictionary convert_from_proxy_s return result; } - internal static Hashtable convert_to_proxy_string_task_allowed_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = task_allowed_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vbd_operations(Object o) + internal static Dictionary ToDictionary_string_vbd_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -473,32 +265,9 @@ internal static Dictionary convert_from_proxy_string_vbd return result; } - internal static Hashtable convert_to_proxy_string_vbd_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vbd_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vdi_operations(Object o) + internal static Dictionary ToDictionary_string_vdi_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -519,32 +288,9 @@ internal static Dictionary convert_from_proxy_string_vdi return result; } - internal static Hashtable convert_to_proxy_string_vdi_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vdi_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vif_operations(Object o) + internal static Dictionary ToDictionary_string_vif_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -565,32 +311,9 @@ internal static Dictionary convert_from_proxy_string_vif return result; } - internal static Hashtable convert_to_proxy_string_vif_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vif_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vm_appliance_operation(Object o) + internal static Dictionary ToDictionary_string_vm_appliance_operation(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -611,32 +334,9 @@ internal static Dictionary convert_from_proxy_st return result; } - internal static Hashtable convert_to_proxy_string_vm_appliance_operation(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vm_appliance_operation_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vm_operations(Object o) + internal static Dictionary ToDictionary_string_vm_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -657,32 +357,9 @@ internal static Dictionary convert_from_proxy_string_vm_o return result; } - internal static Hashtable convert_to_proxy_string_vm_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vm_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vtpm_operations(Object o) + internal static Dictionary ToDictionary_string_vtpm_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -703,32 +380,9 @@ internal static Dictionary convert_from_proxy_string_vt return result; } - internal static Hashtable convert_to_proxy_string_vtpm_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vtpm_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_string_vusb_operations(Object o) + internal static Dictionary ToDictionary_string_vusb_operations(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -749,32 +403,9 @@ internal static Dictionary convert_from_proxy_string_vu return result; } - internal static Hashtable convert_to_proxy_string_vusb_operations(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = vusb_operations_helper.ToString(table[key]); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary> convert_from_proxy_string_XenRefBlob(Object o) + internal static Dictionary> ToDictionary_string_XenRefBlob(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary> result = new Dictionary>(); if (table != null) { @@ -795,32 +426,9 @@ internal static Dictionary> convert_from_proxy_string_XenRe return result; } - internal static Hashtable convert_to_proxy_string_XenRefBlob(Dictionary> table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (string key in table.Keys) - { - try - { - string k = key ?? ""; - string v = table[key] ?? ""; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_long_long(Object o) + internal static Dictionary ToDictionary_long_long(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -841,32 +449,9 @@ internal static Dictionary convert_from_proxy_long_long(Object o) return result; } - internal static Hashtable convert_to_proxy_long_long(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (long key in table.Keys) - { - try - { - string k = key.ToString(); - string v = table[key].ToString(); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_long_double(Object o) + internal static Dictionary ToDictionary_long_double(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -887,32 +472,9 @@ internal static Dictionary convert_from_proxy_long_double(Object o return result; } - internal static Hashtable convert_to_proxy_long_double(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (long key in table.Keys) - { - try - { - string k = key.ToString(); - double v = table[key]; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_long_string_array(Object o) + internal static Dictionary ToDictionary_long_string_array(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -933,32 +495,9 @@ internal static Dictionary convert_from_proxy_long_string_array( return result; } - internal static Hashtable convert_to_proxy_long_string_array(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (long key in table.Keys) - { - try - { - string k = key.ToString(); - string[] v = table[key]; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary convert_from_proxy_vm_operations_string(Object o) + internal static Dictionary ToDictionary_vm_operations_string(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary result = new Dictionary(); if (table != null) { @@ -979,32 +518,9 @@ internal static Dictionary convert_from_proxy_vm_operatio return result; } - internal static Hashtable convert_to_proxy_vm_operations_string(Dictionary table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (vm_operations key in table.Keys) - { - try - { - string k = vm_operations_helper.ToString(key); - string v = table[key] ?? ""; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary, long> convert_from_proxy_XenRefVGPU_type_long(Object o) + internal static Dictionary, long> ToDictionary_XenRefVGPU_type_long(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary, long> result = new Dictionary, long>(); if (table != null) { @@ -1025,32 +541,9 @@ internal static Dictionary, long> convert_from_proxy_XenRefVGP return result; } - internal static Hashtable convert_to_proxy_XenRefVGPU_type_long(Dictionary, long> table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (XenRef key in table.Keys) - { - try - { - string k = key ?? ""; - string v = table[key].ToString(); - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - - internal static Dictionary, string> convert_from_proxy_XenRefVIF_string(Object o) + internal static Dictionary, string> ToDictionary_XenRefVIF_string(Hashtable table) { - Hashtable table = (Hashtable)o; Dictionary, string> result = new Dictionary, string>(); if (table != null) { @@ -1071,28 +564,6 @@ internal static Dictionary, string> convert_from_proxy_XenRefVIF_str return result; } - internal static Hashtable convert_to_proxy_XenRefVIF_string(Dictionary, string> table) - { - var result = new Hashtable(); - if (table != null) - { - foreach (XenRef key in table.Keys) - { - try - { - string k = key ?? ""; - string v = table[key] ?? ""; - result[k] = v; - } - catch - { - // continue - } - } - } - return result; - } - } } diff --git a/XenModel/XenAPI/Marshalling.cs b/XenModel/XenAPI/Marshalling.cs index ecb5cd3633..abb680ab1a 100644 --- a/XenModel/XenAPI/Marshalling.cs +++ b/XenModel/XenAPI/Marshalling.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Collections; +using System.Globalization; using System.Linq; @@ -37,6 +38,14 @@ namespace XenAPI { public class Marshalling { + private static readonly string[] DateFormats = + { + "yyyyMMddTHH:mm:ssZ", //iso8601 + "yyyy-MM-ddTHH:mm:ssZ", //iso8601 + "yyyy-MM-dd", //non-iso + "yyyy.MMdd", //non-iso + }; + /// /// Takes a Hashtable, creates a new t, and populates the fields of /// that t with the values from the Hashtable. @@ -56,31 +65,28 @@ public static Type GetXenAPIType(string name) public static bool ParseBool(Hashtable table, string key) { - bool.TryParse((string)table[key], out var result); - return result; + var val = table[key]; + return val is bool boolVal ? boolVal : bool.Parse((string)val); } public static DateTime ParseDateTime(Hashtable table, string key) { - DateTime.TryParse((string)table[key], out var result); - return result; + var val = table[key]; + return val is DateTime dateTimeVal + ? dateTimeVal + : DateTime.ParseExact((string)val, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } public static double ParseDouble(Hashtable table, string key) { - double.TryParse((string)table[key], out var result); - return result; - } - - public static Hashtable ParseHashTable(Hashtable table, string key) - { - return ParseSxpDict((string)table[key]); + var val = table[key]; + return val is double doubleVal ? doubleVal : double.Parse((string)val); } public static long ParseLong(Hashtable table, string key) { - long.TryParse((string)table[key], out var result); - return result; + var val = table[key]; + return val is long longVal ? longVal : long.Parse((string)val); } public static string ParseString(Hashtable table, string key) @@ -90,25 +96,36 @@ public static string ParseString(Hashtable table, string key) public static string[] ParseStringArray(Hashtable table, string key) { - return ParseSxpList((string)table[key]).ToArray(); + var val = table[key]; + return val is object[] array ? array.Cast().ToArray() : ParseSxpList((string)val).ToArray(); } public static long[] ParseLongArray(Hashtable table, string key) { - return ParseSxpList((string)table[key]).Select(long.Parse).ToArray(); + var val = table[key]; + return val is object[] array + ? array.Cast().ToArray() + : ParseSxpList((string)table[key]).Select(long.Parse).ToArray(); } public static XenRef ParseRef(Hashtable table, string key) where T : XenObject { - var val = (string)table[key]; - return val == null ? null : XenRef.Create(val); + return table[key] is string val ? XenRef.Create(val) : null; } public static List> ParseSetRef(Hashtable table, string key) where T : XenObject { - return ParseSxpList((string)table[key]).Select(XenRef.Create).ToList(); + var val = table[key]; + return val is object[] array + ? array.Cast>().ToList() + : ParseSxpList((string)val).Select(XenRef.Create).ToList(); } + public static Hashtable ParseHashTable(Hashtable table, string key) + { + var val = table[key]; + return val as Hashtable ?? ParseSxpDict((string)table[key]); + } private static Hashtable ParseSxpDict(string p) { @@ -162,27 +179,28 @@ private static IEnumerable Tokenize(string str) switch (str[i]) { case '(': - if (!inStr) - yield return "("; - break; + if (!inStr) + yield return "("; + break; case ')': - if (!inStr) - yield return ")"; - break; + if (!inStr) + yield return ")"; + break; case '\'': case '"': - if (!inStr) - { - inStr = true; - j = i; - } - else if (str[i - 1] != '\\') - { - inStr = false; - yield return str.Substring(j + 1, i - j - 1).Replace("\\\"", "\"").Replace("\\\'", "\'"); - } - break; + if (!inStr) + { + inStr = true; + j = i; + } + else if (str[i - 1] != '\\') + { + inStr = false; + yield return str.Substring(j + 1, i - j - 1).Replace("\\\"", "\"").Replace("\\\'", "\'"); + } + + break; } } } diff --git a/XenModel/XenAPI/Message.cs b/XenModel/XenAPI/Message.cs index a9e5168c30..ef6b89bb5c 100644 --- a/XenModel/XenAPI/Message.cs +++ b/XenModel/XenAPI/Message.cs @@ -128,13 +128,13 @@ public bool DeepEquals(Message other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name, other._name) && - Helper.AreEqual2(this._priority, other._priority) && - Helper.AreEqual2(this._cls, other._cls) && - Helper.AreEqual2(this._obj_uuid, other._obj_uuid) && - Helper.AreEqual2(this._timestamp, other._timestamp) && - Helper.AreEqual2(this._body, other._body); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name, other._name) && + Helper.AreEqual2(_priority, other._priority) && + Helper.AreEqual2(_cls, other._cls) && + Helper.AreEqual2(_obj_uuid, other._obj_uuid) && + Helper.AreEqual2(_timestamp, other._timestamp) && + Helper.AreEqual2(_body, other._body); } public override string SaveChanges(Session session, string opaqueRef, Message server) diff --git a/XenModel/XenAPI/Message2.cs b/XenModel/XenAPI/Message2.cs index ad9beeb867..c3a5eaa2d2 100644 --- a/XenModel/XenAPI/Message2.cs +++ b/XenModel/XenAPI/Message2.cs @@ -34,11 +34,15 @@ public partial class Message : XenObject { public enum MessageType { - PERIODIC_UPDATE_SYNC_FAILED, UPDATES_FEATURE_EXPIRED, UPDATES_FEATURE_EXPIRING_WARNING, UPDATES_FEATURE_EXPIRING_MAJOR, UPDATES_FEATURE_EXPIRING_CRITICAL, + LEAF_COALESCE_START_MESSAGE, + LEAF_COALESCE_COMPLETED, + LEAF_COALESCE_FAILED, + POST_ATTACH_SCAN_FAILED, + PERIODIC_UPDATE_SYNC_FAILED, TLS_VERIFICATION_EMERGENCY_DISABLED, FAILED_LOGIN_ATTEMPTS, HOST_INTERNAL_CERTIFICATE_EXPIRING_07, @@ -136,9 +140,6 @@ public enum MessageType HA_STATEFILE_APPROACHING_TIMEOUT, HA_HEARTBEAT_APPROACHING_TIMEOUT, HA_STATEFILE_LOST, - LEAF_COALESCE_START_MESSAGE, - LEAF_COALESCE_COMPLETED, - LEAF_COALESCE_FAILED, unknown } @@ -148,8 +149,6 @@ public MessageType Type { switch (this.name) { - case "PERIODIC_UPDATE_SYNC_FAILED": - return MessageType.PERIODIC_UPDATE_SYNC_FAILED; case "UPDATES_FEATURE_EXPIRED": return MessageType.UPDATES_FEATURE_EXPIRED; case "UPDATES_FEATURE_EXPIRING_WARNING": @@ -158,6 +157,16 @@ public MessageType Type return MessageType.UPDATES_FEATURE_EXPIRING_MAJOR; case "UPDATES_FEATURE_EXPIRING_CRITICAL": return MessageType.UPDATES_FEATURE_EXPIRING_CRITICAL; + case "LEAF_COALESCE_START_MESSAGE": + return MessageType.LEAF_COALESCE_START_MESSAGE; + case "LEAF_COALESCE_COMPLETED": + return MessageType.LEAF_COALESCE_COMPLETED; + case "LEAF_COALESCE_FAILED": + return MessageType.LEAF_COALESCE_FAILED; + case "POST_ATTACH_SCAN_FAILED": + return MessageType.POST_ATTACH_SCAN_FAILED; + case "PERIODIC_UPDATE_SYNC_FAILED": + return MessageType.PERIODIC_UPDATE_SYNC_FAILED; case "TLS_VERIFICATION_EMERGENCY_DISABLED": return MessageType.TLS_VERIFICATION_EMERGENCY_DISABLED; case "FAILED_LOGIN_ATTEMPTS": @@ -352,12 +361,6 @@ public MessageType Type return MessageType.HA_HEARTBEAT_APPROACHING_TIMEOUT; case "HA_STATEFILE_LOST": return MessageType.HA_STATEFILE_LOST; - case "LEAF_COALESCE_START_MESSAGE": - return MessageType.LEAF_COALESCE_START_MESSAGE; - case "LEAF_COALESCE_COMPLETED": - return MessageType.LEAF_COALESCE_COMPLETED; - case "LEAF_COALESCE_FAILED": - return MessageType.LEAF_COALESCE_FAILED; default: return MessageType.unknown; } diff --git a/XenModel/XenAPI/Network.cs b/XenModel/XenAPI/Network.cs index b931af2fb5..ca08cb1770 100644 --- a/XenModel/XenAPI/Network.cs +++ b/XenModel/XenAPI/Network.cs @@ -141,7 +141,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_network_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VIFs")) VIFs = Marshalling.ParseSetRef(table, "VIFs"); if (table.ContainsKey("PIFs")) @@ -149,19 +149,19 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("MTU")) MTU = Marshalling.ParseLong(table, "MTU"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("bridge")) bridge = Marshalling.ParseString(table, "bridge"); if (table.ContainsKey("managed")) managed = Marshalling.ParseBool(table, "managed"); if (table.ContainsKey("blobs")) - blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); + blobs = Maps.ToDictionary_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("default_locking_mode")) default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode")); if (table.ContainsKey("assigned_ips")) - assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips")); + assigned_ips = Maps.ToDictionary_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips")); if (table.ContainsKey("purpose")) purpose = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "purpose")); } @@ -173,24 +173,24 @@ public bool DeepEquals(Network other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VIFs, other._VIFs) && - Helper.AreEqual2(this._PIFs, other._PIFs) && - Helper.AreEqual2(this._MTU, other._MTU) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._bridge, other._bridge) && - Helper.AreEqual2(this._managed, other._managed) && - Helper.AreEqual2(this._blobs, other._blobs) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) && - Helper.AreEqual2(this._assigned_ips, other._assigned_ips) && - Helper.AreEqual2(this._purpose, other._purpose); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VIFs, other._VIFs) && + Helper.AreEqual2(_PIFs, other._PIFs) && + Helper.AreEqual2(_MTU, other._MTU) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_bridge, other._bridge) && + Helper.AreEqual2(_managed, other._managed) && + Helper.AreEqual2(_blobs, other._blobs) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_default_locking_mode, other._default_locking_mode) && + Helper.AreEqual2(_assigned_ips, other._assigned_ips) && + Helper.AreEqual2(_purpose, other._purpose); } public override string SaveChanges(Session session, string opaqueRef, Network server) diff --git a/XenModel/XenAPI/Network_sriov.cs b/XenModel/XenAPI/Network_sriov.cs index 5b21675275..046f2d83df 100755 --- a/XenModel/XenAPI/Network_sriov.cs +++ b/XenModel/XenAPI/Network_sriov.cs @@ -118,11 +118,11 @@ public bool DeepEquals(Network_sriov other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._physical_PIF, other._physical_PIF) && - Helper.AreEqual2(this._logical_PIF, other._logical_PIF) && - Helper.AreEqual2(this._requires_reboot, other._requires_reboot) && - Helper.AreEqual2(this._configuration_mode, other._configuration_mode); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_physical_PIF, other._physical_PIF) && + Helper.AreEqual2(_logical_PIF, other._logical_PIF) && + Helper.AreEqual2(_requires_reboot, other._requires_reboot) && + Helper.AreEqual2(_configuration_mode, other._configuration_mode); } public override string SaveChanges(Session session, string opaqueRef, Network_sriov server) diff --git a/XenModel/XenAPI/Observer.cs b/XenModel/XenAPI/Observer.cs index 4880378f10..51495acc80 100644 --- a/XenModel/XenAPI/Observer.cs +++ b/XenModel/XenAPI/Observer.cs @@ -117,7 +117,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("hosts")) hosts = Marshalling.ParseSetRef(table, "hosts"); if (table.ContainsKey("attributes")) - attributes = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "attributes")); + attributes = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "attributes")); if (table.ContainsKey("endpoints")) endpoints = Marshalling.ParseStringArray(table, "endpoints"); if (table.ContainsKey("components")) @@ -133,14 +133,14 @@ public bool DeepEquals(Observer other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._hosts, other._hosts) && - Helper.AreEqual2(this._attributes, other._attributes) && - Helper.AreEqual2(this._endpoints, other._endpoints) && - Helper.AreEqual2(this._components, other._components) && - Helper.AreEqual2(this._enabled, other._enabled); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_hosts, other._hosts) && + Helper.AreEqual2(_attributes, other._attributes) && + Helper.AreEqual2(_endpoints, other._endpoints) && + Helper.AreEqual2(_components, other._components) && + Helper.AreEqual2(_enabled, other._enabled); } public override string SaveChanges(Session session, string opaqueRef, Observer server) diff --git a/XenModel/XenAPI/PBD.cs b/XenModel/XenAPI/PBD.cs index a9305bab53..47315fadfb 100644 --- a/XenModel/XenAPI/PBD.cs +++ b/XenModel/XenAPI/PBD.cs @@ -109,11 +109,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("SR")) SR = Marshalling.ParseRef(table, "SR"); if (table.ContainsKey("device_config")) - device_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "device_config")); + device_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "device_config")); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PBD other) @@ -123,12 +123,12 @@ public bool DeepEquals(PBD other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._SR, other._SR) && - Helper.AreEqual2(this._device_config, other._device_config) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_SR, other._SR) && + Helper.AreEqual2(_device_config, other._device_config) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, PBD server) diff --git a/XenModel/XenAPI/PCI.cs b/XenModel/XenAPI/PCI.cs index 938f49783d..dad0f62eb4 100755 --- a/XenModel/XenAPI/PCI.cs +++ b/XenModel/XenAPI/PCI.cs @@ -132,7 +132,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("dependencies")) dependencies = Marshalling.ParseSetRef(table, "dependencies"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("subsystem_vendor_name")) subsystem_vendor_name = Marshalling.ParseString(table, "subsystem_vendor_name"); if (table.ContainsKey("subsystem_device_name")) @@ -148,17 +148,17 @@ public bool DeepEquals(PCI other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._class_name, other._class_name) && - Helper.AreEqual2(this._vendor_name, other._vendor_name) && - Helper.AreEqual2(this._device_name, other._device_name) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._pci_id, other._pci_id) && - Helper.AreEqual2(this._dependencies, other._dependencies) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._subsystem_vendor_name, other._subsystem_vendor_name) && - Helper.AreEqual2(this._subsystem_device_name, other._subsystem_device_name) && - Helper.AreEqual2(this._driver_name, other._driver_name); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_class_name, other._class_name) && + Helper.AreEqual2(_vendor_name, other._vendor_name) && + Helper.AreEqual2(_device_name, other._device_name) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_pci_id, other._pci_id) && + Helper.AreEqual2(_dependencies, other._dependencies) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_subsystem_vendor_name, other._subsystem_vendor_name) && + Helper.AreEqual2(_subsystem_device_name, other._subsystem_device_name) && + Helper.AreEqual2(_driver_name, other._driver_name); } public override string SaveChanges(Session session, string opaqueRef, PCI server) diff --git a/XenModel/XenAPI/PGPU.cs b/XenModel/XenAPI/PGPU.cs index 7aa7cf249d..c54d3cd6e6 100644 --- a/XenModel/XenAPI/PGPU.cs +++ b/XenModel/XenAPI/PGPU.cs @@ -129,7 +129,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("host")) host = Marshalling.ParseRef(table, "host"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("supported_VGPU_types")) supported_VGPU_types = Marshalling.ParseSetRef(table, "supported_VGPU_types"); if (table.ContainsKey("enabled_VGPU_types")) @@ -137,13 +137,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("resident_VGPUs")) resident_VGPUs = Marshalling.ParseSetRef(table, "resident_VGPUs"); if (table.ContainsKey("supported_VGPU_max_capacities")) - supported_VGPU_max_capacities = Maps.convert_from_proxy_XenRefVGPU_type_long(Marshalling.ParseHashTable(table, "supported_VGPU_max_capacities")); + supported_VGPU_max_capacities = Maps.ToDictionary_XenRefVGPU_type_long(Marshalling.ParseHashTable(table, "supported_VGPU_max_capacities")); if (table.ContainsKey("dom0_access")) dom0_access = (pgpu_dom0_access)Helper.EnumParseDefault(typeof(pgpu_dom0_access), Marshalling.ParseString(table, "dom0_access")); if (table.ContainsKey("is_system_display_device")) is_system_display_device = Marshalling.ParseBool(table, "is_system_display_device"); if (table.ContainsKey("compatibility_metadata")) - compatibility_metadata = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "compatibility_metadata")); + compatibility_metadata = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "compatibility_metadata")); } public bool DeepEquals(PGPU other) @@ -153,18 +153,18 @@ public bool DeepEquals(PGPU other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._PCI, other._PCI) && - Helper.AreEqual2(this._GPU_group, other._GPU_group) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._supported_VGPU_types, other._supported_VGPU_types) && - Helper.AreEqual2(this._enabled_VGPU_types, other._enabled_VGPU_types) && - Helper.AreEqual2(this._resident_VGPUs, other._resident_VGPUs) && - Helper.AreEqual2(this._supported_VGPU_max_capacities, other._supported_VGPU_max_capacities) && - Helper.AreEqual2(this._dom0_access, other._dom0_access) && - Helper.AreEqual2(this._is_system_display_device, other._is_system_display_device) && - Helper.AreEqual2(this._compatibility_metadata, other._compatibility_metadata); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_PCI, other._PCI) && + Helper.AreEqual2(_GPU_group, other._GPU_group) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_supported_VGPU_types, other._supported_VGPU_types) && + Helper.AreEqual2(_enabled_VGPU_types, other._enabled_VGPU_types) && + Helper.AreEqual2(_resident_VGPUs, other._resident_VGPUs) && + Helper.AreEqual2(_supported_VGPU_max_capacities, other._supported_VGPU_max_capacities) && + Helper.AreEqual2(_dom0_access, other._dom0_access) && + Helper.AreEqual2(_is_system_display_device, other._is_system_display_device) && + Helper.AreEqual2(_compatibility_metadata, other._compatibility_metadata); } public override string SaveChanges(Session session, string opaqueRef, PGPU server) diff --git a/XenModel/XenAPI/PIF.cs b/XenModel/XenAPI/PIF.cs index e93aefba51..28da7140ac 100755 --- a/XenModel/XenAPI/PIF.cs +++ b/XenModel/XenAPI/PIF.cs @@ -230,7 +230,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("management")) management = Marshalling.ParseBool(table, "management"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("disallow_unplug")) disallow_unplug = Marshalling.ParseBool(table, "disallow_unplug"); if (table.ContainsKey("tunnel_access_PIF_of")) @@ -248,7 +248,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("managed")) managed = Marshalling.ParseBool(table, "managed"); if (table.ContainsKey("properties")) - properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "properties")); + properties = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "properties")); if (table.ContainsKey("capabilities")) capabilities = Marshalling.ParseStringArray(table, "capabilities"); if (table.ContainsKey("igmp_snooping_status")) @@ -268,41 +268,41 @@ public bool DeepEquals(PIF other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._device, other._device) && - Helper.AreEqual2(this._network, other._network) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._MAC, other._MAC) && - Helper.AreEqual2(this._MTU, other._MTU) && - Helper.AreEqual2(this._VLAN, other._VLAN) && - Helper.AreEqual2(this._metrics, other._metrics) && - Helper.AreEqual2(this._physical, other._physical) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._ip_configuration_mode, other._ip_configuration_mode) && - Helper.AreEqual2(this._IP, other._IP) && - Helper.AreEqual2(this._netmask, other._netmask) && - Helper.AreEqual2(this._gateway, other._gateway) && - Helper.AreEqual2(this._DNS, other._DNS) && - Helper.AreEqual2(this._bond_slave_of, other._bond_slave_of) && - Helper.AreEqual2(this._bond_master_of, other._bond_master_of) && - Helper.AreEqual2(this._VLAN_master_of, other._VLAN_master_of) && - Helper.AreEqual2(this._VLAN_slave_of, other._VLAN_slave_of) && - Helper.AreEqual2(this._management, other._management) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._disallow_unplug, other._disallow_unplug) && - Helper.AreEqual2(this._tunnel_access_PIF_of, other._tunnel_access_PIF_of) && - Helper.AreEqual2(this._tunnel_transport_PIF_of, other._tunnel_transport_PIF_of) && - Helper.AreEqual2(this._ipv6_configuration_mode, other._ipv6_configuration_mode) && - Helper.AreEqual2(this._IPv6, other._IPv6) && - Helper.AreEqual2(this._ipv6_gateway, other._ipv6_gateway) && - Helper.AreEqual2(this._primary_address_type, other._primary_address_type) && - Helper.AreEqual2(this._managed, other._managed) && - Helper.AreEqual2(this._properties, other._properties) && - Helper.AreEqual2(this._capabilities, other._capabilities) && - Helper.AreEqual2(this._igmp_snooping_status, other._igmp_snooping_status) && - Helper.AreEqual2(this._sriov_physical_PIF_of, other._sriov_physical_PIF_of) && - Helper.AreEqual2(this._sriov_logical_PIF_of, other._sriov_logical_PIF_of) && - Helper.AreEqual2(this._PCI, other._PCI); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_device, other._device) && + Helper.AreEqual2(_network, other._network) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_MAC, other._MAC) && + Helper.AreEqual2(_MTU, other._MTU) && + Helper.AreEqual2(_VLAN, other._VLAN) && + Helper.AreEqual2(_metrics, other._metrics) && + Helper.AreEqual2(_physical, other._physical) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_ip_configuration_mode, other._ip_configuration_mode) && + Helper.AreEqual2(_IP, other._IP) && + Helper.AreEqual2(_netmask, other._netmask) && + Helper.AreEqual2(_gateway, other._gateway) && + Helper.AreEqual2(_DNS, other._DNS) && + Helper.AreEqual2(_bond_slave_of, other._bond_slave_of) && + Helper.AreEqual2(_bond_master_of, other._bond_master_of) && + Helper.AreEqual2(_VLAN_master_of, other._VLAN_master_of) && + Helper.AreEqual2(_VLAN_slave_of, other._VLAN_slave_of) && + Helper.AreEqual2(_management, other._management) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_disallow_unplug, other._disallow_unplug) && + Helper.AreEqual2(_tunnel_access_PIF_of, other._tunnel_access_PIF_of) && + Helper.AreEqual2(_tunnel_transport_PIF_of, other._tunnel_transport_PIF_of) && + Helper.AreEqual2(_ipv6_configuration_mode, other._ipv6_configuration_mode) && + Helper.AreEqual2(_IPv6, other._IPv6) && + Helper.AreEqual2(_ipv6_gateway, other._ipv6_gateway) && + Helper.AreEqual2(_primary_address_type, other._primary_address_type) && + Helper.AreEqual2(_managed, other._managed) && + Helper.AreEqual2(_properties, other._properties) && + Helper.AreEqual2(_capabilities, other._capabilities) && + Helper.AreEqual2(_igmp_snooping_status, other._igmp_snooping_status) && + Helper.AreEqual2(_sriov_physical_PIF_of, other._sriov_physical_PIF_of) && + Helper.AreEqual2(_sriov_logical_PIF_of, other._sriov_logical_PIF_of) && + Helper.AreEqual2(_PCI, other._PCI); } public override string SaveChanges(Session session, string opaqueRef, PIF server) diff --git a/XenModel/XenAPI/PIF_metrics.cs b/XenModel/XenAPI/PIF_metrics.cs index 45d3923fd2..0ce6c624db 100644 --- a/XenModel/XenAPI/PIF_metrics.cs +++ b/XenModel/XenAPI/PIF_metrics.cs @@ -148,7 +148,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PIF_metrics other) @@ -158,19 +158,19 @@ public bool DeepEquals(PIF_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && - Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && - Helper.AreEqual2(this._carrier, other._carrier) && - Helper.AreEqual2(this._vendor_id, other._vendor_id) && - Helper.AreEqual2(this._vendor_name, other._vendor_name) && - Helper.AreEqual2(this._device_id, other._device_id) && - Helper.AreEqual2(this._device_name, other._device_name) && - Helper.AreEqual2(this._speed, other._speed) && - Helper.AreEqual2(this._duplex, other._duplex) && - Helper.AreEqual2(this._pci_bus_path, other._pci_bus_path) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_io_read_kbs, other._io_read_kbs) && + Helper.AreEqual2(_io_write_kbs, other._io_write_kbs) && + Helper.AreEqual2(_carrier, other._carrier) && + Helper.AreEqual2(_vendor_id, other._vendor_id) && + Helper.AreEqual2(_vendor_name, other._vendor_name) && + Helper.AreEqual2(_device_id, other._device_id) && + Helper.AreEqual2(_device_name, other._device_name) && + Helper.AreEqual2(_speed, other._speed) && + Helper.AreEqual2(_duplex, other._duplex) && + Helper.AreEqual2(_pci_bus_path, other._pci_bus_path) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, PIF_metrics server) diff --git a/XenModel/XenAPI/PUSB.cs b/XenModel/XenAPI/PUSB.cs index be05ee3a71..d5e5f9cfad 100644 --- a/XenModel/XenAPI/PUSB.cs +++ b/XenModel/XenAPI/PUSB.cs @@ -151,7 +151,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("passthrough_enabled")) passthrough_enabled = Marshalling.ParseBool(table, "passthrough_enabled"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("speed")) speed = Marshalling.ParseDouble(table, "speed"); } @@ -163,20 +163,20 @@ public bool DeepEquals(PUSB other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._USB_group, other._USB_group) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._path, other._path) && - Helper.AreEqual2(this._vendor_id, other._vendor_id) && - Helper.AreEqual2(this._vendor_desc, other._vendor_desc) && - Helper.AreEqual2(this._product_id, other._product_id) && - Helper.AreEqual2(this._product_desc, other._product_desc) && - Helper.AreEqual2(this._serial, other._serial) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._description, other._description) && - Helper.AreEqual2(this._passthrough_enabled, other._passthrough_enabled) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._speed, other._speed); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_USB_group, other._USB_group) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_path, other._path) && + Helper.AreEqual2(_vendor_id, other._vendor_id) && + Helper.AreEqual2(_vendor_desc, other._vendor_desc) && + Helper.AreEqual2(_product_id, other._product_id) && + Helper.AreEqual2(_product_desc, other._product_desc) && + Helper.AreEqual2(_serial, other._serial) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_description, other._description) && + Helper.AreEqual2(_passthrough_enabled, other._passthrough_enabled) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_speed, other._speed); } public override string SaveChanges(Session session, string opaqueRef, PUSB server) diff --git a/XenModel/XenAPI/PVS_cache_storage.cs b/XenModel/XenAPI/PVS_cache_storage.cs index d22036e176..e24425ca8b 100644 --- a/XenModel/XenAPI/PVS_cache_storage.cs +++ b/XenModel/XenAPI/PVS_cache_storage.cs @@ -123,12 +123,12 @@ public bool DeepEquals(PVS_cache_storage other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._host, other._host) && - Helper.AreEqual2(this._SR, other._SR) && - Helper.AreEqual2(this._site, other._site) && - Helper.AreEqual2(this._size, other._size) && - Helper.AreEqual2(this._VDI, other._VDI); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_host, other._host) && + Helper.AreEqual2(_SR, other._SR) && + Helper.AreEqual2(_site, other._site) && + Helper.AreEqual2(_size, other._size) && + Helper.AreEqual2(_VDI, other._VDI); } public override string SaveChanges(Session session, string opaqueRef, PVS_cache_storage server) diff --git a/XenModel/XenAPI/PVS_proxy.cs b/XenModel/XenAPI/PVS_proxy.cs index ae0d181364..3205c3351c 100644 --- a/XenModel/XenAPI/PVS_proxy.cs +++ b/XenModel/XenAPI/PVS_proxy.cs @@ -118,11 +118,11 @@ public bool DeepEquals(PVS_proxy other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._site, other._site) && - Helper.AreEqual2(this._VIF, other._VIF) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._status, other._status); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_site, other._site) && + Helper.AreEqual2(_VIF, other._VIF) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_status, other._status); } public override string SaveChanges(Session session, string opaqueRef, PVS_proxy server) diff --git a/XenModel/XenAPI/PVS_server.cs b/XenModel/XenAPI/PVS_server.cs index ac27721fdd..7fcebd2c45 100644 --- a/XenModel/XenAPI/PVS_server.cs +++ b/XenModel/XenAPI/PVS_server.cs @@ -118,11 +118,11 @@ public bool DeepEquals(PVS_server other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._addresses, other._addresses) && - Helper.AreEqual2(this._first_port, other._first_port) && - Helper.AreEqual2(this._last_port, other._last_port) && - Helper.AreEqual2(this._site, other._site); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_addresses, other._addresses) && + Helper.AreEqual2(_first_port, other._first_port) && + Helper.AreEqual2(_last_port, other._last_port) && + Helper.AreEqual2(_site, other._site); } public override string SaveChanges(Session session, string opaqueRef, PVS_server server) diff --git a/XenModel/XenAPI/PVS_site.cs b/XenModel/XenAPI/PVS_site.cs index eb91632b41..300abe4911 100644 --- a/XenModel/XenAPI/PVS_site.cs +++ b/XenModel/XenAPI/PVS_site.cs @@ -128,13 +128,13 @@ public bool DeepEquals(PVS_site other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._PVS_uuid, other._PVS_uuid) && - Helper.AreEqual2(this._cache_storage, other._cache_storage) && - Helper.AreEqual2(this._servers, other._servers) && - Helper.AreEqual2(this._proxies, other._proxies); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_PVS_uuid, other._PVS_uuid) && + Helper.AreEqual2(_cache_storage, other._cache_storage) && + Helper.AreEqual2(_servers, other._servers) && + Helper.AreEqual2(_proxies, other._proxies); } public override string SaveChanges(Session session, string opaqueRef, PVS_site server) diff --git a/XenModel/XenAPI/Pool.cs b/XenModel/XenAPI/Pool.cs index 3aef1dd991..6534641b9a 100644 --- a/XenModel/XenAPI/Pool.cs +++ b/XenModel/XenAPI/Pool.cs @@ -261,11 +261,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("crash_dump_SR")) crash_dump_SR = Marshalling.ParseRef(table, "crash_dump_SR"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("ha_enabled")) ha_enabled = Marshalling.ParseBool(table, "ha_enabled"); if (table.ContainsKey("ha_configuration")) - ha_configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "ha_configuration")); + ha_configuration = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "ha_configuration")); if (table.ContainsKey("ha_statefiles")) ha_statefiles = Marshalling.ParseStringArray(table, "ha_statefiles"); if (table.ContainsKey("ha_host_failures_to_tolerate")) @@ -277,13 +277,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("ha_overcommitted")) ha_overcommitted = Marshalling.ParseBool(table, "ha_overcommitted"); if (table.ContainsKey("blobs")) - blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); + blobs = Maps.ToDictionary_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("gui_config")) - gui_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "gui_config")); + gui_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "gui_config")); if (table.ContainsKey("health_check_config")) - health_check_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "health_check_config")); + health_check_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "health_check_config")); if (table.ContainsKey("wlb_url")) wlb_url = Marshalling.ParseString(table, "wlb_url"); if (table.ContainsKey("wlb_username")) @@ -299,7 +299,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("vswitch_controller")) vswitch_controller = Marshalling.ParseString(table, "vswitch_controller"); if (table.ContainsKey("restrictions")) - restrictions = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "restrictions")); + restrictions = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "restrictions")); if (table.ContainsKey("metadata_VDIs")) metadata_VDIs = Marshalling.ParseSetRef(table, "metadata_VDIs"); if (table.ContainsKey("ha_cluster_stack")) @@ -307,11 +307,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_pool_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_pool_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("guest_agent_config")) - guest_agent_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "guest_agent_config")); + guest_agent_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "guest_agent_config")); if (table.ContainsKey("cpu_info")) - cpu_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cpu_info")); + cpu_info = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "cpu_info")); if (table.ContainsKey("policy_no_vendor_device")) policy_no_vendor_device = Marshalling.ParseBool(table, "policy_no_vendor_device"); if (table.ContainsKey("live_patching_disabled")) @@ -363,62 +363,62 @@ public bool DeepEquals(Pool other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._master, other._master) && - Helper.AreEqual2(this._default_SR, other._default_SR) && - Helper.AreEqual2(this._suspend_image_SR, other._suspend_image_SR) && - Helper.AreEqual2(this._crash_dump_SR, other._crash_dump_SR) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._ha_enabled, other._ha_enabled) && - Helper.AreEqual2(this._ha_configuration, other._ha_configuration) && - Helper.AreEqual2(this._ha_statefiles, other._ha_statefiles) && - Helper.AreEqual2(this._ha_host_failures_to_tolerate, other._ha_host_failures_to_tolerate) && - Helper.AreEqual2(this._ha_plan_exists_for, other._ha_plan_exists_for) && - Helper.AreEqual2(this._ha_allow_overcommit, other._ha_allow_overcommit) && - Helper.AreEqual2(this._ha_overcommitted, other._ha_overcommitted) && - Helper.AreEqual2(this._blobs, other._blobs) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._gui_config, other._gui_config) && - Helper.AreEqual2(this._health_check_config, other._health_check_config) && - Helper.AreEqual2(this._wlb_url, other._wlb_url) && - Helper.AreEqual2(this._wlb_username, other._wlb_username) && - Helper.AreEqual2(this._wlb_enabled, other._wlb_enabled) && - Helper.AreEqual2(this._wlb_verify_cert, other._wlb_verify_cert) && - Helper.AreEqual2(this._redo_log_enabled, other._redo_log_enabled) && - Helper.AreEqual2(this._redo_log_vdi, other._redo_log_vdi) && - Helper.AreEqual2(this._vswitch_controller, other._vswitch_controller) && - Helper.AreEqual2(this._restrictions, other._restrictions) && - Helper.AreEqual2(this._metadata_VDIs, other._metadata_VDIs) && - Helper.AreEqual2(this._ha_cluster_stack, other._ha_cluster_stack) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._guest_agent_config, other._guest_agent_config) && - Helper.AreEqual2(this._cpu_info, other._cpu_info) && - Helper.AreEqual2(this._policy_no_vendor_device, other._policy_no_vendor_device) && - Helper.AreEqual2(this._live_patching_disabled, other._live_patching_disabled) && - Helper.AreEqual2(this._igmp_snooping_enabled, other._igmp_snooping_enabled) && - Helper.AreEqual2(this._uefi_certificates, other._uefi_certificates) && - Helper.AreEqual2(this._is_psr_pending, other._is_psr_pending) && - Helper.AreEqual2(this._tls_verification_enabled, other._tls_verification_enabled) && - Helper.AreEqual2(this._repositories, other._repositories) && - Helper.AreEqual2(this._client_certificate_auth_enabled, other._client_certificate_auth_enabled) && - Helper.AreEqual2(this._client_certificate_auth_name, other._client_certificate_auth_name) && - Helper.AreEqual2(this._repository_proxy_url, other._repository_proxy_url) && - Helper.AreEqual2(this._repository_proxy_username, other._repository_proxy_username) && - Helper.AreEqual2(this._repository_proxy_password, other._repository_proxy_password) && - Helper.AreEqual2(this._migration_compression, other._migration_compression) && - Helper.AreEqual2(this._coordinator_bias, other._coordinator_bias) && - Helper.AreEqual2(this._telemetry_uuid, other._telemetry_uuid) && - Helper.AreEqual2(this._telemetry_frequency, other._telemetry_frequency) && - Helper.AreEqual2(this._telemetry_next_collection, other._telemetry_next_collection) && - Helper.AreEqual2(this._last_update_sync, other._last_update_sync) && - Helper.AreEqual2(this._update_sync_frequency, other._update_sync_frequency) && - Helper.AreEqual2(this._update_sync_day, other._update_sync_day) && - Helper.AreEqual2(this._update_sync_enabled, other._update_sync_enabled); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_master, other._master) && + Helper.AreEqual2(_default_SR, other._default_SR) && + Helper.AreEqual2(_suspend_image_SR, other._suspend_image_SR) && + Helper.AreEqual2(_crash_dump_SR, other._crash_dump_SR) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_ha_enabled, other._ha_enabled) && + Helper.AreEqual2(_ha_configuration, other._ha_configuration) && + Helper.AreEqual2(_ha_statefiles, other._ha_statefiles) && + Helper.AreEqual2(_ha_host_failures_to_tolerate, other._ha_host_failures_to_tolerate) && + Helper.AreEqual2(_ha_plan_exists_for, other._ha_plan_exists_for) && + Helper.AreEqual2(_ha_allow_overcommit, other._ha_allow_overcommit) && + Helper.AreEqual2(_ha_overcommitted, other._ha_overcommitted) && + Helper.AreEqual2(_blobs, other._blobs) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_gui_config, other._gui_config) && + Helper.AreEqual2(_health_check_config, other._health_check_config) && + Helper.AreEqual2(_wlb_url, other._wlb_url) && + Helper.AreEqual2(_wlb_username, other._wlb_username) && + Helper.AreEqual2(_wlb_enabled, other._wlb_enabled) && + Helper.AreEqual2(_wlb_verify_cert, other._wlb_verify_cert) && + Helper.AreEqual2(_redo_log_enabled, other._redo_log_enabled) && + Helper.AreEqual2(_redo_log_vdi, other._redo_log_vdi) && + Helper.AreEqual2(_vswitch_controller, other._vswitch_controller) && + Helper.AreEqual2(_restrictions, other._restrictions) && + Helper.AreEqual2(_metadata_VDIs, other._metadata_VDIs) && + Helper.AreEqual2(_ha_cluster_stack, other._ha_cluster_stack) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_guest_agent_config, other._guest_agent_config) && + Helper.AreEqual2(_cpu_info, other._cpu_info) && + Helper.AreEqual2(_policy_no_vendor_device, other._policy_no_vendor_device) && + Helper.AreEqual2(_live_patching_disabled, other._live_patching_disabled) && + Helper.AreEqual2(_igmp_snooping_enabled, other._igmp_snooping_enabled) && + Helper.AreEqual2(_uefi_certificates, other._uefi_certificates) && + Helper.AreEqual2(_is_psr_pending, other._is_psr_pending) && + Helper.AreEqual2(_tls_verification_enabled, other._tls_verification_enabled) && + Helper.AreEqual2(_repositories, other._repositories) && + Helper.AreEqual2(_client_certificate_auth_enabled, other._client_certificate_auth_enabled) && + Helper.AreEqual2(_client_certificate_auth_name, other._client_certificate_auth_name) && + Helper.AreEqual2(_repository_proxy_url, other._repository_proxy_url) && + Helper.AreEqual2(_repository_proxy_username, other._repository_proxy_username) && + Helper.AreEqual2(_repository_proxy_password, other._repository_proxy_password) && + Helper.AreEqual2(_migration_compression, other._migration_compression) && + Helper.AreEqual2(_coordinator_bias, other._coordinator_bias) && + Helper.AreEqual2(_telemetry_uuid, other._telemetry_uuid) && + Helper.AreEqual2(_telemetry_frequency, other._telemetry_frequency) && + Helper.AreEqual2(_telemetry_next_collection, other._telemetry_next_collection) && + Helper.AreEqual2(_last_update_sync, other._last_update_sync) && + Helper.AreEqual2(_update_sync_frequency, other._update_sync_frequency) && + Helper.AreEqual2(_update_sync_day, other._update_sync_day) && + Helper.AreEqual2(_update_sync_enabled, other._update_sync_enabled); } public override string SaveChanges(Session session, string opaqueRef, Pool server) diff --git a/XenModel/XenAPI/Pool_patch.cs b/XenModel/XenAPI/Pool_patch.cs index 4ab116a0ca..ab8e94596f 100644 --- a/XenModel/XenAPI/Pool_patch.cs +++ b/XenModel/XenAPI/Pool_patch.cs @@ -133,7 +133,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("pool_update")) pool_update = Marshalling.ParseRef(table, "pool_update"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Pool_patch other) @@ -143,16 +143,16 @@ public bool DeepEquals(Pool_patch other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._size, other._size) && - Helper.AreEqual2(this._pool_applied, other._pool_applied) && - Helper.AreEqual2(this._host_patches, other._host_patches) && - Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) && - Helper.AreEqual2(this._pool_update, other._pool_update) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_size, other._size) && + Helper.AreEqual2(_pool_applied, other._pool_applied) && + Helper.AreEqual2(_host_patches, other._host_patches) && + Helper.AreEqual2(_after_apply_guidance, other._after_apply_guidance) && + Helper.AreEqual2(_pool_update, other._pool_update) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Pool_patch server) diff --git a/XenModel/XenAPI/Pool_update.cs b/XenModel/XenAPI/Pool_update.cs index e19484c4c3..b5c94e1324 100644 --- a/XenModel/XenAPI/Pool_update.cs +++ b/XenModel/XenAPI/Pool_update.cs @@ -136,7 +136,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("hosts")) hosts = Marshalling.ParseSetRef(table, "hosts"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("enforce_homogeneity")) enforce_homogeneity = Marshalling.ParseBool(table, "enforce_homogeneity"); } @@ -148,17 +148,17 @@ public bool DeepEquals(Pool_update other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._installation_size, other._installation_size) && - Helper.AreEqual2(this._key, other._key) && - Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) && - Helper.AreEqual2(this._vdi, other._vdi) && - Helper.AreEqual2(this._hosts, other._hosts) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._enforce_homogeneity, other._enforce_homogeneity); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_installation_size, other._installation_size) && + Helper.AreEqual2(_key, other._key) && + Helper.AreEqual2(_after_apply_guidance, other._after_apply_guidance) && + Helper.AreEqual2(_vdi, other._vdi) && + Helper.AreEqual2(_hosts, other._hosts) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_enforce_homogeneity, other._enforce_homogeneity); } public override string SaveChanges(Session session, string opaqueRef, Pool_update server) diff --git a/XenModel/XenAPI/Probe_result.cs b/XenModel/XenAPI/Probe_result.cs index f310e49551..8f97daf6e5 100644 --- a/XenModel/XenAPI/Probe_result.cs +++ b/XenModel/XenAPI/Probe_result.cs @@ -97,13 +97,13 @@ public override void UpdateFrom(Probe_result record) public void UpdateFrom(Hashtable table) { if (table.ContainsKey("configuration")) - configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration")); + configuration = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "configuration")); if (table.ContainsKey("complete")) complete = Marshalling.ParseBool(table, "complete"); if (table.ContainsKey("sr")) sr = (Sr_stat)Marshalling.convertStruct(typeof(Sr_stat), Marshalling.ParseHashTable(table, "sr"));; if (table.ContainsKey("extra_info")) - extra_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "extra_info")); + extra_info = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "extra_info")); } public bool DeepEquals(Probe_result other) @@ -113,10 +113,10 @@ public bool DeepEquals(Probe_result other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._configuration, other._configuration) && - Helper.AreEqual2(this._complete, other._complete) && - Helper.AreEqual2(this._sr, other._sr) && - Helper.AreEqual2(this._extra_info, other._extra_info); + return Helper.AreEqual2(_configuration, other._configuration) && + Helper.AreEqual2(_complete, other._complete) && + Helper.AreEqual2(_sr, other._sr) && + Helper.AreEqual2(_extra_info, other._extra_info); } public override string SaveChanges(Session session, string opaqueRef, Probe_result server) diff --git a/XenModel/XenAPI/Repository.cs b/XenModel/XenAPI/Repository.cs index abfad96e3d..5fbc7a534e 100644 --- a/XenModel/XenAPI/Repository.cs +++ b/XenModel/XenAPI/Repository.cs @@ -138,15 +138,15 @@ public bool DeepEquals(Repository other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._binary_url, other._binary_url) && - Helper.AreEqual2(this._source_url, other._source_url) && - Helper.AreEqual2(this._update, other._update) && - Helper.AreEqual2(this._hash, other._hash) && - Helper.AreEqual2(this._up_to_date, other._up_to_date) && - Helper.AreEqual2(this._gpgkey_path, other._gpgkey_path); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_binary_url, other._binary_url) && + Helper.AreEqual2(_source_url, other._source_url) && + Helper.AreEqual2(_update, other._update) && + Helper.AreEqual2(_hash, other._hash) && + Helper.AreEqual2(_up_to_date, other._up_to_date) && + Helper.AreEqual2(_gpgkey_path, other._gpgkey_path); } public override string SaveChanges(Session session, string opaqueRef, Repository server) @@ -288,11 +288,11 @@ public static string get_hash(Session session, string _repository) /// /// Get the up_to_date field of the given Repository. /// First published in 1.301.0. - /// Deprecated since 23.12.0-next. + /// Deprecated since 23.18.0. /// /// The session /// The opaque_ref of the given repository - [Deprecated("23.12.0-next")] + [Deprecated("23.18.0")] public static bool get_up_to_date(Session session, string _repository) { return session.JsonRpcClient.repository_get_up_to_date(session.opaque_ref, _repository); diff --git a/XenModel/XenAPI/Role.cs b/XenModel/XenAPI/Role.cs index 820fe5effa..4b24bf7e85 100644 --- a/XenModel/XenAPI/Role.cs +++ b/XenModel/XenAPI/Role.cs @@ -118,11 +118,11 @@ public bool DeepEquals(Role other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._subroles, other._subroles) && - Helper.AreEqual2(this._is_internal, other._is_internal); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_subroles, other._subroles) && + Helper.AreEqual2(_is_internal, other._is_internal); } public override string SaveChanges(Session session, string opaqueRef, Role server) diff --git a/XenModel/XenAPI/SDN_controller.cs b/XenModel/XenAPI/SDN_controller.cs index 85f759f4ff..af70b131a9 100644 --- a/XenModel/XenAPI/SDN_controller.cs +++ b/XenModel/XenAPI/SDN_controller.cs @@ -113,10 +113,10 @@ public bool DeepEquals(SDN_controller other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._protocol, other._protocol) && - Helper.AreEqual2(this._address, other._address) && - Helper.AreEqual2(this._port, other._port); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_protocol, other._protocol) && + Helper.AreEqual2(_address, other._address) && + Helper.AreEqual2(_port, other._port); } public override string SaveChanges(Session session, string opaqueRef, SDN_controller server) diff --git a/XenModel/XenAPI/SM.cs b/XenModel/XenAPI/SM.cs index 44bacad00e..c9d0cb9c8a 100644 --- a/XenModel/XenAPI/SM.cs +++ b/XenModel/XenAPI/SM.cs @@ -143,13 +143,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("required_api_version")) required_api_version = Marshalling.ParseString(table, "required_api_version"); if (table.ContainsKey("configuration")) - configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration")); + configuration = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "configuration")); if (table.ContainsKey("capabilities")) capabilities = Marshalling.ParseStringArray(table, "capabilities"); if (table.ContainsKey("features")) - features = Maps.convert_from_proxy_string_long(Marshalling.ParseHashTable(table, "features")); + features = Maps.ToDictionary_string_long(Marshalling.ParseHashTable(table, "features")); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("driver_filename")) driver_filename = Marshalling.ParseString(table, "driver_filename"); if (table.ContainsKey("required_cluster_stack")) @@ -163,20 +163,20 @@ public bool DeepEquals(SM other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._vendor, other._vendor) && - Helper.AreEqual2(this._copyright, other._copyright) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._required_api_version, other._required_api_version) && - Helper.AreEqual2(this._configuration, other._configuration) && - Helper.AreEqual2(this._capabilities, other._capabilities) && - Helper.AreEqual2(this._features, other._features) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._driver_filename, other._driver_filename) && - Helper.AreEqual2(this._required_cluster_stack, other._required_cluster_stack); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_vendor, other._vendor) && + Helper.AreEqual2(_copyright, other._copyright) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_required_api_version, other._required_api_version) && + Helper.AreEqual2(_configuration, other._configuration) && + Helper.AreEqual2(_capabilities, other._capabilities) && + Helper.AreEqual2(_features, other._features) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_driver_filename, other._driver_filename) && + Helper.AreEqual2(_required_cluster_stack, other._required_cluster_stack); } public override string SaveChanges(Session session, string opaqueRef, SM server) diff --git a/XenModel/XenAPI/SR.cs b/XenModel/XenAPI/SR.cs index bd12735f63..b1ac1f0b07 100644 --- a/XenModel/XenAPI/SR.cs +++ b/XenModel/XenAPI/SR.cs @@ -156,7 +156,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_storage_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_storage_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VDIs")) VDIs = Marshalling.ParseSetRef(table, "VDIs"); if (table.ContainsKey("PBDs")) @@ -174,13 +174,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("shared")) shared = Marshalling.ParseBool(table, "shared"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("sm_config")) - sm_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "sm_config")); + sm_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "sm_config")); if (table.ContainsKey("blobs")) - blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); + blobs = Maps.ToDictionary_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("local_cache_enabled")) local_cache_enabled = Marshalling.ParseBool(table, "local_cache_enabled"); if (table.ContainsKey("introduced_by")) @@ -198,29 +198,29 @@ public bool DeepEquals(SR other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VDIs, other._VDIs) && - Helper.AreEqual2(this._PBDs, other._PBDs) && - Helper.AreEqual2(this._virtual_allocation, other._virtual_allocation) && - Helper.AreEqual2(this._physical_utilisation, other._physical_utilisation) && - Helper.AreEqual2(this._physical_size, other._physical_size) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._content_type, other._content_type) && - Helper.AreEqual2(this._shared, other._shared) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._sm_config, other._sm_config) && - Helper.AreEqual2(this._blobs, other._blobs) && - Helper.AreEqual2(this._local_cache_enabled, other._local_cache_enabled) && - Helper.AreEqual2(this._introduced_by, other._introduced_by) && - Helper.AreEqual2(this._clustered, other._clustered) && - Helper.AreEqual2(this._is_tools_sr, other._is_tools_sr); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VDIs, other._VDIs) && + Helper.AreEqual2(_PBDs, other._PBDs) && + Helper.AreEqual2(_virtual_allocation, other._virtual_allocation) && + Helper.AreEqual2(_physical_utilisation, other._physical_utilisation) && + Helper.AreEqual2(_physical_size, other._physical_size) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_content_type, other._content_type) && + Helper.AreEqual2(_shared, other._shared) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_sm_config, other._sm_config) && + Helper.AreEqual2(_blobs, other._blobs) && + Helper.AreEqual2(_local_cache_enabled, other._local_cache_enabled) && + Helper.AreEqual2(_introduced_by, other._introduced_by) && + Helper.AreEqual2(_clustered, other._clustered) && + Helper.AreEqual2(_is_tools_sr, other._is_tools_sr); } public override string SaveChanges(Session session, string opaqueRef, SR server) diff --git a/XenModel/XenAPI/Secret.cs b/XenModel/XenAPI/Secret.cs index 94da7973c8..6498171a52 100644 --- a/XenModel/XenAPI/Secret.cs +++ b/XenModel/XenAPI/Secret.cs @@ -98,7 +98,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("value")) value = Marshalling.ParseString(table, "value"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Secret other) @@ -108,9 +108,9 @@ public bool DeepEquals(Secret other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._value, other._value) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_value, other._value) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Secret server) diff --git a/XenModel/XenAPI/Sr_stat.cs b/XenModel/XenAPI/Sr_stat.cs index ff31bbc833..834277975b 100644 --- a/XenModel/XenAPI/Sr_stat.cs +++ b/XenModel/XenAPI/Sr_stat.cs @@ -128,13 +128,13 @@ public bool DeepEquals(Sr_stat other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._free_space, other._free_space) && - Helper.AreEqual2(this._total_space, other._total_space) && - Helper.AreEqual2(this._clustered, other._clustered) && - Helper.AreEqual2(this._health, other._health); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_free_space, other._free_space) && + Helper.AreEqual2(_total_space, other._total_space) && + Helper.AreEqual2(_clustered, other._clustered) && + Helper.AreEqual2(_health, other._health); } public override string SaveChanges(Session session, string opaqueRef, Sr_stat server) diff --git a/XenModel/XenAPI/Subject.cs b/XenModel/XenAPI/Subject.cs index 082c4f5b23..83ebd4f745 100644 --- a/XenModel/XenAPI/Subject.cs +++ b/XenModel/XenAPI/Subject.cs @@ -101,7 +101,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("subject_identifier")) subject_identifier = Marshalling.ParseString(table, "subject_identifier"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("roles")) roles = Marshalling.ParseSetRef(table, "roles"); } @@ -113,10 +113,10 @@ public bool DeepEquals(Subject other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._subject_identifier, other._subject_identifier) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._roles, other._roles); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_subject_identifier, other._subject_identifier) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_roles, other._roles); } public override string SaveChanges(Session session, string opaqueRef, Subject server) diff --git a/XenModel/XenAPI/Task.cs b/XenModel/XenAPI/Task.cs index 532366f498..d1ab1fa66b 100644 --- a/XenModel/XenAPI/Task.cs +++ b/XenModel/XenAPI/Task.cs @@ -144,7 +144,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("created")) created = Marshalling.ParseDateTime(table, "created"); if (table.ContainsKey("finished")) @@ -162,7 +162,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("error_info")) error_info = Marshalling.ParseStringArray(table, "error_info"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("subtask_of")) subtask_of = Marshalling.ParseRef(table, "subtask_of"); if (table.ContainsKey("subtasks")) @@ -178,25 +178,25 @@ public bool DeepEquals(Task other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._created, other._created) && - Helper.AreEqual2(this._finished, other._finished) && - Helper.AreEqual2(this._status, other._status) && - Helper.AreEqual2(this._resident_on, other._resident_on) && - Helper.AreEqual2(this._progress, other._progress) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._result, other._result) && - Helper.AreEqual2(this._error_info, other._error_info) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._subtask_of, other._subtask_of) && - Helper.AreEqual2(this._subtasks, other._subtasks) && - Helper.AreEqual2(this._backtrace, other._backtrace); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_created, other._created) && + Helper.AreEqual2(_finished, other._finished) && + Helper.AreEqual2(_status, other._status) && + Helper.AreEqual2(_resident_on, other._resident_on) && + Helper.AreEqual2(_progress, other._progress) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_result, other._result) && + Helper.AreEqual2(_error_info, other._error_info) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_subtask_of, other._subtask_of) && + Helper.AreEqual2(_subtasks, other._subtasks) && + Helper.AreEqual2(_backtrace, other._backtrace); } public override string SaveChanges(Session session, string opaqueRef, Task server) diff --git a/XenModel/XenAPI/Tunnel.cs b/XenModel/XenAPI/Tunnel.cs index 2e4be44a02..e75e08b7f0 100644 --- a/XenModel/XenAPI/Tunnel.cs +++ b/XenModel/XenAPI/Tunnel.cs @@ -109,9 +109,9 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("transport_PIF")) transport_PIF = Marshalling.ParseRef(table, "transport_PIF"); if (table.ContainsKey("status")) - status = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "status")); + status = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "status")); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("protocol")) protocol = (tunnel_protocol)Helper.EnumParseDefault(typeof(tunnel_protocol), Marshalling.ParseString(table, "protocol")); } @@ -123,12 +123,12 @@ public bool DeepEquals(Tunnel other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._access_PIF, other._access_PIF) && - Helper.AreEqual2(this._transport_PIF, other._transport_PIF) && - Helper.AreEqual2(this._status, other._status) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._protocol, other._protocol); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_access_PIF, other._access_PIF) && + Helper.AreEqual2(_transport_PIF, other._transport_PIF) && + Helper.AreEqual2(_status, other._status) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_protocol, other._protocol); } public override string SaveChanges(Session session, string opaqueRef, Tunnel server) diff --git a/XenModel/XenAPI/USB_group.cs b/XenModel/XenAPI/USB_group.cs index c97e7a474c..f8eaca7798 100644 --- a/XenModel/XenAPI/USB_group.cs +++ b/XenModel/XenAPI/USB_group.cs @@ -113,7 +113,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("VUSBs")) VUSBs = Marshalling.ParseSetRef(table, "VUSBs"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(USB_group other) @@ -123,12 +123,12 @@ public bool DeepEquals(USB_group other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._PUSBs, other._PUSBs) && - Helper.AreEqual2(this._VUSBs, other._VUSBs) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_PUSBs, other._PUSBs) && + Helper.AreEqual2(_VUSBs, other._VUSBs) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, USB_group server) diff --git a/XenModel/XenAPI/User.cs b/XenModel/XenAPI/User.cs index b5dc1c6bb0..23a7da40c1 100644 --- a/XenModel/XenAPI/User.cs +++ b/XenModel/XenAPI/User.cs @@ -103,7 +103,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("fullname")) fullname = Marshalling.ParseString(table, "fullname"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(User other) @@ -113,10 +113,10 @@ public bool DeepEquals(User other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._short_name, other._short_name) && - Helper.AreEqual2(this._fullname, other._fullname) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_short_name, other._short_name) && + Helper.AreEqual2(_fullname, other._fullname) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, User server) diff --git a/XenModel/XenAPI/VBD.cs b/XenModel/XenAPI/VBD.cs index be23178b29..de5462416b 100644 --- a/XenModel/XenAPI/VBD.cs +++ b/XenModel/XenAPI/VBD.cs @@ -155,7 +155,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vbd_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vbd_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef(table, "VM"); if (table.ContainsKey("VDI")) @@ -177,7 +177,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("empty")) empty = Marshalling.ParseBool(table, "empty"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); if (table.ContainsKey("status_code")) @@ -185,11 +185,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("status_detail")) status_detail = Marshalling.ParseString(table, "status_detail"); if (table.ContainsKey("runtime_properties")) - runtime_properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "runtime_properties")); + runtime_properties = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "runtime_properties")); if (table.ContainsKey("qos_algorithm_type")) qos_algorithm_type = Marshalling.ParseString(table, "qos_algorithm_type"); if (table.ContainsKey("qos_algorithm_params")) - qos_algorithm_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params")); + qos_algorithm_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params")); if (table.ContainsKey("qos_supported_algorithms")) qos_supported_algorithms = Marshalling.ParseStringArray(table, "qos_supported_algorithms"); if (table.ContainsKey("metrics")) @@ -203,30 +203,30 @@ public bool DeepEquals(VBD other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._VDI, other._VDI) && - Helper.AreEqual2(this._device, other._device) && - Helper.AreEqual2(this._userdevice, other._userdevice) && - Helper.AreEqual2(this._bootable, other._bootable) && - Helper.AreEqual2(this._mode, other._mode) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._unpluggable, other._unpluggable) && - Helper.AreEqual2(this._storage_lock, other._storage_lock) && - Helper.AreEqual2(this._empty, other._empty) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._status_code, other._status_code) && - Helper.AreEqual2(this._status_detail, other._status_detail) && - Helper.AreEqual2(this._runtime_properties, other._runtime_properties) && - Helper.AreEqual2(this._qos_algorithm_type, other._qos_algorithm_type) && - Helper.AreEqual2(this._qos_algorithm_params, other._qos_algorithm_params) && - Helper.AreEqual2(this._qos_supported_algorithms, other._qos_supported_algorithms) && - Helper.AreEqual2(this._metrics, other._metrics); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_VDI, other._VDI) && + Helper.AreEqual2(_device, other._device) && + Helper.AreEqual2(_userdevice, other._userdevice) && + Helper.AreEqual2(_bootable, other._bootable) && + Helper.AreEqual2(_mode, other._mode) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_unpluggable, other._unpluggable) && + Helper.AreEqual2(_storage_lock, other._storage_lock) && + Helper.AreEqual2(_empty, other._empty) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_status_code, other._status_code) && + Helper.AreEqual2(_status_detail, other._status_detail) && + Helper.AreEqual2(_runtime_properties, other._runtime_properties) && + Helper.AreEqual2(_qos_algorithm_type, other._qos_algorithm_type) && + Helper.AreEqual2(_qos_algorithm_params, other._qos_algorithm_params) && + Helper.AreEqual2(_qos_supported_algorithms, other._qos_supported_algorithms) && + Helper.AreEqual2(_metrics, other._metrics); } public override string SaveChanges(Session session, string opaqueRef, VBD server) diff --git a/XenModel/XenAPI/VBD_metrics.cs b/XenModel/XenAPI/VBD_metrics.cs index 3a3d5428f9..729a7c30b5 100644 --- a/XenModel/XenAPI/VBD_metrics.cs +++ b/XenModel/XenAPI/VBD_metrics.cs @@ -108,7 +108,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VBD_metrics other) @@ -118,11 +118,11 @@ public bool DeepEquals(VBD_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && - Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_io_read_kbs, other._io_read_kbs) && + Helper.AreEqual2(_io_write_kbs, other._io_write_kbs) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VBD_metrics server) diff --git a/XenModel/XenAPI/VDI.cs b/XenModel/XenAPI/VDI.cs index 1531be76a7..f5e1cdb7ed 100644 --- a/XenModel/XenAPI/VDI.cs +++ b/XenModel/XenAPI/VDI.cs @@ -189,7 +189,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vdi_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vdi_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("SR")) SR = Marshalling.ParseRef(table, "SR"); if (table.ContainsKey("VBDs")) @@ -207,7 +207,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("read_only")) read_only = Marshalling.ParseBool(table, "read_only"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("storage_lock")) storage_lock = Marshalling.ParseBool(table, "storage_lock"); if (table.ContainsKey("location")) @@ -219,9 +219,9 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("parent")) parent = Marshalling.ParseRef(table, "parent"); if (table.ContainsKey("xenstore_data")) - xenstore_data = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "xenstore_data")); + xenstore_data = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "xenstore_data")); if (table.ContainsKey("sm_config")) - sm_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "sm_config")); + sm_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "sm_config")); if (table.ContainsKey("is_a_snapshot")) is_a_snapshot = Marshalling.ParseBool(table, "is_a_snapshot"); if (table.ContainsKey("snapshot_of")) @@ -253,40 +253,40 @@ public bool DeepEquals(VDI other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._SR, other._SR) && - Helper.AreEqual2(this._VBDs, other._VBDs) && - Helper.AreEqual2(this._crash_dumps, other._crash_dumps) && - Helper.AreEqual2(this._virtual_size, other._virtual_size) && - Helper.AreEqual2(this._physical_utilisation, other._physical_utilisation) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._sharable, other._sharable) && - Helper.AreEqual2(this._read_only, other._read_only) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._storage_lock, other._storage_lock) && - Helper.AreEqual2(this._location, other._location) && - Helper.AreEqual2(this._managed, other._managed) && - Helper.AreEqual2(this._missing, other._missing) && - Helper.AreEqual2(this._parent, other._parent) && - Helper.AreEqual2(this._xenstore_data, other._xenstore_data) && - Helper.AreEqual2(this._sm_config, other._sm_config) && - Helper.AreEqual2(this._is_a_snapshot, other._is_a_snapshot) && - Helper.AreEqual2(this._snapshot_of, other._snapshot_of) && - Helper.AreEqual2(this._snapshots, other._snapshots) && - Helper.AreEqual2(this._snapshot_time, other._snapshot_time) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._allow_caching, other._allow_caching) && - Helper.AreEqual2(this._on_boot, other._on_boot) && - Helper.AreEqual2(this._metadata_of_pool, other._metadata_of_pool) && - Helper.AreEqual2(this._metadata_latest, other._metadata_latest) && - Helper.AreEqual2(this._is_tools_iso, other._is_tools_iso) && - Helper.AreEqual2(this._cbt_enabled, other._cbt_enabled); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_SR, other._SR) && + Helper.AreEqual2(_VBDs, other._VBDs) && + Helper.AreEqual2(_crash_dumps, other._crash_dumps) && + Helper.AreEqual2(_virtual_size, other._virtual_size) && + Helper.AreEqual2(_physical_utilisation, other._physical_utilisation) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_sharable, other._sharable) && + Helper.AreEqual2(_read_only, other._read_only) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_storage_lock, other._storage_lock) && + Helper.AreEqual2(_location, other._location) && + Helper.AreEqual2(_managed, other._managed) && + Helper.AreEqual2(_missing, other._missing) && + Helper.AreEqual2(_parent, other._parent) && + Helper.AreEqual2(_xenstore_data, other._xenstore_data) && + Helper.AreEqual2(_sm_config, other._sm_config) && + Helper.AreEqual2(_is_a_snapshot, other._is_a_snapshot) && + Helper.AreEqual2(_snapshot_of, other._snapshot_of) && + Helper.AreEqual2(_snapshots, other._snapshots) && + Helper.AreEqual2(_snapshot_time, other._snapshot_time) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_allow_caching, other._allow_caching) && + Helper.AreEqual2(_on_boot, other._on_boot) && + Helper.AreEqual2(_metadata_of_pool, other._metadata_of_pool) && + Helper.AreEqual2(_metadata_latest, other._metadata_latest) && + Helper.AreEqual2(_is_tools_iso, other._is_tools_iso) && + Helper.AreEqual2(_cbt_enabled, other._cbt_enabled); } public override string SaveChanges(Session session, string opaqueRef, VDI server) diff --git a/XenModel/XenAPI/VGPU.cs b/XenModel/XenAPI/VGPU.cs index ec8ba1c8e8..f537eff1e3 100644 --- a/XenModel/XenAPI/VGPU.cs +++ b/XenModel/XenAPI/VGPU.cs @@ -131,7 +131,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("type")) type = Marshalling.ParseRef(table, "type"); if (table.ContainsKey("resident_on")) @@ -139,7 +139,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("scheduled_to_be_resident_on")) scheduled_to_be_resident_on = Marshalling.ParseRef(table, "scheduled_to_be_resident_on"); if (table.ContainsKey("compatibility_metadata")) - compatibility_metadata = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "compatibility_metadata")); + compatibility_metadata = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "compatibility_metadata")); if (table.ContainsKey("extra_args")) extra_args = Marshalling.ParseString(table, "extra_args"); if (table.ContainsKey("PCI")) @@ -153,18 +153,18 @@ public bool DeepEquals(VGPU other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._GPU_group, other._GPU_group) && - Helper.AreEqual2(this._device, other._device) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._resident_on, other._resident_on) && - Helper.AreEqual2(this._scheduled_to_be_resident_on, other._scheduled_to_be_resident_on) && - Helper.AreEqual2(this._compatibility_metadata, other._compatibility_metadata) && - Helper.AreEqual2(this._extra_args, other._extra_args) && - Helper.AreEqual2(this._PCI, other._PCI); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_GPU_group, other._GPU_group) && + Helper.AreEqual2(_device, other._device) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_resident_on, other._resident_on) && + Helper.AreEqual2(_scheduled_to_be_resident_on, other._scheduled_to_be_resident_on) && + Helper.AreEqual2(_compatibility_metadata, other._compatibility_metadata) && + Helper.AreEqual2(_extra_args, other._extra_args) && + Helper.AreEqual2(_PCI, other._PCI); } public override string SaveChanges(Session session, string opaqueRef, VGPU server) diff --git a/XenModel/XenAPI/VGPU_type.cs b/XenModel/XenAPI/VGPU_type.cs index 8373cd37d3..96f3e56a87 100644 --- a/XenModel/XenAPI/VGPU_type.cs +++ b/XenModel/XenAPI/VGPU_type.cs @@ -173,22 +173,22 @@ public bool DeepEquals(VGPU_type other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._vendor_name, other._vendor_name) && - Helper.AreEqual2(this._model_name, other._model_name) && - Helper.AreEqual2(this._framebuffer_size, other._framebuffer_size) && - Helper.AreEqual2(this._max_heads, other._max_heads) && - Helper.AreEqual2(this._max_resolution_x, other._max_resolution_x) && - Helper.AreEqual2(this._max_resolution_y, other._max_resolution_y) && - Helper.AreEqual2(this._supported_on_PGPUs, other._supported_on_PGPUs) && - Helper.AreEqual2(this._enabled_on_PGPUs, other._enabled_on_PGPUs) && - Helper.AreEqual2(this._VGPUs, other._VGPUs) && - Helper.AreEqual2(this._supported_on_GPU_groups, other._supported_on_GPU_groups) && - Helper.AreEqual2(this._enabled_on_GPU_groups, other._enabled_on_GPU_groups) && - Helper.AreEqual2(this._implementation, other._implementation) && - Helper.AreEqual2(this._identifier, other._identifier) && - Helper.AreEqual2(this._experimental, other._experimental) && - Helper.AreEqual2(this._compatible_types_in_vm, other._compatible_types_in_vm); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_vendor_name, other._vendor_name) && + Helper.AreEqual2(_model_name, other._model_name) && + Helper.AreEqual2(_framebuffer_size, other._framebuffer_size) && + Helper.AreEqual2(_max_heads, other._max_heads) && + Helper.AreEqual2(_max_resolution_x, other._max_resolution_x) && + Helper.AreEqual2(_max_resolution_y, other._max_resolution_y) && + Helper.AreEqual2(_supported_on_PGPUs, other._supported_on_PGPUs) && + Helper.AreEqual2(_enabled_on_PGPUs, other._enabled_on_PGPUs) && + Helper.AreEqual2(_VGPUs, other._VGPUs) && + Helper.AreEqual2(_supported_on_GPU_groups, other._supported_on_GPU_groups) && + Helper.AreEqual2(_enabled_on_GPU_groups, other._enabled_on_GPU_groups) && + Helper.AreEqual2(_implementation, other._implementation) && + Helper.AreEqual2(_identifier, other._identifier) && + Helper.AreEqual2(_experimental, other._experimental) && + Helper.AreEqual2(_compatible_types_in_vm, other._compatible_types_in_vm); } public override string SaveChanges(Session session, string opaqueRef, VGPU_type server) diff --git a/XenModel/XenAPI/VIF.cs b/XenModel/XenAPI/VIF.cs index 1aa6ccd757..3145916d38 100644 --- a/XenModel/XenAPI/VIF.cs +++ b/XenModel/XenAPI/VIF.cs @@ -170,7 +170,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vif_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vif_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("device")) device = Marshalling.ParseString(table, "device"); if (table.ContainsKey("network")) @@ -182,7 +182,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("MTU")) MTU = Marshalling.ParseLong(table, "MTU"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); if (table.ContainsKey("status_code")) @@ -190,11 +190,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("status_detail")) status_detail = Marshalling.ParseString(table, "status_detail"); if (table.ContainsKey("runtime_properties")) - runtime_properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "runtime_properties")); + runtime_properties = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "runtime_properties")); if (table.ContainsKey("qos_algorithm_type")) qos_algorithm_type = Marshalling.ParseString(table, "qos_algorithm_type"); if (table.ContainsKey("qos_algorithm_params")) - qos_algorithm_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params")); + qos_algorithm_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params")); if (table.ContainsKey("qos_supported_algorithms")) qos_supported_algorithms = Marshalling.ParseStringArray(table, "qos_supported_algorithms"); if (table.ContainsKey("metrics")) @@ -228,35 +228,35 @@ public bool DeepEquals(VIF other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._device, other._device) && - Helper.AreEqual2(this._network, other._network) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._MAC, other._MAC) && - Helper.AreEqual2(this._MTU, other._MTU) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._currently_attached, other._currently_attached) && - Helper.AreEqual2(this._status_code, other._status_code) && - Helper.AreEqual2(this._status_detail, other._status_detail) && - Helper.AreEqual2(this._runtime_properties, other._runtime_properties) && - Helper.AreEqual2(this._qos_algorithm_type, other._qos_algorithm_type) && - Helper.AreEqual2(this._qos_algorithm_params, other._qos_algorithm_params) && - Helper.AreEqual2(this._qos_supported_algorithms, other._qos_supported_algorithms) && - Helper.AreEqual2(this._metrics, other._metrics) && - Helper.AreEqual2(this._MAC_autogenerated, other._MAC_autogenerated) && - Helper.AreEqual2(this._locking_mode, other._locking_mode) && - Helper.AreEqual2(this._ipv4_allowed, other._ipv4_allowed) && - Helper.AreEqual2(this._ipv6_allowed, other._ipv6_allowed) && - Helper.AreEqual2(this._ipv4_configuration_mode, other._ipv4_configuration_mode) && - Helper.AreEqual2(this._ipv4_addresses, other._ipv4_addresses) && - Helper.AreEqual2(this._ipv4_gateway, other._ipv4_gateway) && - Helper.AreEqual2(this._ipv6_configuration_mode, other._ipv6_configuration_mode) && - Helper.AreEqual2(this._ipv6_addresses, other._ipv6_addresses) && - Helper.AreEqual2(this._ipv6_gateway, other._ipv6_gateway); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_device, other._device) && + Helper.AreEqual2(_network, other._network) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_MAC, other._MAC) && + Helper.AreEqual2(_MTU, other._MTU) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_currently_attached, other._currently_attached) && + Helper.AreEqual2(_status_code, other._status_code) && + Helper.AreEqual2(_status_detail, other._status_detail) && + Helper.AreEqual2(_runtime_properties, other._runtime_properties) && + Helper.AreEqual2(_qos_algorithm_type, other._qos_algorithm_type) && + Helper.AreEqual2(_qos_algorithm_params, other._qos_algorithm_params) && + Helper.AreEqual2(_qos_supported_algorithms, other._qos_supported_algorithms) && + Helper.AreEqual2(_metrics, other._metrics) && + Helper.AreEqual2(_MAC_autogenerated, other._MAC_autogenerated) && + Helper.AreEqual2(_locking_mode, other._locking_mode) && + Helper.AreEqual2(_ipv4_allowed, other._ipv4_allowed) && + Helper.AreEqual2(_ipv6_allowed, other._ipv6_allowed) && + Helper.AreEqual2(_ipv4_configuration_mode, other._ipv4_configuration_mode) && + Helper.AreEqual2(_ipv4_addresses, other._ipv4_addresses) && + Helper.AreEqual2(_ipv4_gateway, other._ipv4_gateway) && + Helper.AreEqual2(_ipv6_configuration_mode, other._ipv6_configuration_mode) && + Helper.AreEqual2(_ipv6_addresses, other._ipv6_addresses) && + Helper.AreEqual2(_ipv6_gateway, other._ipv6_gateway); } public override string SaveChanges(Session session, string opaqueRef, VIF server) diff --git a/XenModel/XenAPI/VIF_metrics.cs b/XenModel/XenAPI/VIF_metrics.cs index d81f87dd11..2a0758305d 100644 --- a/XenModel/XenAPI/VIF_metrics.cs +++ b/XenModel/XenAPI/VIF_metrics.cs @@ -108,7 +108,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VIF_metrics other) @@ -118,11 +118,11 @@ public bool DeepEquals(VIF_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && - Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_io_read_kbs, other._io_read_kbs) && + Helper.AreEqual2(_io_write_kbs, other._io_write_kbs) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VIF_metrics server) diff --git a/XenModel/XenAPI/VLAN.cs b/XenModel/XenAPI/VLAN.cs index 8d1c090ae6..ef6c1663ac 100644 --- a/XenModel/XenAPI/VLAN.cs +++ b/XenModel/XenAPI/VLAN.cs @@ -108,7 +108,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("tag")) tag = Marshalling.ParseLong(table, "tag"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VLAN other) @@ -118,11 +118,11 @@ public bool DeepEquals(VLAN other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._tagged_PIF, other._tagged_PIF) && - Helper.AreEqual2(this._untagged_PIF, other._untagged_PIF) && - Helper.AreEqual2(this._tag, other._tag) && - Helper.AreEqual2(this._other_config, other._other_config); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_tagged_PIF, other._tagged_PIF) && + Helper.AreEqual2(_untagged_PIF, other._untagged_PIF) && + Helper.AreEqual2(_tag, other._tag) && + Helper.AreEqual2(_other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VLAN server) diff --git a/XenModel/XenAPI/VM.cs b/XenModel/XenAPI/VM.cs index b8da89339f..6b689ace30 100755 --- a/XenModel/XenAPI/VM.cs +++ b/XenModel/XenAPI/VM.cs @@ -138,8 +138,7 @@ public VM(string uuid, string reference_label, domain_type domain_type, Dictionary NVRAM, - List pending_guidances, - List recommended_guidances) + List pending_guidances) { this.uuid = uuid; this.allowed_operations = allowed_operations; @@ -229,7 +228,6 @@ public VM(string uuid, this.domain_type = domain_type; this.NVRAM = NVRAM; this.pending_guidances = pending_guidances; - this.recommended_guidances = recommended_guidances; } /// @@ -340,7 +338,6 @@ public override void UpdateFrom(VM record) domain_type = record.domain_type; NVRAM = record.NVRAM; pending_guidances = record.pending_guidances; - recommended_guidances = record.recommended_guidances; } /// @@ -356,7 +353,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vm_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vm_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("name_label")) name_label = Marshalling.ParseString(table, "name_label"); if (table.ContainsKey("name_description")) @@ -390,7 +387,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("memory_static_min")) memory_static_min = Marshalling.ParseLong(table, "memory_static_min"); if (table.ContainsKey("VCPUs_params")) - VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "VCPUs_params")); + VCPUs_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "VCPUs_params")); if (table.ContainsKey("VCPUs_max")) VCPUs_max = Marshalling.ParseLong(table, "VCPUs_max"); if (table.ContainsKey("VCPUs_at_startup")) @@ -430,21 +427,21 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("HVM_boot_policy")) HVM_boot_policy = Marshalling.ParseString(table, "HVM_boot_policy"); if (table.ContainsKey("HVM_boot_params")) - HVM_boot_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "HVM_boot_params")); + HVM_boot_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "HVM_boot_params")); if (table.ContainsKey("HVM_shadow_multiplier")) HVM_shadow_multiplier = Marshalling.ParseDouble(table, "HVM_shadow_multiplier"); if (table.ContainsKey("platform")) - platform = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "platform")); + platform = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "platform")); if (table.ContainsKey("PCI_bus")) PCI_bus = Marshalling.ParseString(table, "PCI_bus"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("domid")) domid = Marshalling.ParseLong(table, "domid"); if (table.ContainsKey("domarch")) domarch = Marshalling.ParseString(table, "domarch"); if (table.ContainsKey("last_boot_CPU_flags")) - last_boot_CPU_flags = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "last_boot_CPU_flags")); + last_boot_CPU_flags = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "last_boot_CPU_flags")); if (table.ContainsKey("is_control_domain")) is_control_domain = Marshalling.ParseBool(table, "is_control_domain"); if (table.ContainsKey("metrics")) @@ -456,7 +453,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("recommendations")) recommendations = Marshalling.ParseString(table, "recommendations"); if (table.ContainsKey("xenstore_data")) - xenstore_data = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "xenstore_data")); + xenstore_data = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "xenstore_data")); if (table.ContainsKey("ha_always_run")) ha_always_run = Marshalling.ParseBool(table, "ha_always_run"); if (table.ContainsKey("ha_restart_priority")) @@ -472,13 +469,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("transportable_snapshot_id")) transportable_snapshot_id = Marshalling.ParseString(table, "transportable_snapshot_id"); if (table.ContainsKey("blobs")) - blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); + blobs = Maps.ToDictionary_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("blocked_operations")) - blocked_operations = Maps.convert_from_proxy_vm_operations_string(Marshalling.ParseHashTable(table, "blocked_operations")); + blocked_operations = Maps.ToDictionary_vm_operations_string(Marshalling.ParseHashTable(table, "blocked_operations")); if (table.ContainsKey("snapshot_info")) - snapshot_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "snapshot_info")); + snapshot_info = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "snapshot_info")); if (table.ContainsKey("snapshot_metadata")) snapshot_metadata = Marshalling.ParseString(table, "snapshot_metadata"); if (table.ContainsKey("parent")) @@ -486,7 +483,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("children")) children = Marshalling.ParseSetRef(table, "children"); if (table.ContainsKey("bios_strings")) - bios_strings = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "bios_strings")); + bios_strings = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "bios_strings")); if (table.ContainsKey("protection_policy")) protection_policy = Marshalling.ParseRef(table, "protection_policy"); if (table.ContainsKey("is_snapshot_from_vmpp")) @@ -524,11 +521,9 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("domain_type")) domain_type = (domain_type)Helper.EnumParseDefault(typeof(domain_type), Marshalling.ParseString(table, "domain_type")); if (table.ContainsKey("NVRAM")) - NVRAM = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "NVRAM")); + NVRAM = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "NVRAM")); if (table.ContainsKey("pending_guidances")) pending_guidances = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "pending_guidances")); - if (table.ContainsKey("recommended_guidances")) - recommended_guidances = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "recommended_guidances")); } public bool DeepEquals(VM other, bool ignoreCurrentOperations) @@ -538,97 +533,96 @@ public bool DeepEquals(VM other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._power_state, other._power_state) && - Helper.AreEqual2(this._user_version, other._user_version) && - Helper.AreEqual2(this._is_a_template, other._is_a_template) && - Helper.AreEqual2(this._is_default_template, other._is_default_template) && - Helper.AreEqual2(this._suspend_VDI, other._suspend_VDI) && - Helper.AreEqual2(this._resident_on, other._resident_on) && - Helper.AreEqual2(this._scheduled_to_be_resident_on, other._scheduled_to_be_resident_on) && - Helper.AreEqual2(this._affinity, other._affinity) && - Helper.AreEqual2(this._memory_overhead, other._memory_overhead) && - Helper.AreEqual2(this._memory_target, other._memory_target) && - Helper.AreEqual2(this._memory_static_max, other._memory_static_max) && - Helper.AreEqual2(this._memory_dynamic_max, other._memory_dynamic_max) && - Helper.AreEqual2(this._memory_dynamic_min, other._memory_dynamic_min) && - Helper.AreEqual2(this._memory_static_min, other._memory_static_min) && - Helper.AreEqual2(this._VCPUs_params, other._VCPUs_params) && - Helper.AreEqual2(this._VCPUs_max, other._VCPUs_max) && - Helper.AreEqual2(this._VCPUs_at_startup, other._VCPUs_at_startup) && - Helper.AreEqual2(this._actions_after_softreboot, other._actions_after_softreboot) && - Helper.AreEqual2(this._actions_after_shutdown, other._actions_after_shutdown) && - Helper.AreEqual2(this._actions_after_reboot, other._actions_after_reboot) && - Helper.AreEqual2(this._actions_after_crash, other._actions_after_crash) && - Helper.AreEqual2(this._consoles, other._consoles) && - Helper.AreEqual2(this._VIFs, other._VIFs) && - Helper.AreEqual2(this._VBDs, other._VBDs) && - Helper.AreEqual2(this._VUSBs, other._VUSBs) && - Helper.AreEqual2(this._crash_dumps, other._crash_dumps) && - Helper.AreEqual2(this._VTPMs, other._VTPMs) && - Helper.AreEqual2(this._PV_bootloader, other._PV_bootloader) && - Helper.AreEqual2(this._PV_kernel, other._PV_kernel) && - Helper.AreEqual2(this._PV_ramdisk, other._PV_ramdisk) && - Helper.AreEqual2(this._PV_args, other._PV_args) && - Helper.AreEqual2(this._PV_bootloader_args, other._PV_bootloader_args) && - Helper.AreEqual2(this._PV_legacy_args, other._PV_legacy_args) && - Helper.AreEqual2(this._HVM_boot_policy, other._HVM_boot_policy) && - Helper.AreEqual2(this._HVM_boot_params, other._HVM_boot_params) && - Helper.AreEqual2(this._HVM_shadow_multiplier, other._HVM_shadow_multiplier) && - Helper.AreEqual2(this._platform, other._platform) && - Helper.AreEqual2(this._PCI_bus, other._PCI_bus) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._domid, other._domid) && - Helper.AreEqual2(this._domarch, other._domarch) && - Helper.AreEqual2(this._last_boot_CPU_flags, other._last_boot_CPU_flags) && - Helper.AreEqual2(this._is_control_domain, other._is_control_domain) && - Helper.AreEqual2(this._metrics, other._metrics) && - Helper.AreEqual2(this._guest_metrics, other._guest_metrics) && - Helper.AreEqual2(this._last_booted_record, other._last_booted_record) && - Helper.AreEqual2(this._recommendations, other._recommendations) && - Helper.AreEqual2(this._xenstore_data, other._xenstore_data) && - Helper.AreEqual2(this._ha_always_run, other._ha_always_run) && - Helper.AreEqual2(this._ha_restart_priority, other._ha_restart_priority) && - Helper.AreEqual2(this._is_a_snapshot, other._is_a_snapshot) && - Helper.AreEqual2(this._snapshot_of, other._snapshot_of) && - Helper.AreEqual2(this._snapshots, other._snapshots) && - Helper.AreEqual2(this._snapshot_time, other._snapshot_time) && - Helper.AreEqual2(this._transportable_snapshot_id, other._transportable_snapshot_id) && - Helper.AreEqual2(this._blobs, other._blobs) && - Helper.AreEqual2(this._tags, other._tags) && - Helper.AreEqual2(this._blocked_operations, other._blocked_operations) && - Helper.AreEqual2(this._snapshot_info, other._snapshot_info) && - Helper.AreEqual2(this._snapshot_metadata, other._snapshot_metadata) && - Helper.AreEqual2(this._parent, other._parent) && - Helper.AreEqual2(this._children, other._children) && - Helper.AreEqual2(this._bios_strings, other._bios_strings) && - Helper.AreEqual2(this._protection_policy, other._protection_policy) && - Helper.AreEqual2(this._is_snapshot_from_vmpp, other._is_snapshot_from_vmpp) && - Helper.AreEqual2(this._snapshot_schedule, other._snapshot_schedule) && - Helper.AreEqual2(this._is_vmss_snapshot, other._is_vmss_snapshot) && - Helper.AreEqual2(this._appliance, other._appliance) && - Helper.AreEqual2(this._start_delay, other._start_delay) && - Helper.AreEqual2(this._shutdown_delay, other._shutdown_delay) && - Helper.AreEqual2(this._order, other._order) && - Helper.AreEqual2(this._VGPUs, other._VGPUs) && - Helper.AreEqual2(this._attached_PCIs, other._attached_PCIs) && - Helper.AreEqual2(this._suspend_SR, other._suspend_SR) && - Helper.AreEqual2(this._version, other._version) && - Helper.AreEqual2(this._generation_id, other._generation_id) && - Helper.AreEqual2(this._hardware_platform_version, other._hardware_platform_version) && - Helper.AreEqual2(this._has_vendor_device, other._has_vendor_device) && - Helper.AreEqual2(this._requires_reboot, other._requires_reboot) && - Helper.AreEqual2(this._reference_label, other._reference_label) && - Helper.AreEqual2(this._domain_type, other._domain_type) && - Helper.AreEqual2(this._NVRAM, other._NVRAM) && - Helper.AreEqual2(this._pending_guidances, other._pending_guidances) && - Helper.AreEqual2(this._recommended_guidances, other._recommended_guidances); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_power_state, other._power_state) && + Helper.AreEqual2(_user_version, other._user_version) && + Helper.AreEqual2(_is_a_template, other._is_a_template) && + Helper.AreEqual2(_is_default_template, other._is_default_template) && + Helper.AreEqual2(_suspend_VDI, other._suspend_VDI) && + Helper.AreEqual2(_resident_on, other._resident_on) && + Helper.AreEqual2(_scheduled_to_be_resident_on, other._scheduled_to_be_resident_on) && + Helper.AreEqual2(_affinity, other._affinity) && + Helper.AreEqual2(_memory_overhead, other._memory_overhead) && + Helper.AreEqual2(_memory_target, other._memory_target) && + Helper.AreEqual2(_memory_static_max, other._memory_static_max) && + Helper.AreEqual2(_memory_dynamic_max, other._memory_dynamic_max) && + Helper.AreEqual2(_memory_dynamic_min, other._memory_dynamic_min) && + Helper.AreEqual2(_memory_static_min, other._memory_static_min) && + Helper.AreEqual2(_VCPUs_params, other._VCPUs_params) && + Helper.AreEqual2(_VCPUs_max, other._VCPUs_max) && + Helper.AreEqual2(_VCPUs_at_startup, other._VCPUs_at_startup) && + Helper.AreEqual2(_actions_after_softreboot, other._actions_after_softreboot) && + Helper.AreEqual2(_actions_after_shutdown, other._actions_after_shutdown) && + Helper.AreEqual2(_actions_after_reboot, other._actions_after_reboot) && + Helper.AreEqual2(_actions_after_crash, other._actions_after_crash) && + Helper.AreEqual2(_consoles, other._consoles) && + Helper.AreEqual2(_VIFs, other._VIFs) && + Helper.AreEqual2(_VBDs, other._VBDs) && + Helper.AreEqual2(_VUSBs, other._VUSBs) && + Helper.AreEqual2(_crash_dumps, other._crash_dumps) && + Helper.AreEqual2(_VTPMs, other._VTPMs) && + Helper.AreEqual2(_PV_bootloader, other._PV_bootloader) && + Helper.AreEqual2(_PV_kernel, other._PV_kernel) && + Helper.AreEqual2(_PV_ramdisk, other._PV_ramdisk) && + Helper.AreEqual2(_PV_args, other._PV_args) && + Helper.AreEqual2(_PV_bootloader_args, other._PV_bootloader_args) && + Helper.AreEqual2(_PV_legacy_args, other._PV_legacy_args) && + Helper.AreEqual2(_HVM_boot_policy, other._HVM_boot_policy) && + Helper.AreEqual2(_HVM_boot_params, other._HVM_boot_params) && + Helper.AreEqual2(_HVM_shadow_multiplier, other._HVM_shadow_multiplier) && + Helper.AreEqual2(_platform, other._platform) && + Helper.AreEqual2(_PCI_bus, other._PCI_bus) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_domid, other._domid) && + Helper.AreEqual2(_domarch, other._domarch) && + Helper.AreEqual2(_last_boot_CPU_flags, other._last_boot_CPU_flags) && + Helper.AreEqual2(_is_control_domain, other._is_control_domain) && + Helper.AreEqual2(_metrics, other._metrics) && + Helper.AreEqual2(_guest_metrics, other._guest_metrics) && + Helper.AreEqual2(_last_booted_record, other._last_booted_record) && + Helper.AreEqual2(_recommendations, other._recommendations) && + Helper.AreEqual2(_xenstore_data, other._xenstore_data) && + Helper.AreEqual2(_ha_always_run, other._ha_always_run) && + Helper.AreEqual2(_ha_restart_priority, other._ha_restart_priority) && + Helper.AreEqual2(_is_a_snapshot, other._is_a_snapshot) && + Helper.AreEqual2(_snapshot_of, other._snapshot_of) && + Helper.AreEqual2(_snapshots, other._snapshots) && + Helper.AreEqual2(_snapshot_time, other._snapshot_time) && + Helper.AreEqual2(_transportable_snapshot_id, other._transportable_snapshot_id) && + Helper.AreEqual2(_blobs, other._blobs) && + Helper.AreEqual2(_tags, other._tags) && + Helper.AreEqual2(_blocked_operations, other._blocked_operations) && + Helper.AreEqual2(_snapshot_info, other._snapshot_info) && + Helper.AreEqual2(_snapshot_metadata, other._snapshot_metadata) && + Helper.AreEqual2(_parent, other._parent) && + Helper.AreEqual2(_children, other._children) && + Helper.AreEqual2(_bios_strings, other._bios_strings) && + Helper.AreEqual2(_protection_policy, other._protection_policy) && + Helper.AreEqual2(_is_snapshot_from_vmpp, other._is_snapshot_from_vmpp) && + Helper.AreEqual2(_snapshot_schedule, other._snapshot_schedule) && + Helper.AreEqual2(_is_vmss_snapshot, other._is_vmss_snapshot) && + Helper.AreEqual2(_appliance, other._appliance) && + Helper.AreEqual2(_start_delay, other._start_delay) && + Helper.AreEqual2(_shutdown_delay, other._shutdown_delay) && + Helper.AreEqual2(_order, other._order) && + Helper.AreEqual2(_VGPUs, other._VGPUs) && + Helper.AreEqual2(_attached_PCIs, other._attached_PCIs) && + Helper.AreEqual2(_suspend_SR, other._suspend_SR) && + Helper.AreEqual2(_version, other._version) && + Helper.AreEqual2(_generation_id, other._generation_id) && + Helper.AreEqual2(_hardware_platform_version, other._hardware_platform_version) && + Helper.AreEqual2(_has_vendor_device, other._has_vendor_device) && + Helper.AreEqual2(_requires_reboot, other._requires_reboot) && + Helper.AreEqual2(_reference_label, other._reference_label) && + Helper.AreEqual2(_domain_type, other._domain_type) && + Helper.AreEqual2(_NVRAM, other._NVRAM) && + Helper.AreEqual2(_pending_guidances, other._pending_guidances); } public override string SaveChanges(Session session, string opaqueRef, VM server) @@ -1886,17 +1880,6 @@ public static List get_pending_guidances(Session session, stri return session.JsonRpcClient.vm_get_pending_guidances(session.opaque_ref, _vm); } - /// - /// Get the recommended_guidances field of the given VM. - /// Experimental. First published in 23.18.0. - /// - /// The session - /// The opaque_ref of the given vm - public static List get_recommended_guidances(Session session, string _vm) - { - return session.JsonRpcClient.vm_get_recommended_guidances(session.opaque_ref, _vm); - } - /// /// Set the name/label field of the given VM. /// First published in XenServer 4.0. @@ -5851,23 +5834,5 @@ public virtual List pending_guidances } } private List _pending_guidances = new List() {}; - - /// - /// The set of recommended guidances after applying updates - /// Experimental. First published in 23.18.0. - /// - public virtual List recommended_guidances - { - get { return _recommended_guidances; } - set - { - if (!Helper.AreEqual(value, _recommended_guidances)) - { - _recommended_guidances = value; - NotifyPropertyChanged("recommended_guidances"); - } - } - } - private List _recommended_guidances = new List() {}; } } diff --git a/XenModel/XenAPI/VMPP.cs b/XenModel/XenAPI/VMPP.cs index 21b8ad254d..0b4080ecea 100644 --- a/XenModel/XenAPI/VMPP.cs +++ b/XenModel/XenAPI/VMPP.cs @@ -159,7 +159,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("backup_frequency")) backup_frequency = (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), Marshalling.ParseString(table, "backup_frequency")); if (table.ContainsKey("backup_schedule")) - backup_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "backup_schedule")); + backup_schedule = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "backup_schedule")); if (table.ContainsKey("is_backup_running")) is_backup_running = Marshalling.ParseBool(table, "is_backup_running"); if (table.ContainsKey("backup_last_run_time")) @@ -167,11 +167,11 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("archive_target_type")) archive_target_type = (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), Marshalling.ParseString(table, "archive_target_type")); if (table.ContainsKey("archive_target_config")) - archive_target_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_target_config")); + archive_target_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "archive_target_config")); if (table.ContainsKey("archive_frequency")) archive_frequency = (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), Marshalling.ParseString(table, "archive_frequency")); if (table.ContainsKey("archive_schedule")) - archive_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_schedule")); + archive_schedule = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "archive_schedule")); if (table.ContainsKey("is_archive_running")) is_archive_running = Marshalling.ParseBool(table, "is_archive_running"); if (table.ContainsKey("archive_last_run_time")) @@ -181,7 +181,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("is_alarm_enabled")) is_alarm_enabled = Marshalling.ParseBool(table, "is_alarm_enabled"); if (table.ContainsKey("alarm_config")) - alarm_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "alarm_config")); + alarm_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "alarm_config")); if (table.ContainsKey("recent_alerts")) recent_alerts = Marshalling.ParseStringArray(table, "recent_alerts"); } @@ -193,26 +193,26 @@ public bool DeepEquals(VMPP other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._is_policy_enabled, other._is_policy_enabled) && - Helper.AreEqual2(this._backup_type, other._backup_type) && - Helper.AreEqual2(this._backup_retention_value, other._backup_retention_value) && - Helper.AreEqual2(this._backup_frequency, other._backup_frequency) && - Helper.AreEqual2(this._backup_schedule, other._backup_schedule) && - Helper.AreEqual2(this._is_backup_running, other._is_backup_running) && - Helper.AreEqual2(this._backup_last_run_time, other._backup_last_run_time) && - Helper.AreEqual2(this._archive_target_type, other._archive_target_type) && - Helper.AreEqual2(this._archive_target_config, other._archive_target_config) && - Helper.AreEqual2(this._archive_frequency, other._archive_frequency) && - Helper.AreEqual2(this._archive_schedule, other._archive_schedule) && - Helper.AreEqual2(this._is_archive_running, other._is_archive_running) && - Helper.AreEqual2(this._archive_last_run_time, other._archive_last_run_time) && - Helper.AreEqual2(this._VMs, other._VMs) && - Helper.AreEqual2(this._is_alarm_enabled, other._is_alarm_enabled) && - Helper.AreEqual2(this._alarm_config, other._alarm_config) && - Helper.AreEqual2(this._recent_alerts, other._recent_alerts); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_is_policy_enabled, other._is_policy_enabled) && + Helper.AreEqual2(_backup_type, other._backup_type) && + Helper.AreEqual2(_backup_retention_value, other._backup_retention_value) && + Helper.AreEqual2(_backup_frequency, other._backup_frequency) && + Helper.AreEqual2(_backup_schedule, other._backup_schedule) && + Helper.AreEqual2(_is_backup_running, other._is_backup_running) && + Helper.AreEqual2(_backup_last_run_time, other._backup_last_run_time) && + Helper.AreEqual2(_archive_target_type, other._archive_target_type) && + Helper.AreEqual2(_archive_target_config, other._archive_target_config) && + Helper.AreEqual2(_archive_frequency, other._archive_frequency) && + Helper.AreEqual2(_archive_schedule, other._archive_schedule) && + Helper.AreEqual2(_is_archive_running, other._is_archive_running) && + Helper.AreEqual2(_archive_last_run_time, other._archive_last_run_time) && + Helper.AreEqual2(_VMs, other._VMs) && + Helper.AreEqual2(_is_alarm_enabled, other._is_alarm_enabled) && + Helper.AreEqual2(_alarm_config, other._alarm_config) && + Helper.AreEqual2(_recent_alerts, other._recent_alerts); } public override string SaveChanges(Session session, string opaqueRef, VMPP server) diff --git a/XenModel/XenAPI/VMSS.cs b/XenModel/XenAPI/VMSS.cs index 0659a1bbab..a3108bcc4b 100644 --- a/XenModel/XenAPI/VMSS.cs +++ b/XenModel/XenAPI/VMSS.cs @@ -129,7 +129,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("frequency")) frequency = (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), Marshalling.ParseString(table, "frequency")); if (table.ContainsKey("schedule")) - schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "schedule")); + schedule = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "schedule")); if (table.ContainsKey("last_run_time")) last_run_time = Marshalling.ParseDateTime(table, "last_run_time"); if (table.ContainsKey("VMs")) @@ -143,16 +143,16 @@ public bool DeepEquals(VMSS other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._enabled, other._enabled) && - Helper.AreEqual2(this._type, other._type) && - Helper.AreEqual2(this._retained_snapshots, other._retained_snapshots) && - Helper.AreEqual2(this._frequency, other._frequency) && - Helper.AreEqual2(this._schedule, other._schedule) && - Helper.AreEqual2(this._last_run_time, other._last_run_time) && - Helper.AreEqual2(this._VMs, other._VMs); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_enabled, other._enabled) && + Helper.AreEqual2(_type, other._type) && + Helper.AreEqual2(_retained_snapshots, other._retained_snapshots) && + Helper.AreEqual2(_frequency, other._frequency) && + Helper.AreEqual2(_schedule, other._schedule) && + Helper.AreEqual2(_last_run_time, other._last_run_time) && + Helper.AreEqual2(_VMs, other._VMs); } public override string SaveChanges(Session session, string opaqueRef, VMSS server) diff --git a/XenModel/XenAPI/VM_appliance.cs b/XenModel/XenAPI/VM_appliance.cs index b5ab4264dd..5f847f3c85 100644 --- a/XenModel/XenAPI/VM_appliance.cs +++ b/XenModel/XenAPI/VM_appliance.cs @@ -111,7 +111,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vm_appliance_operation(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vm_appliance_operation(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VMs")) VMs = Marshalling.ParseSetRef(table, "VMs"); } @@ -123,14 +123,14 @@ public bool DeepEquals(VM_appliance other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._name_label, other._name_label) && - Helper.AreEqual2(this._name_description, other._name_description) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VMs, other._VMs); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_name_label, other._name_label) && + Helper.AreEqual2(_name_description, other._name_description) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VMs, other._VMs); } public override string SaveChanges(Session session, string opaqueRef, VM_appliance server) diff --git a/XenModel/XenAPI/VM_guest_metrics.cs b/XenModel/XenAPI/VM_guest_metrics.cs index 9d256b3bd3..71b9c8546a 100644 --- a/XenModel/XenAPI/VM_guest_metrics.cs +++ b/XenModel/XenAPI/VM_guest_metrics.cs @@ -129,23 +129,23 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("os_version")) - os_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "os_version")); + os_version = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "os_version")); if (table.ContainsKey("PV_drivers_version")) - PV_drivers_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "PV_drivers_version")); + PV_drivers_version = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "PV_drivers_version")); if (table.ContainsKey("PV_drivers_up_to_date")) PV_drivers_up_to_date = Marshalling.ParseBool(table, "PV_drivers_up_to_date"); if (table.ContainsKey("memory")) - memory = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "memory")); + memory = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "memory")); if (table.ContainsKey("disks")) - disks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "disks")); + disks = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "disks")); if (table.ContainsKey("networks")) - networks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "networks")); + networks = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "networks")); if (table.ContainsKey("other")) - other = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other")); + other = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other")); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("live")) live = Marshalling.ParseBool(table, "live"); if (table.ContainsKey("can_use_hotplug_vbd")) @@ -163,20 +163,20 @@ public bool DeepEquals(VM_guest_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._os_version, other._os_version) && - Helper.AreEqual2(this._PV_drivers_version, other._PV_drivers_version) && - Helper.AreEqual2(this._PV_drivers_up_to_date, other._PV_drivers_up_to_date) && - Helper.AreEqual2(this._memory, other._memory) && - Helper.AreEqual2(this._disks, other._disks) && - Helper.AreEqual2(this._networks, other._networks) && - Helper.AreEqual2(this._other, other._other) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._live, other._live) && - Helper.AreEqual2(this._can_use_hotplug_vbd, other._can_use_hotplug_vbd) && - Helper.AreEqual2(this._can_use_hotplug_vif, other._can_use_hotplug_vif) && - Helper.AreEqual2(this._PV_drivers_detected, other._PV_drivers_detected); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_os_version, other._os_version) && + Helper.AreEqual2(_PV_drivers_version, other._PV_drivers_version) && + Helper.AreEqual2(_PV_drivers_up_to_date, other._PV_drivers_up_to_date) && + Helper.AreEqual2(_memory, other._memory) && + Helper.AreEqual2(_disks, other._disks) && + Helper.AreEqual2(_networks, other._networks) && + Helper.AreEqual2(_other, other._other) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_live, other._live) && + Helper.AreEqual2(_can_use_hotplug_vbd, other._can_use_hotplug_vbd) && + Helper.AreEqual2(_can_use_hotplug_vif, other._can_use_hotplug_vif) && + Helper.AreEqual2(_PV_drivers_detected, other._PV_drivers_detected); } public override string SaveChanges(Session session, string opaqueRef, VM_guest_metrics server) diff --git a/XenModel/XenAPI/VM_metrics.cs b/XenModel/XenAPI/VM_metrics.cs index b21c4ded48..e80a753c50 100755 --- a/XenModel/XenAPI/VM_metrics.cs +++ b/XenModel/XenAPI/VM_metrics.cs @@ -139,13 +139,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("VCPUs_number")) VCPUs_number = Marshalling.ParseLong(table, "VCPUs_number"); if (table.ContainsKey("VCPUs_utilisation")) - VCPUs_utilisation = Maps.convert_from_proxy_long_double(Marshalling.ParseHashTable(table, "VCPUs_utilisation")); + VCPUs_utilisation = Maps.ToDictionary_long_double(Marshalling.ParseHashTable(table, "VCPUs_utilisation")); if (table.ContainsKey("VCPUs_CPU")) - VCPUs_CPU = Maps.convert_from_proxy_long_long(Marshalling.ParseHashTable(table, "VCPUs_CPU")); + VCPUs_CPU = Maps.ToDictionary_long_long(Marshalling.ParseHashTable(table, "VCPUs_CPU")); if (table.ContainsKey("VCPUs_params")) - VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "VCPUs_params")); + VCPUs_params = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "VCPUs_params")); if (table.ContainsKey("VCPUs_flags")) - VCPUs_flags = Maps.convert_from_proxy_long_string_array(Marshalling.ParseHashTable(table, "VCPUs_flags")); + VCPUs_flags = Maps.ToDictionary_long_string_array(Marshalling.ParseHashTable(table, "VCPUs_flags")); if (table.ContainsKey("state")) state = Marshalling.ParseStringArray(table, "state"); if (table.ContainsKey("start_time")) @@ -155,7 +155,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("hvm")) hvm = Marshalling.ParseBool(table, "hvm"); if (table.ContainsKey("nested_virt")) @@ -173,22 +173,22 @@ public bool DeepEquals(VM_metrics other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._memory_actual, other._memory_actual) && - Helper.AreEqual2(this._VCPUs_number, other._VCPUs_number) && - Helper.AreEqual2(this._VCPUs_utilisation, other._VCPUs_utilisation) && - Helper.AreEqual2(this._VCPUs_CPU, other._VCPUs_CPU) && - Helper.AreEqual2(this._VCPUs_params, other._VCPUs_params) && - Helper.AreEqual2(this._VCPUs_flags, other._VCPUs_flags) && - Helper.AreEqual2(this._state, other._state) && - Helper.AreEqual2(this._start_time, other._start_time) && - Helper.AreEqual2(this._install_time, other._install_time) && - Helper.AreEqual2(this._last_updated, other._last_updated) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._hvm, other._hvm) && - Helper.AreEqual2(this._nested_virt, other._nested_virt) && - Helper.AreEqual2(this._nomigrate, other._nomigrate) && - Helper.AreEqual2(this._current_domain_type, other._current_domain_type); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_memory_actual, other._memory_actual) && + Helper.AreEqual2(_VCPUs_number, other._VCPUs_number) && + Helper.AreEqual2(_VCPUs_utilisation, other._VCPUs_utilisation) && + Helper.AreEqual2(_VCPUs_CPU, other._VCPUs_CPU) && + Helper.AreEqual2(_VCPUs_params, other._VCPUs_params) && + Helper.AreEqual2(_VCPUs_flags, other._VCPUs_flags) && + Helper.AreEqual2(_state, other._state) && + Helper.AreEqual2(_start_time, other._start_time) && + Helper.AreEqual2(_install_time, other._install_time) && + Helper.AreEqual2(_last_updated, other._last_updated) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_hvm, other._hvm) && + Helper.AreEqual2(_nested_virt, other._nested_virt) && + Helper.AreEqual2(_nomigrate, other._nomigrate) && + Helper.AreEqual2(_current_domain_type, other._current_domain_type); } public override string SaveChanges(Session session, string opaqueRef, VM_metrics server) diff --git a/XenModel/XenAPI/VTPM.cs b/XenModel/XenAPI/VTPM.cs index 69e5481b1f..e46b91f1c4 100644 --- a/XenModel/XenAPI/VTPM.cs +++ b/XenModel/XenAPI/VTPM.cs @@ -113,7 +113,7 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vtpm_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vtpm_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef(table, "VM"); if (table.ContainsKey("backend")) @@ -133,16 +133,16 @@ public bool DeepEquals(VTPM other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._backend, other._backend) && - Helper.AreEqual2(this._persistence_backend, other._persistence_backend) && - Helper.AreEqual2(this._is_unique, other._is_unique) && - Helper.AreEqual2(this._is_protected, other._is_protected); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_backend, other._backend) && + Helper.AreEqual2(_persistence_backend, other._persistence_backend) && + Helper.AreEqual2(_is_unique, other._is_unique) && + Helper.AreEqual2(_is_protected, other._is_protected); } public override string SaveChanges(Session session, string opaqueRef, VTPM server) diff --git a/XenModel/XenAPI/VUSB.cs b/XenModel/XenAPI/VUSB.cs index e1643c80a2..5ba5996ac2 100644 --- a/XenModel/XenAPI/VUSB.cs +++ b/XenModel/XenAPI/VUSB.cs @@ -110,13 +110,13 @@ public void UpdateFrom(Hashtable table) if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) - current_operations = Maps.convert_from_proxy_string_vusb_operations(Marshalling.ParseHashTable(table, "current_operations")); + current_operations = Maps.ToDictionary_string_vusb_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef(table, "VM"); if (table.ContainsKey("USB_group")) USB_group = Marshalling.ParseRef(table, "USB_group"); if (table.ContainsKey("other_config")) - other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); + other_config = Maps.ToDictionary_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); } @@ -128,15 +128,15 @@ public bool DeepEquals(VUSB other, bool ignoreCurrentOperations) if (ReferenceEquals(this, other)) return true; - if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) + if (!ignoreCurrentOperations && !Helper.AreEqual2(current_operations, other.current_operations)) return false; - return Helper.AreEqual2(this._uuid, other._uuid) && - Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && - Helper.AreEqual2(this._VM, other._VM) && - Helper.AreEqual2(this._USB_group, other._USB_group) && - Helper.AreEqual2(this._other_config, other._other_config) && - Helper.AreEqual2(this._currently_attached, other._currently_attached); + return Helper.AreEqual2(_uuid, other._uuid) && + Helper.AreEqual2(_allowed_operations, other._allowed_operations) && + Helper.AreEqual2(_VM, other._VM) && + Helper.AreEqual2(_USB_group, other._USB_group) && + Helper.AreEqual2(_other_config, other._other_config) && + Helper.AreEqual2(_currently_attached, other._currently_attached); } public override string SaveChanges(Session session, string opaqueRef, VUSB server) diff --git a/XenModel/XenAPI/Vdi_nbd_server_info.cs b/XenModel/XenAPI/Vdi_nbd_server_info.cs index 1fde4bd459..669f7d9b88 100644 --- a/XenModel/XenAPI/Vdi_nbd_server_info.cs +++ b/XenModel/XenAPI/Vdi_nbd_server_info.cs @@ -118,11 +118,11 @@ public bool DeepEquals(Vdi_nbd_server_info other) if (ReferenceEquals(this, other)) return true; - return Helper.AreEqual2(this._exportname, other._exportname) && - Helper.AreEqual2(this._address, other._address) && - Helper.AreEqual2(this._port, other._port) && - Helper.AreEqual2(this._cert, other._cert) && - Helper.AreEqual2(this._subject, other._subject); + return Helper.AreEqual2(_exportname, other._exportname) && + Helper.AreEqual2(_address, other._address) && + Helper.AreEqual2(_port, other._port) && + Helper.AreEqual2(_cert, other._cert) && + Helper.AreEqual2(_subject, other._subject); } public override string SaveChanges(Session session, string opaqueRef, Vdi_nbd_server_info server) diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 04d4f851cc..13349a2b82 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU @@ -224,10 +224,10 @@ - + - + diff --git a/XenOvfApi/XenOvfApi.csproj b/XenOvfApi/XenOvfApi.csproj index 75dde5b673..029a2abab0 100644 --- a/XenOvfApi/XenOvfApi.csproj +++ b/XenOvfApi/XenOvfApi.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU diff --git a/Branding/branding.sh b/scripts/branding.ps1 similarity index 61% rename from Branding/branding.sh rename to scripts/branding.ps1 index bbd62690aa..f90f3e4f62 100644 --- a/Branding/branding.sh +++ b/scripts/branding.ps1 @@ -1,6 +1,4 @@ -#!/bin/sh - -# Copyright (c) Cloud Software Group, Inc. +# Copyright (c) Cloud Software Group, Inc. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided @@ -29,16 +27,22 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. -BRANDING_COMPANY_NAME_LEGAL="[Vendor Legal]" -BRANDING_COMPANY_NAME_SHORT="[Vendor]" -BRANDING_PRODUCT_BRAND="[XenServerProduct]" -BRANDING_SERVER="[XenServer host]" -BRANDING_BRAND_CONSOLE="[XenCenter]" -BRANDING_BRAND_CONSOLE_NO_SPACE="[XenCenter]" -BRANDING_BRAND_CONSOLE_SHORT=XenCente -BRANDING_HELP_PATH=xencenter/current-release/ -BRANDING_PV_TOOLS="[Guest Tools]" -BRANDING_PRODUCT_VERSION_TEXT=0.0.0 -BRANDING_XC_PRODUCT_VERSION=0.0.0 -BRANDING_XC_PRODUCT_VERSION_INSTALLER=0.0.0 -UPDATES_URL="[Updates url]" +$BRANDING_COMPANY_NAME_LEGAL="[Vendor Legal]" +$BRANDING_COMPANY_NAME_SHORT="[Vendor]" +$BRANDING_PRODUCT_BRAND="[XenServerProduct]" +$BRANDING_SERVER="[XenServer host]" +$BRANDING_BRAND_CONSOLE="[XenCenter]" +$BRANDING_BRAND_CONSOLE_SHORT="XenCente" +$BRANDING_HELP_PATH="xencenter/current-release/" +$BRANDING_PV_TOOLS="[Guest Tools]" +$BRANDING_PRODUCT_VERSION_TEXT="0.0.0" +$BRANDING_XC_PRODUCT_VERSION="0.0.0" +$BRANDING_XC_PRODUCT_VERSION_INSTALLER="0.0.0" +$XC_UPDATES_URL="[Xc updates url]" +$CFU_URL="[Cfu url]" +$YUM_REPO_BASE_BIN="[YumRepoBaseBin]" +$YUM_REPO_BASE_SRC="[YumRepoBaseSource]" +$YUM_REPO_EARLY_ACCESS_BIN="[YumRepoEarlyAccessBin]" +$YUM_REPO_EARLY_ACCESS_SRC="[YumRepoEarlyAccessSource]" +$YUM_REPO_NORMAL_BIN="[YumRepoNormalBin]" +$YUM_REPO_NORMAL_SRC="[YumRepoNormalSource]" diff --git a/scripts/re-branding.sh b/scripts/re-branding.sh deleted file mode 100644 index 14f099dbfb..0000000000 --- a/scripts/re-branding.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/bin/bash - -# Copyright (c) Cloud Software Group, Inc. -# -#Redistribution and use in source and binary forms, with or without modification, -#are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation and/or -#other materials provided with the distribution. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -#IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -#NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -#WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -#POSSIBILITY OF SUCH DAMAGE. - -echo Entered re-branding.sh -set -u - -GLOBAL_BUILD_NUMBER=$1 - -REPO="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" - -version_csharp() -{ - sed -b -i -e "s/0\.0\.0\.0/${BRANDING_XC_PRODUCT_VERSION}.${GLOBAL_BUILD_NUMBER}/g" \ - -e "s/0000/${BRANDING_XC_PRODUCT_VERSION}.${GLOBAL_BUILD_NUMBER}/g" \ - $1 -} - -rebranding_global() -{ - sed -b -i -e "s#\[Vendor Legal\]#${BRANDING_COMPANY_NAME_LEGAL}#g" \ - -e "s#\[Vendor\]#${BRANDING_COMPANY_NAME_SHORT}#g" \ - -e "s#\[Guest Tools\]#${BRANDING_PV_TOOLS}#g" \ - -e "s#\[XenServerProduct\]#${BRANDING_PRODUCT_BRAND}#g" \ - -e "s#\[XenServer version\]#${BRANDING_PRODUCT_VERSION_TEXT}#g" \ - -e "s#\[XenServer host\]#${BRANDING_SERVER}#g" \ - -e "s#\[XenCenter\]#${BRANDING_BRAND_CONSOLE}#g" \ - -e "s#\[XenCenter_No_Space\]#${BRANDING_BRAND_CONSOLE_NO_SPACE}#g" \ - -e "s#xencenter\/current-release\/#${BRANDING_HELP_PATH}#g" \ - -e "s#\[Xc updates url\]#${XC_UPDATES_URL}#g" \ - -e "s#\[Cfu url\]#${CFU_URL}#g" \ - -e "s#\[YumRepoBaseBin\]#${YUM_REPO_BASE_BIN}#g" \ - -e "s#\[YumRepoBaseSource\]#${YUM_REPO_BASE_SRC}#g" \ - -e "s#\[YumRepoEarlyAccessBin\]#${YUM_REPO_EARLY_ACCESS_BIN}#g" \ - -e "s#\[YumRepoEarlyAccessSource\]#${YUM_REPO_EARLY_ACCESS_SRC}#g" \ - -e "s#\[YumRepoNormalBin\]#${YUM_REPO_NORMAL_BIN}#g" \ - -e "s#\[YumRepoNormalSource\]#${YUM_REPO_NORMAL_SRC}#g" \ - $1 -} - -version_csharp "${REPO}/CommonAssemblyInfo.cs" -rebranding_global "${REPO}/CommonAssemblyInfo.cs" - -#AssemblyInfo rebranding -for projectDir in CFUValidator CommandLib xe XenAdmin XenAdminTests XenCenterLib XenModel XenOvfApi xva_verify -do - assemblyInfo="${REPO}/${projectDir}/Properties/AssemblyInfo.cs" - version_csharp ${assemblyInfo} - rebranding_global ${assemblyInfo} -done - -rebranding_global ${REPO}/XenAdmin/XenAdmin.csproj - -PRODUCT_GUID=$(uuidgen | tr [a-z] [A-Z] | tr -d [:space:]) - -sed -b -i -e "s/@AUTOGEN_PRODUCT_GUID@/${PRODUCT_GUID}/g" \ - -e "s/@PRODUCT_VERSION@/${BRANDING_XC_PRODUCT_VERSION_INSTALLER}/g" \ - -e "s/@COMPANY_NAME_LEGAL@/${BRANDING_COMPANY_NAME_LEGAL}/g" \ - -e "s/@COMPANY_NAME_SHORT@/${BRANDING_COMPANY_NAME_SHORT}/g" \ - -e "s/@BRAND_CONSOLE@/${BRANDING_BRAND_CONSOLE}/g" \ - -e "s/@BRAND_CONSOLE_NO_SPACE@/${BRANDING_BRAND_CONSOLE_NO_SPACE}/g" \ - -e "s/@BRAND_CONSOLE_SHORT@/${BRANDING_BRAND_CONSOLE_SHORT}/g" \ - -e "s/@PRODUCT_BRAND@/${BRANDING_PRODUCT_BRAND}/g" \ - ${REPO}/WixInstaller/branding.wxi - -#XenAdminTests -rebranding_global ${REPO}/XenAdminTests/TestResources/ContextMenuBuilderTestResults.xml -rebranding_global ${REPO}/XenAdminTests/XenAdminTests.csproj - -set +u diff --git a/scripts/rebranding.ps1 b/scripts/rebranding.ps1 new file mode 100644 index 0000000000..36db53b37a --- /dev/null +++ b/scripts/rebranding.ps1 @@ -0,0 +1,122 @@ +# Copyright (c) Cloud Software Group, Inc. +# +# Redistribution and use in source and binary forms, +# with or without modification, are permitted provided +# that the following conditions are met: +# +# * Redistributions of source code must retain the above +# copyright notice, this list of conditions and the +# following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the +# following disclaimer in the documentation and/or other +# materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. + +Param( + [Parameter(HelpMessage = "Global build number", Mandatory = $true)] + [int]$buildNumber +) + +$verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $verbose = $PsBoundParameters['Verbose'] +} + +#################### +# Helper functions # +#################### + +function version_csharp([string]$file) { + Write-Verbose "Versioning file $file" -Verbose:$verbose + + (Get-Content -Path $file -Encoding "utf8") ` + -replace "0.0.0.0", "$BRANDING_XC_PRODUCT_VERSION.$buildNumber" ` + -replace "0000", "$BRANDING_XC_PRODUCT_VERSION.$buildNumber" |` + Set-Content -Path $file -Encoding "utf8" +} + +function rebranding_global([string]$file) { + Write-Verbose "Rebranding file $file" -Verbose:$verbose + + (Get-Content -Path $file -Encoding "utf8") ` + -replace "\[Vendor Legal\]", $BRANDING_COMPANY_NAME_LEGAL ` + -replace "\[Vendor\]", $BRANDING_COMPANY_NAME_SHORT ` + -replace "\[Guest Tools\]", $BRANDING_PV_TOOLS ` + -replace "\[XenServerProduct\]", $BRANDING_PRODUCT_BRAND ` + -replace "\[XenServer version\]", $BRANDING_PRODUCT_VERSION_TEXT ` + -replace "\[XenServer host\]", $BRANDING_SERVER ` + -replace "\[XenCenter\]", $BRANDING_BRAND_CONSOLE ` + -replace "xencenter/current-release/", $BRANDING_HELP_PATH ` + -replace "\[Xc updates url\]", $XC_UPDATES_URL ` + -replace "\[Cfu url\]", $CFU_URL ` + -replace "\[YumRepoBaseBin\]", $YUM_REPO_BASE_BIN ` + -replace "\[YumRepoBaseSource\]", $YUM_REPO_BASE_SRC ` + -replace "\[YumRepoEarlyAccessBin\]", $YUM_REPO_EARLY_ACCESS_BIN ` + -replace "\[YumRepoEarlyAccessSource\]", $YUM_REPO_EARLY_ACCESS_SRC ` + -replace "\[YumRepoNormalBin\]", $YUM_REPO_NORMAL_BIN ` + -replace "\[YumRepoNormalSource\]", $YUM_REPO_NORMAL_SRC |` + Set-Content -Path $file -Encoding "utf8" +} + +########################## +# Rebrand solution files # +########################## + +Write-Host "Started product rebranding" + +$REPO = Get-Item "$PSScriptRoot\.." | Select-Object -ExpandProperty FullName + +. $REPO\scripts\branding.ps1 + +version_csharp $REPO\CommonAssemblyInfo.cs +rebranding_global $REPO\CommonAssemblyInfo.cs + +$projects = @("CommandLib", "xe", "XenAdmin", "XenAdminTests", "XenCenterLib", "XenModel", "XenOvfApi") + +foreach ($project in $projects) { + $assemblyInfo = "$REPO\$project\Properties\AssemblyInfo.cs" + version_csharp $assemblyInfo + rebranding_global $assemblyInfo +} + +rebranding_global $REPO\XenAdmin\XenAdmin.csproj + +rebranding_global $REPO\XenAdminTests\TestResources\ContextMenuBuilderTestResults.xml +rebranding_global $REPO\XenAdminTests\XenAdminTests.csproj + +##################### +# Rebrand installer # +##################### + +$PRODUCT_GUID = [guid]::NewGuid().ToString() + +$wxiFile="$REPO\WixInstaller\branding.wxi" + +Write-Verbose "Rebranding file $wxiFile" -Verbose:$verbose + +(Get-Content -Path $wxiFile -Encoding "utf8") ` + -replace "@AUTOGEN_PRODUCT_GUID@", $PRODUCT_GUID ` + -replace "@PRODUCT_VERSION@", $BRANDING_XC_PRODUCT_VERSION_INSTALLER ` + -replace "@COMPANY_NAME_LEGAL@", $BRANDING_COMPANY_NAME_LEGAL ` + -replace "@COMPANY_NAME_SHORT@", $BRANDING_COMPANY_NAME_SHORT ` + -replace "@BRAND_CONSOLE@", $BRANDING_BRAND_CONSOLE ` + -replace "@BRAND_CONSOLE_SHORT@", $BRANDING_BRAND_CONSOLE_SHORT ` + -replace "@PRODUCT_BRAND@", $BRANDING_PRODUCT_BRAND |` + Set-Content -Path $wxiFile -Encoding "utf8" + +Write-Host "Completed product rebranding" diff --git a/scripts/xenadmin-build.ps1 b/scripts/xenadmin-build.ps1 new file mode 100644 index 0000000000..c154fb0568 --- /dev/null +++ b/scripts/xenadmin-build.ps1 @@ -0,0 +1,331 @@ +# Copyright (c) Cloud Software Group, Inc. +# +# Redistribution and use in source and binary forms, +# with or without modification, are permitted provided +# that the following conditions are met: +# +# * Redistributions of source code must retain the above +# copyright notice, this list of conditions and the +# following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the +# following disclaimer in the documentation and/or other +# materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. + +Param( + [Parameter(HelpMessage = "Global build number", Mandatory = $true)] + [int]$buildNumber, + + [Parameter(HelpMessage = "Thumbprint of the certificate to use for signing")] + [string]$thumbPrint, + + [Parameter(HelpMessage = "Timestamp server to use for signing")] + [string]$timestampServer +) + +$verbose = $false +if ($PSBoundParameters.ContainsKey('Verbose')) { + $verbose = $PsBoundParameters['Verbose'] +} + +$ErrorActionPreference = "Stop" + +#################### +# Helper functions # +#################### + +function mkdir_clean([string]$path) { + if ([System.IO.Directory]::Exists($path)) { + Remove-Item -Path $path -Force -Recurse -Verbose:$verbose + } + New-Item -ItemType Directory -Path $path -Verbose:$verbose +} + +function build([string]$solution) { + msbuild /m /verbosity:minimal /p:Configuration=Release /p:TargetFrameworkVersion=v4.8 /p:VisualStudioVersion=17.0 $solution +} + +function get_locale_id([string]$locale) { + switch ($locale) { + "ja-jp" { 1041 } + "zh-cn" { 2052 } + "zh-tw" { 1028 } + default { 1033 } #en-us + } +} + +###################### +# clean working area # +###################### + +$REPO = Get-Item "$PSScriptRoot\.." | Select-Object -ExpandProperty FullName +$SCRATCH_DIR="$REPO\_scratch" +$OUTPUT_DIR="$REPO\_output" + +Write-Host "INFO: Cleaning scratch and output directories" +mkdir_clean $SCRATCH_DIR +mkdir_clean $OUTPUT_DIR + +. $REPO\scripts\branding.ps1 +$appName = $BRANDING_BRAND_CONSOLE + +############################################ +# package sources BEFORE applying branding # +############################################ + +Write-Host "INFO: Packaging source files" + +$gitCommit = git rev-parse HEAD +git archive --format=zip -o "$SCRATCH_DIR\xenadmin-sources.zip" $gitCommit + +Compress-Archive -Path "$SCRATCH_DIR\xenadmin-sources.zip","$REPO\packages\dotnet-packages-sources.zip" ` + -DestinationPath "$OUTPUT_DIR\$appName-source.zip" -Verbose:$verbose + +################## +# apply branding # +################## + +.$REPO\scripts\rebranding.ps1 $buildNumber -Verbose:$verbose + +Write-Host "INFO: Expanding External Tools" +Expand-Archive -Path $REPO\packages\XenCenterOVF.zip -DestinationPath $SCRATCH_DIR -Verbose:$verbose + +Write-Host "INFO: Building solution" +build $REPO\XenAdmin.sln + +############## +# sign files # +############## + +if ([System.IO.File]::Exists("$REPO\scripts\sign.ps1")) { + . $REPO\scripts\sign.ps1 + + $filesToSign = @( + "$REPO\XenAdmin\bin\Release\CommandLib.dll", + "$REPO\XenAdmin\bin\Release\MSTSCLib.dll", + "$REPO\XenAdmin\bin\Release\CoreUtilsLib.dll", + "$REPO\XenAdmin\bin\Release\XenModel.dll", + "$REPO\XenAdmin\bin\Release\XenOvf.dll", + "$REPO\XenAdmin\bin\Release\$appName.exe", + "$REPO\xe\bin\Release\xe.exe", + "$REPO\XenAdmin\ReportViewer\Microsoft.ReportViewer.Common.dll", + "$REPO\XenAdmin\ReportViewer\Microsoft.ReportViewer.ProcessingObjectModel.dll", + "$REPO\XenAdmin\ReportViewer\Microsoft.ReportViewer.WinForms.dll", + "$REPO\XenAdmin\ReportViewer\Microsoft.ReportViewer.Common.resources.dll", + "$REPO\XenAdmin\ReportViewer\Microsoft.ReportViewer.WinForms.resources.dll" + ) + + foreach ($file in $filesToSign) { + sign_artifact $file $appName $thumbPrint $timestampServer + } + + sign_artifact $REPO\XenAdmin\bin\Release\CookComputing.XmlRpcV2.dll "XML-RPC.NET" $thumbPrint $timestampServer + sign_artifact $REPO\XenAdmin\bin\Release\Newtonsoft.Json.CH.dll "JSON.NET" $thumbPrint $timestampServer + sign_artifact $REPO\XenAdmin\bin\Release\log4net.dll "Log4Net" $thumbPrint $timestampServer + sign_artifact $REPO\XenAdmin\bin\Release\ICSharpCode.SharpZipLib.dll "SharpZipLib" $thumbPrint $timestampServer + sign_artifact $REPO\XenAdmin\bin\Release\DiscUtils.dll "DiscUtils" $thumbPrint $timestampServer + +} +else { + Write-Host "INFO: Sign script does not exist; skip signing binaries" +} + +############### +# prepare Wix # +############### + +Write-Host "INFO: Preparing Wix binaries and UI sources" +mkdir_clean $SCRATCH_DIR\wixbin +Expand-Archive -Path $REPO\packages\wix311-binaries.zip -DestinationPath $SCRATCH_DIR\wixbin +mkdir_clean $SCRATCH_DIR\wixsrc +Expand-Archive -Path $REPO\packages\wix311-debug.zip -DestinationPath $SCRATCH_DIR\wixsrc + +Copy-Item -Recurse $REPO\WixInstaller $SCRATCH_DIR -Verbose:$verbose +Copy-Item -Recurse $SCRATCH_DIR\wixsrc\src\ext\UIExtension\wixlib $SCRATCH_DIR\WixInstaller -Verbose:$verbose +Copy-Item $SCRATCH_DIR\WixInstaller\wixlib\CustomizeDlg.wxs $SCRATCH_DIR\WixInstaller\wixlib\CustomizeStdDlg.wxs -Verbose:$verbose + +if ("XenCenter" -ne $appName) { + Rename-Item -Path $SCRATCH_DIR\WixInstaller\XenCenter.wxs -NewName "$appName.wxs" -Verbose:$verbose +} + +$origLocation = Get-Location +Set-Location $SCRATCH_DIR\WixInstaller\wixlib -Verbose:$verbose +try { + Write-Host "INFO: Patching Wix UI library" + git apply --verbose $SCRATCH_DIR\WixInstaller\wix_src.patch + Write-Host "INFO: Patching Wix UI library completed" +} +finally { + Set-Location $origLocation -Verbose:$verbose +} + +New-Item -ItemType File -Path $SCRATCH_DIR\WixInstaller\PrintEula.dll -Verbose:$verbose + +############### +# compile Wix # +############### + +$CANDLE="$SCRATCH_DIR\wixbin\candle.exe" +$LIT="$SCRATCH_DIR\wixbin\lit.exe" +$LIGHT="$SCRATCH_DIR\wixbin\light.exe" + +$installerUiFiles = @( + "BrowseDlg", + "CancelDlg", + "Common", + "CustomizeDlg", + "CustomizeStdDlg", + "DiskCostDlg", + "ErrorDlg", + "ErrorProgressText", + "ExitDialog", + "FatalError", + "FilesInUse", + "InstallDirDlg", + "InvalidDirDlg", + "LicenseAgreementDlg", + "MaintenanceTypeDlg", + "MaintenanceWelcomeDlg", + "MsiRMFilesInUse", + "OutOfDiskDlg", + "OutOfRbDiskDlg", + "PrepareDlg", + "ProgressDlg", + "ResumeDlg", + "SetupTypeDlg", + "UserExit", + "VerifyReadyDlg", + "WaitForCostingDlg", + "WelcomeDlg", + "WixUI_InstallDir", + "WixUI_FeatureTree" +) + +$candleList = $installerUiFiles | ForEach-Object { "$SCRATCH_DIR\WixInstaller\wixlib\$_.wxs" } +$candleListString = $candleList -join " " +$litList = $installerUiFiles | ForEach-Object { "$SCRATCH_DIR\WixInstaller\wixlib\$_.wixobj" } +$litListString = $litList -join " " + +$env:RepoRoot=$REPO +$env:WixLangId=get_locale_id $locale + +Write-Host "INFO: Compiling Wix UI" +Invoke-Expression "$CANDLE -v -out $SCRATCH_DIR\WixInstaller\wixlib\ $candleListString" +Invoke-Expression "$LIT -v -out $SCRATCH_DIR\WixInstaller\wixlib\WixUiLibrary.wixlib $litListString" + +########################################################## +# for each locale create an msi containing all resources # +########################################################## + +$locales = @("en-us") + +foreach ($locale in $locales) { + if ($locale -eq "en-us") { + $name=$appName + } + else { + $name=$appName.$locale + } + + Write-Host "INFO: Building msi installer" + + Invoke-Expression "$CANDLE -v -ext WiXNetFxExtension -ext WixUtilExtension -out $SCRATCH_DIR\WixInstaller\ $SCRATCH_DIR\WixInstaller\$appName.wxs" + + Invoke-Expression "$LIGHT -v -sval -ext WiXNetFxExtension -ext WixUtilExtension -out $SCRATCH_DIR\WixInstaller\$name.msi -loc $SCRATCH_DIR\WixInstaller\wixlib\wixui_$locale.wxl -loc $SCRATCH_DIR\WixInstaller\$locale.wxl $SCRATCH_DIR\WixInstaller\$appName.wixobj $SCRATCH_DIR\WixInstaller\wixlib\WixUiLibrary.wixlib" +} + +######################################## +# copy and sign the combined installer # +######################################## + +if ([System.IO.File]::Exists("$REPO\scripts\sign.ps1")) { + sign_artifact "$SCRATCH_DIR\WixInstaller\$appName.msi" $appName $thumbPrint $timestampServer +} +else { + Write-Host "INFO: Sign script does not exist; skip signing installer" +} + +Copy-Item -LiteralPath "$SCRATCH_DIR\WixInstaller\$appName.msi" $OUTPUT_DIR -Verbose:$verbose + +################### +# build the tests # +################### + +Write-Host "INFO: Building the tests" +build $REPO\XenAdminTests\XenAdminTests.csproj +Copy-Item $REPO\XenAdmin\ReportViewer\* $REPO\XenAdminTests\bin\Release\ -Verbose:$verbose + +Compress-Archive -Path $REPO\XenAdminTests\bin\Release -DestinationPath $OUTPUT_DIR\XenAdminTests.zip -Verbose:$verbose +Compress-Archive -Path $REPO\XenAdmin\TestResources\* -DestinationPath "$OUTPUT_DIR\$($appName)TestResources.zip" -Verbose:$verbose + +#################### +# package the pdbs # +#################### + +Compress-Archive -Path $REPO\packages\*.pdb,$REPO\XenAdmin\bin\Release\*.pdb,$REPO\xe\bin\Release\xe.pdb ` + -DestinationPath "$OUTPUT_DIR\$appName.Symbols.zip" -Verbose:$verbose + +################################################ +# calculate installer and source zip checksums # +################################################ + +$msi_checksum = (Get-FileHash -LiteralPath "$OUTPUT_DIR\$appName.msi" -Algorithm SHA256 |` + Select-Object -ExpandProperty Hash).ToLower() + +$msi_checksum | Out-File -LiteralPath "$OUTPUT_DIR\$appName.msi.checksum" -Encoding utf8 + +Write-Host "INFO: Calculated checksum installer checksum: $msi_checksum" + +$source_checksum = (Get-FileHash -LiteralPath "$OUTPUT_DIR\$appName-source.zip" -Algorithm SHA256 |` + Select-Object -ExpandProperty Hash).ToLower() + +$source_checksum | Out-File -LiteralPath "$OUTPUT_DIR\$appName-source.zip.checksum" -Encoding utf8 + +Write-Host "INFO: Calculated checksum source checksum: $source_checksum" + +$xmlFormat=@" + + + + + + +"@ + +$msi_url = $XC_UPDATES_URL -replace "XCUpdates.xml","$appName.msi" +$date=(Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") +$productVersion = "$BRANDING_XC_PRODUCT_VERSION.$buildNumber" +$productFullName = "$appName $productVersion" + +Write-Host "INFO: Generating XCUpdates.xml" + +[string]::Format($xmlFormat, $productFullName, $date, $msi_url, $msi_checksum, $productVersion) |` + Out-File -FilePath $OUTPUT_DIR\XCUpdates.xml -Encoding utf8 + +Write-Host "INFO: Generating stage-test-XCUpdates.xml. URL is a placeholder value" + +[string]::Format($xmlFormat, $productFullName, $date, "@DEV_MSI_URL_PLACEHOLDER@", $msi_checksum, $productVersion) |` + Out-File -FilePath $OUTPUT_DIR\stage-test-XCUpdates.xml -Encoding utf8 diff --git a/scripts/xenadmin-build.sh b/scripts/xenadmin-build.sh deleted file mode 100644 index 842eac5c8a..0000000000 --- a/scripts/xenadmin-build.sh +++ /dev/null @@ -1,229 +0,0 @@ -#!/bin/bash - -# Copyright (c) Cloud Software Group, Inc. -# -# Redistribution and use in source and binary forms, -# with or without modification, are permitted provided -# that the following conditions are met: -# -# * Redistributions of source code must retain the above -# copyright notice, this list of conditions and the -# following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the -# following disclaimer in the documentation and/or other -# materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND -# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. - -# Script parameters: -# 1 Global build number - -set -exu - -UNZIP="unzip -q -o" - -mkdir_clean() -{ - rm -rf $1 && mkdir -p $1 -} - -REPO="$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -SCRATCH_DIR=${REPO}/_scratch -OUTPUT_DIR=${REPO}/_output - -#build -MSBUILD="/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/2019/Community/MSBuild/Current/Bin/MSBuild.exe" -SWITCHES="/m /verbosity:minimal /p:Configuration=Release /p:TargetFrameworkVersion=v4.8 /p:VisualStudioVersion=16.0" - -if [ ! -f "${MSBUILD}" ] ; then - echo "DEBUG: Did not find VS Community edition. Trying Professional" - MSBUILD="/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/2019/Professional/MSBuild/Current/Bin/MSBuild.exe" -fi - -if [ ! -f "${MSBUILD}" ] ; then - echo "DEBUG: Did not find VS Professional edition. Trying Enterprise" - MSBUILD="/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/MSBuild/Current/Bin/MSBuild.exe" -fi - -mkdir_clean ${SCRATCH_DIR} -mkdir_clean ${OUTPUT_DIR} - -source ${REPO}/Branding/branding.sh -source ${REPO}/scripts/re-branding.sh $1 - -#packages sources -mkdir_clean ${SCRATCH_DIR}/SOURCES -cd ${REPO} -gitCommit=`git rev-parse HEAD` -git archive --format=zip -o "_scratch/SOURCES/xenadmin-sources.zip" ${gitCommit} -cp ${REPO}/packages/dotnet-packages-sources.zip ${SCRATCH_DIR}/SOURCES -cd ${SCRATCH_DIR}/SOURCES && zip ${OUTPUT_DIR}/${BRANDING_BRAND_CONSOLE_NO_SPACE}-source.zip dotnet-packages-sources.zip xenadmin-sources.zip - -${UNZIP} -d ${SCRATCH_DIR} ${REPO}/packages/XenCenterOVF.zip -cd ${REPO} && "${MSBUILD}" ${SWITCHES} XenAdmin.sln - -#sign files only if all parameters are set and non-empty -SIGN_BAT="${REPO}/scripts/sign.bat" - -if [ -f "${SIGN_BAT}" ] ; then - for file in ${BRANDING_BRAND_CONSOLE_NO_SPACE}.exe CommandLib.dll MSTSCLib.dll CoreUtilsLib.dll XenModel.dll XenOvf.dll - do - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} ${file} "${BRANDING_BRAND_CONSOLE}" - done - - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} ${BRANDING_BRAND_CONSOLE_NO_SPACE}.exe "${BRANDING_BRAND_CONSOLE}" - cd ${REPO}/xe/bin/Release && ${SIGN_BAT} xe.exe "${BRANDING_BRAND_CONSOLE}" - cd ${REPO}/xva_verify/bin/Release && ${SIGN_BAT} xva_verify.exe "${BRANDING_BRAND_CONSOLE}" - - for file in Microsoft.ReportViewer.Common.dll Microsoft.ReportViewer.ProcessingObjectModel.dll Microsoft.ReportViewer.WinForms.dll Microsoft.ReportViewer.Common.resources.dll Microsoft.ReportViewer.WinForms.resources.dll - do - cd ${REPO}/XenAdmin/ReportViewer && ${SIGN_BAT} ${file} "${BRANDING_BRAND_CONSOLE}" - done - - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} CookComputing.XmlRpcV2.dll "XML-RPC.NET" - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} Newtonsoft.Json.CH.dll "JSON.NET" - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} log4net.dll "Log4Net" - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} ICSharpCode.SharpZipLib.dll "SharpZipLib" - cd ${REPO}/XenAdmin/bin/Release && ${SIGN_BAT} DiscUtils.dll "DiscUtils" - -else - echo "Sign script does not exist; skip signing binaries" -fi - -#prepare wix - -WIX_BIN=${SCRATCH_DIR}/wixbin -WIX_SRC=${SCRATCH_DIR}/wixsrc -WIX=${SCRATCH_DIR}/WixInstaller - -CANDLE=${WIX_BIN}/candle.exe -LIT=${WIX_BIN}/lit.exe -LIGHT=${WIX_BIN}/light.exe - -mkdir_clean ${WIX_BIN} && ${UNZIP} ${REPO}/packages/wix311-binaries.zip -d ${WIX_BIN} -mkdir_clean ${WIX_SRC} && ${UNZIP} ${REPO}/packages/wix311-debug.zip -d ${WIX_SRC} -cp -r ${REPO}/WixInstaller ${SCRATCH_DIR}/ -cp -r ${WIX_SRC}/src/ext/UIExtension/wixlib ${WIX}/ -cd ${WIX}/wixlib && cp CustomizeDlg.wxs CustomizeStdDlg.wxs -cd ${WIX}/wixlib && patch -p1 --binary < ${WIX}/wix_src.patch -touch ${WIX}/PrintEula.dll - -#compile_wix -chmod -R u+rx ${WIX_BIN} -cd ${WIX} && mkdir -p obj lib -RepoRoot=$(cygpath -w ${REPO}) ${CANDLE} -out obj/ @candleList.txt -${LIT} -out lib/WixUI_InstallDir.wixlib @litList.txt - -locale_id() { - case "$1" in - "ja-jp") echo 1041 ;; - "zh-cn") echo 2052 ;; - "zh-tw") echo 1028 ;; - *) echo 1033 ;; #en-us - esac -} - -if [ "XenCenter" != "${BRANDING_BRAND_CONSOLE}" ] ; then - cd ${WIX} && mv XenCenter.wxs ${BRANDING_BRAND_CONSOLE_NO_SPACE}.wxs -fi - -#for each locale create an msi containing all resources - -for locale in en-us -do - if [ "${locale}" = "en-us" ] ; then - name=${BRANDING_BRAND_CONSOLE_NO_SPACE} - else - name=${BRANDING_BRAND_CONSOLE_NO_SPACE}.${locale} - fi - - cd ${WIX} - mkdir -p obj${name} out${name} - - WixLangId=$(locale_id ${locale} | tr -d [:space:]) RepoRoot=$(cygpath -w ${REPO}) \ - ${CANDLE} -ext WiXNetFxExtension -ext WixUtilExtension -out obj${name}/ ${BRANDING_BRAND_CONSOLE_NO_SPACE}.wxs - - ${LIGHT} -sval -ext WiXNetFxExtension -ext WixUtilExtension -out out${name}/${name}.msi \ - -loc wixlib/wixui_${locale}.wxl -loc ${locale}.wxl \ - obj${name}/${BRANDING_BRAND_CONSOLE_NO_SPACE}.wixobj lib/WixUI_InstallDir.wixlib - - cp ${WIX}/out${name}/${name}.msi ${WIX} -done - -#copy and sign the combined installer - -if [ -f "${SIGN_BAT}" ] ; then - cd ${WIX} && chmod a+rw ${BRANDING_BRAND_CONSOLE_NO_SPACE}.msi && ${SIGN_BAT} ${BRANDING_BRAND_CONSOLE_NO_SPACE}.msi "${BRANDING_BRAND_CONSOLE}" -else - echo "Sign script does not exist; skip signing installer" -fi - -cp ${WIX}/${BRANDING_BRAND_CONSOLE_NO_SPACE}.msi ${OUTPUT_DIR} - -#build the tests -echo "INFO: Build the tests..." -cd ${REPO}/XenAdminTests && "${MSBUILD}" ${SWITCHES} -cp ${REPO}/XenAdmin/ReportViewer/* ${REPO}/XenAdminTests/bin/Release/ -cd ${REPO}/XenAdminTests/bin/ && zip -r ${OUTPUT_DIR}/XenAdminTests.zip Release -cd ${REPO}/XenAdmin/TestResources && zip -r ${OUTPUT_DIR}/${BRANDING_BRAND_CONSOLE_NO_SPACE}TestResources.zip * - -#include cfu validator binary in output directory -cd ${REPO}/CFUValidator/bin/Release && zip ${OUTPUT_DIR}/CFUValidator.zip ./{*.dll,CFUValidator.exe,${BRANDING_BRAND_CONSOLE_NO_SPACE}.exe} - -#now package the pdbs -cp ${REPO}/packages/*.pdb ${OUTPUT_DIR} - -cp ${REPO}/XenAdmin/bin/Release/{CommandLib.pdb,${BRANDING_BRAND_CONSOLE_NO_SPACE}.pdb,CoreUtilsLib.pdb,${BRANDING_BRAND_CONSOLE_NO_SPACE}.pdb,XenModel.pdb,XenOvf.pdb} \ - ${REPO}/xe/bin/Release/xe.pdb \ - ${REPO}/xva_verify/bin/Release/xva_verify.pdb \ - ${OUTPUT_DIR} - -cd ${OUTPUT_DIR} && zip -r -m ${BRANDING_BRAND_CONSOLE_NO_SPACE}.Symbols.zip *.pdb - -msi_checksum_with_file_name=`sha256sum ./${BRANDING_BRAND_CONSOLE_NO_SPACE}.msi` -echo $msi_checksum_with_file_name > ${OUTPUT_DIR}/${BRANDING_BRAND_CONSOLE_NO_SPACE}.msi.checksum -msi_checksum=($msi_checksum_with_file_name) - -sha256sum ${OUTPUT_DIR}/${BRANDING_BRAND_CONSOLE_NO_SPACE}-source.zip > ${OUTPUT_DIR}/${BRANDING_BRAND_CONSOLE_NO_SPACE}-source.zip.checksum - -echo "INFO: Generating XCUpdates.xml" - -# UPDATE_URL points at the updates XML, we need to point to the MSI -msi_url="${UPDATES_URL/XCUpdates.xml/$BRANDING_BRAND_CONSOLE_NO_SPACE.msi}" - -output_xml=" - - - - -" - -echo $output_xml > ${OUTPUT_DIR}/XCUpdates.xml - -echo "INFO: Generating stage-test-XCUpdates.xml. URL is a placeholder value" - -echo "${output_xml/"url=\"${msi_url}\""/"url=\"@DEV_MSI_URL_PLACEHOLDER@\""}" > ${OUTPUT_DIR}/stage-test-XCUpdates.xml - -set +u diff --git a/xe/Xe.csproj b/xe/Xe.csproj index 1fa5b6c013..af0a681bb9 100755 --- a/xe/Xe.csproj +++ b/xe/Xe.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU @@ -83,7 +83,6 @@ - - \ No newline at end of file diff --git a/xva_verify/xva_verify.rc b/xva_verify/xva_verify.rc deleted file mode 100644 index 923079a770..0000000000 --- a/xva_verify/xva_verify.rc +++ /dev/null @@ -1,4 +0,0 @@ -#define RT_MANIFEST 24 -#define APP_MANIFEST 1 - -APP_MANIFEST RT_MANIFEST xva_verify.manifest