From a78b1541e7474c6aaa4f3aff4e10fef1b3964386 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 9 Aug 2021 15:24:15 +0100 Subject: [PATCH 01/62] CA-339273: Mention source SR in VDI actions Description Also changed description to reflect the status of the action Signed-off-by: Danilo Del Busso --- XenModel/Actions/VDI/MigrateVirtualDiskAction.cs | 5 ++--- XenModel/Actions/VDI/MoveVirtualDiskAction.cs | 6 +++--- XenModel/Actions/VM/VMMoveAction.cs | 2 +- XenModel/Messages.Designer.cs | 11 +---------- XenModel/Messages.resx | 5 +---- 5 files changed, 8 insertions(+), 21 deletions(-) diff --git a/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs b/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs index 5cbd1654f..7f410afce 100644 --- a/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs +++ b/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs @@ -44,16 +44,15 @@ namespace XenAdmin.Actions private readonly VDI vdi; public MigrateVirtualDiskAction(IXenConnection connection, VDI vdi, SR sr) - : base(connection, string.Format(Messages.ACTION_MOVING_VDI_TO_SR, Helpers.GetName(vdi), Helpers.GetName(sr))) + : base(connection, string.Format(Messages.ACTION_MOVING_VDI_TO_SR, Helpers.GetName(vdi), Helpers.GetName(connection.Resolve(vdi.SR)), Helpers.GetName(sr))) { - Description = Messages.ACTION_PREPARING; this.vdi = vdi; SR = sr; } protected override void Run() { - Description = string.Format(Messages.ACTION_MOVING_VDI, Helpers.GetName(vdi)); + Description = Messages.MOVING; RelatedTask = VDI.async_pool_migrate(Session, vdi.opaque_ref, SR.opaque_ref, new Dictionary()); PollToCompletion(); Description = Messages.MOVED; diff --git a/XenModel/Actions/VDI/MoveVirtualDiskAction.cs b/XenModel/Actions/VDI/MoveVirtualDiskAction.cs index d784e5fa1..2659b43e1 100644 --- a/XenModel/Actions/VDI/MoveVirtualDiskAction.cs +++ b/XenModel/Actions/VDI/MoveVirtualDiskAction.cs @@ -44,8 +44,8 @@ namespace XenAdmin.Actions private VDI vdi; - public MoveVirtualDiskAction(IXenConnection connection, XenAPI.VDI vdi, SR sr) - : base(connection, string.Format(Messages.ACTION_MOVING_VDI_TO_SR, Helpers.GetName(vdi), Helpers.GetName(sr))) + public MoveVirtualDiskAction(IXenConnection connection, VDI vdi, SR sr) + : base(connection, string.Format(Messages.ACTION_MOVING_VDI_TO_SR, Helpers.GetName(vdi), Helpers.GetName(connection.Resolve(vdi.SR)), Helpers.GetName(sr))) { this.vdi = vdi; SR = sr; @@ -61,7 +61,7 @@ namespace XenAdmin.Actions protected override void Run() { - Description = string.Format(Messages.ACTION_MOVING_VDI, Helpers.GetName(vdi)); + Description = Messages.MOVING; PercentComplete = 10; log.DebugFormat("Moving VDI '{0}'", Helpers.GetName(vdi)); RelatedTask = VDI.async_copy(Session, vdi.opaque_ref, SR.opaque_ref); diff --git a/XenModel/Actions/VM/VMMoveAction.cs b/XenModel/Actions/VM/VMMoveAction.cs index 5472eefe7..c63e38ca1 100644 --- a/XenModel/Actions/VM/VMMoveAction.cs +++ b/XenModel/Actions/VM/VMMoveAction.cs @@ -126,7 +126,7 @@ namespace XenAdmin.Actions.VMActions continue; Description = string.Format(Messages.ACTION_MOVING_VDI_TO_SR, - Helpers.GetName(curVdi), Helpers.GetName(sr)); + Helpers.GetName(curVdi), Helpers.GetName(Connection.Resolve(curVdi.SR)), Helpers.GetName(sr)); RelatedTask = VDI.async_copy(Session, oldVBD.VDI.opaque_ref, sr.opaque_ref); PollToCompletion(PercentComplete, PercentComplete + halfstep); diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 61d8bd416..ee2b553e4 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -1555,16 +1555,7 @@ namespace XenAdmin { } /// - /// Looks up a localized string similar to Moving virtual disk '{0}'.... - /// - public static string ACTION_MOVING_VDI { - get { - return ResourceManager.GetString("ACTION_MOVING_VDI", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Moving Virtual Disk '{0}' to SR '{1}'. + /// Looks up a localized string similar to Moving Virtual Disk '{0}' from SR '{1}' to SR '{2}'. /// public static string ACTION_MOVING_VDI_TO_SR { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 91ef2e8c2..92fda7da1 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -615,11 +615,8 @@ Started migrating virtual disks - - Moving virtual disk '{0}'... - - Moving Virtual Disk '{0}' to SR '{1}' + Moving Virtual Disk '{0}' from SR '{1}' to SR '{2}' Moving {0} virtual disks to {1} From 72a997950651dfdbad4f41171a05d6b622101656 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 12:37:37 +0100 Subject: [PATCH 02/62] CA-339273: Mention source and destination Hosts in VM move action Also removed unused `this` calls, and updated one constructor override. Signed-off-by: Danilo Del Busso --- XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs | 2 +- XenModel/Actions/VM/VMMoveAction.cs | 36 ++++++++++------------ XenModel/Messages.Designer.cs | 11 +------ XenModel/Messages.resx | 5 +-- 4 files changed, 20 insertions(+), 34 deletions(-) diff --git a/XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs b/XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs index 491644534..27c0daebe 100644 --- a/XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs +++ b/XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs @@ -78,7 +78,7 @@ namespace XenAdmin.Dialogs.VMDialogs private void buttonMove_Click(object sender, EventArgs e) { - var action = new VMMoveAction(vm, srPicker1.SR, vm.GetStorageHost(false), vm.Name()); + var action = new VMMoveAction(vm, srPicker1.SR, vm.GetStorageHost(false)); action.RunAsync(); Close(); } diff --git a/XenModel/Actions/VM/VMMoveAction.cs b/XenModel/Actions/VM/VMMoveAction.cs index c63e38ca1..8598c520b 100644 --- a/XenModel/Actions/VM/VMMoveAction.cs +++ b/XenModel/Actions/VM/VMMoveAction.cs @@ -45,13 +45,13 @@ namespace XenAdmin.Actions.VMActions private Dictionary _storageMapping; public VMMoveAction(VM vm, Dictionary storageMapping, Host host) - : base(vm.Connection, string.Format(Messages.ACTION_VM_MOVING, vm.Name())) + : base(vm.Connection, string.Format(Messages.ACTION_VM_MOVING, vm.Name(), vm.Connection.Name, host.Name())) { - this.VM = vm; - this.Host = host; - this.Pool = Helpers.GetPool(vm.Connection); + VM = vm; + Host = host; + Pool = Helpers.GetPool(vm.Connection); if (vm.is_a_template) - this.Template = vm; + Template = vm; _storageMapping = storageMapping; SR = _storageMapping.Values.FirstOrDefault(); @@ -59,26 +59,22 @@ namespace XenAdmin.Actions.VMActions PopulateApiMethodsToRoleCheck(); } - public VMMoveAction(VM vm, SR sr, Host host, string namelabel) - : base(vm.Connection, string.Format(Messages.ACTION_VM_MOVING_TITLE, vm.Name(), namelabel, sr.NameWithoutHost())) + public VMMoveAction(VM vm, SR sr, Host host) + : this(vm, GetStorageMapping(vm, sr), host) { - this.VM = vm; - this.Host = host; - this.Pool = Helpers.GetPool(vm.Connection); - this.SR = sr; - if (vm.is_a_template) - this.Template = vm; + } - // create a storage map where all VDIs are mapped to the same SR - _storageMapping = new Dictionary(); + private static Dictionary GetStorageMapping(VM vm, SR sr) + { + var storageMapping = new Dictionary(); foreach (var vbdRef in vm.VBDs) { var vbd = vm.Connection.Resolve(vbdRef); if (vbd != null) - _storageMapping.Add(vbd.VDI.opaque_ref, sr); + storageMapping.Add(vbd.VDI.opaque_ref, sr); } + return storageMapping; - PopulateApiMethodsToRoleCheck(); } #region RBAC Dependencies @@ -96,7 +92,7 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - Description = Messages.ACTION_PREPARING; + Description = Messages.MOVING; // move the progress bar above 0, it's more reassuring to see than a blank bar as we copy the first disk PercentComplete += 10; @@ -160,11 +156,13 @@ namespace XenAdmin.Actions.VMActions PercentComplete += halfstep; } + Description = Messages.MOVING; + if (SR != null) VM.set_suspend_SR(Session, VM.opaque_ref, SR.opaque_ref); if (exceptions.Count > 0) - throw new Exception(Messages.ACTION_VM_MOVING_VDI_DESTROY_FAILURE); + throw new Exception(string.Format(Messages.ACTION_VM_MOVING_VDI_DESTROY_FAILURE, VM.NameWithLocation())); Description = Messages.MOVED; } diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index ee2b553e4..83bcb7b50 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -3175,7 +3175,7 @@ namespace XenAdmin { } /// - /// Looks up a localized string similar to Moving VM '{0}' to new storage. + /// Looks up a localized string similar to Moving VM '{0}' from Host '{1}' to Host '{2}'. /// public static string ACTION_VM_MOVING { get { @@ -3183,15 +3183,6 @@ namespace XenAdmin { } } - /// - /// Looks up a localized string similar to Moving VM '{0}' to '{1}' on SR '{2}'. - /// - public static string ACTION_VM_MOVING_TITLE { - get { - return ResourceManager.GetString("ACTION_VM_MOVING_TITLE", resourceCulture); - } - } - /// /// Looks up a localized string similar to Failed to finalize moving VM '{0}' to new storage. Please see logs for details.. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 92fda7da1..5fe154775 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -1177,10 +1177,7 @@ Migrating VM '{0}' - Moving VM '{0}' to new storage - - - Moving VM '{0}' to '{1}' on SR '{2}' + Moving VM '{0}' from Host '{1}' to Host '{2}' Failed to finalize moving VM '{0}' to new storage. Please see logs for details. From d41cd94baf04f39a7eff65e746d5ebd0a498a31c Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 13:54:06 +0100 Subject: [PATCH 03/62] CA-339273: Mention source Host/Pool in VM clone action Also removed useless `this` calls and tidied code Signed-off-by: Danilo Del Busso --- XenModel/Actions/VM/VMCloneAction.cs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/XenModel/Actions/VM/VMCloneAction.cs b/XenModel/Actions/VM/VMCloneAction.cs index 2da1ee64b..10693eb42 100644 --- a/XenModel/Actions/VM/VMCloneAction.cs +++ b/XenModel/Actions/VM/VMCloneAction.cs @@ -29,6 +29,7 @@ * SUCH DAMAGE. */ +using XenAdmin.Core; using XenAPI; @@ -40,14 +41,13 @@ namespace XenAdmin.Actions.VMActions protected string _cloneName; protected string _cloneDescription; public VMCloneAction(VM vm, string name, string description) - : base(vm.Connection, string.Format(Messages.CREATEVM_CLONE, name, vm.Name())) + : base(vm.Connection, string.Format(Messages.CREATEVM_CLONE, name, vm.NameWithLocation())) { - this.Description = Messages.ACTION_PREPARING; - this.VM = vm; - this.Host = vm.Home(); - this.Pool = Core.Helpers.GetPool(vm.Connection); + VM = vm; + Host = vm.Home(); + Pool = Helpers.GetPool(vm.Connection); if (vm.is_a_template) - this.Template = vm; + Template = vm; _cloneName = name; _cloneDescription = description; ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList); @@ -58,15 +58,15 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - this.Description = Messages.ACTION_TEMPLATE_CLONING; - RelatedTask = XenAPI.VM.async_clone(Session, VM.opaque_ref, _cloneName); + Description = Messages.ACTION_TEMPLATE_CLONING; + RelatedTask = VM.async_clone(Session, VM.opaque_ref, _cloneName); PollToCompletion(); { VM created = Connection.WaitForCache(new XenRef(Result)); - XenAPI.VM.set_name_description(Session, created.opaque_ref, _cloneDescription); + VM.set_name_description(Session, created.opaque_ref, _cloneDescription); Result = created.opaque_ref; } - this.Description = Messages.ACTION_TEMPLATE_CLONED; + Description = Messages.ACTION_TEMPLATE_CLONED; } } From d5e2324408668b8071a0b6db04a544d5031b6f19 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 14:18:11 +0100 Subject: [PATCH 04/62] CA-339273: Mention source Host in VM copy action Also removed useless `this` calls and tidied code Signed-off-by: Danilo Del Busso --- XenModel/Actions/VM/VMCopyAction.cs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/XenModel/Actions/VM/VMCopyAction.cs b/XenModel/Actions/VM/VMCopyAction.cs index 6b4f64f7b..6d1d210c1 100644 --- a/XenModel/Actions/VM/VMCopyAction.cs +++ b/XenModel/Actions/VM/VMCopyAction.cs @@ -40,19 +40,17 @@ namespace XenAdmin.Actions.VMActions private string _namedescription; public VMCopyAction(VM vm, Host host, SR sr, string nameLabel, string description) - : base(vm.Connection, string.Format(Messages.ACTION_VM_COPYING_TITLE, vm.Name(), nameLabel, sr.NameWithoutHost())) + : base(vm.Connection, string.Format(Messages.ACTION_VM_COPYING_TITLE, vm.NameWithLocation(), nameLabel, sr.NameWithLocation())) { - this.Description = Messages.ACTION_PREPARING; - this.VM = vm; - this.Host = host; - this.Pool = Core.Helpers.GetPool(vm.Connection); - this.SR = sr; + VM = vm; + Host = host; + Pool = Core.Helpers.GetPool(vm.Connection); + SR = sr; _nameLabel = nameLabel; if (vm.is_a_template) - this.Template = vm; + Template = vm; _namedescription = description; SetRBACPermissions(); - } private void SetRBACPermissions() @@ -67,25 +65,22 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - - this.Description = Messages.ACTION_VM_COPYING; - RelatedTask = XenAPI.VM.async_copy(Session, VM.opaque_ref, _nameLabel, this.SR.opaque_ref); + Description = Messages.ACTION_VM_COPYING; + RelatedTask = VM.async_copy(Session, VM.opaque_ref, _nameLabel, SR.opaque_ref); try { PollToCompletion(); } catch (CancelledException) { - this.Description = string.Format(Messages.COPY_TO_SHARED_CANCELLED, VM.Name()); + Description = string.Format(Messages.COPY_TO_SHARED_CANCELLED, VM.NameWithLocation()); throw; } { VM created = Connection.WaitForCache(new XenRef(Result)); - XenAPI.VM.set_name_description(Session, created.opaque_ref, _namedescription); + VM.set_name_description(Session, created.opaque_ref, _namedescription); } - this.Description = Messages.ACTION_VM_COPIED; - - + Description = Messages.ACTION_VM_COPIED; } } } From 4f2a6f8995a014ce108be6a0716f231134ff90e6 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 14:31:08 +0100 Subject: [PATCH 05/62] CA-339273: Mention source and destination Host/Pool in VM migrate action Also removed useless `this` calls and tidied code Signed-off-by: Danilo Del Busso --- XenModel/Actions/VM/VMMigrateAction.cs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/XenModel/Actions/VM/VMMigrateAction.cs b/XenModel/Actions/VM/VMMigrateAction.cs index 9b5a9434a..f39d29181 100644 --- a/XenModel/Actions/VM/VMMigrateAction.cs +++ b/XenModel/Actions/VM/VMMigrateAction.cs @@ -42,10 +42,9 @@ namespace XenAdmin.Actions.VMActions public VMMigrateAction(VM vm, Host destinationHost) : base(vm.Connection, GetTitle(vm, destinationHost)) { - this.Description = Messages.ACTION_PREPARING; - this.VM = vm; - this.Host = destinationHost; - this.Pool = Core.Helpers.GetPool(vm.Connection); + VM = vm; + Host = destinationHost; + Pool = Helpers.GetPool(vm.Connection); } private static string GetTitle(VM vm, Host toHost) @@ -53,14 +52,14 @@ namespace XenAdmin.Actions.VMActions Host residentOn = vm.Connection.Resolve(vm.resident_on); return residentOn == null - ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.Name(), toHost.Name()) - : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), Helpers.GetName(residentOn), toHost.Name()); + ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.NameWithLocation(), toHost.NameWithLocation()) + : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), residentOn.NameWithLocation(), toHost.NameWithLocation()); } protected override void Run() { - this.Description = Messages.ACTION_VM_MIGRATING; - RelatedTask = XenAPI.VM.async_live_migrate(Session, VM.opaque_ref, Host.opaque_ref); + Description = Messages.ACTION_VM_MIGRATING; + RelatedTask = VM.async_live_migrate(Session, VM.opaque_ref, Host.opaque_ref); try { PollToCompletion(); @@ -68,17 +67,15 @@ namespace XenAdmin.Actions.VMActions catch (Failure f) { if (f.ErrorDescription.Count >= 5 && f.ErrorDescription[0] == "VM_MIGRATE_FAILED" - && f.ErrorDescription[4].Contains("VDI_MISSING")) + && f.ErrorDescription[4].Contains("VDI_MISSING")) { throw new Exception(Messages.MIGRATE_EJECT_TOOLS_ON_UPGRADE); } - else - { - throw; - } + + throw; } - this.Description = Messages.ACTION_VM_MIGRATED; + Description = Messages.ACTION_VM_MIGRATED; } } } From 73f1f620da7d10ac985a2a8ceb8ac77dacd4e652 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 14:46:34 +0100 Subject: [PATCH 06/62] CA-339273: Mention source Host/Pool in VM cross-pool migration and copy actions Also amended connected string resource and removed initial description. Signed-off-by: Danilo Del Busso --- XenModel/Actions/VM/VMCrossPoolMigrateAction.cs | 14 ++++++++------ XenModel/Messages.Designer.cs | 2 +- XenModel/Messages.resx | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs b/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs index efb15d9b2..ed57a6fb8 100644 --- a/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs +++ b/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs @@ -55,7 +55,6 @@ namespace XenAdmin.Actions.VMActions : base(vm.Connection, GetTitle(vm, destinationHost, copy)) { Session = vm.Connection.Session; - Description = Messages.ACTION_PREPARING; VM = vm; Host = destinationHost; Pool = Helpers.GetPool(vm.Connection); @@ -80,13 +79,16 @@ namespace XenAdmin.Actions.VMActions public static string GetTitle(VM vm, Host toHost, bool copy) { if (copy) - return string.Format(Messages.ACTION_VM_CROSS_POOL_COPY_TITLE, vm.Name(), toHost.Name()); + return string.Format(Messages.ACTION_VM_CROSS_POOL_COPY_TITLE, + vm.NameWithLocation(), + Helpers.GetPool(vm.Connection)?.Name() ?? vm.Connection.Name, + toHost.NameWithLocation()); Host residentOn = vm.Connection.Resolve(vm.resident_on); - + return residentOn == null - ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.Name(), toHost.Name()) - : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), Helpers.GetName(residentOn), toHost.Name()); + ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.NameWithLocation(), toHost.NameWithLocation()) + : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), residentOn.NameWithLocation(), toHost.NameWithLocation()); } protected override void Run() @@ -114,7 +116,7 @@ namespace XenAdmin.Actions.VMActions Description = string.Format(copy ? Messages.ACTION_VM_CROSS_POOL_COPY_CANCELLED : Messages.ACTION_VM_MIGRATE_CANCELLED, - VM.Name()); + VM.NameWithLocation()); throw; } catch (Failure ex) diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 83bcb7b50..31e99b5db 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -3067,7 +3067,7 @@ namespace XenAdmin { } /// - /// Looks up a localized string similar to Copying VM '{0}' to '{1}'. + /// Looks up a localized string similar to Copying VM '{0}' from '{1}' to '{2}'. /// public static string ACTION_VM_CROSS_POOL_COPY_TITLE { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 5fe154775..95ae0b5dd 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -1141,7 +1141,7 @@ Copying {0} canceled - Copying VM '{0}' to '{1}' + Copying VM '{0}' from '{1}' to '{2}' Deleting snapshots From 9af8efdc24a3dd220845c90a62a39a11b82b8766 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 10 Aug 2021 15:14:52 +0100 Subject: [PATCH 07/62] CA-339273: Mention destination Host/Pool in VM import action Also moved initial description update from base constructor call to body of subclass constructor. Signed-off-by: Danilo Del Busso --- XenModel/Actions/VM/ImportVmAction.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/XenModel/Actions/VM/ImportVmAction.cs b/XenModel/Actions/VM/ImportVmAction.cs index 44243619c..d5f728af1 100644 --- a/XenModel/Actions/VM/ImportVmAction.cs +++ b/XenModel/Actions/VM/ImportVmAction.cs @@ -72,9 +72,10 @@ namespace XenAdmin.Actions public ImportVmAction(IXenConnection connection, Host affinity, string filename, SR sr, Action warningDelegate, Action failureDiagnosisDelegate) - : base(connection, string.Format(Messages.IMPORTVM_TITLE, filename, Helpers.GetName(connection)), Messages.IMPORTVM_PREP) - { - Pool = Helpers.GetPoolOfOne(connection); + : base(connection, GetTitle(filename, connection, affinity)) + { + Description = Messages.IMPORTVM_PREP; + Pool = Helpers.GetPoolOfOne(connection); m_affinity = affinity; Host = affinity ?? connection.Resolve(Pool.master); SR = sr; @@ -96,6 +97,12 @@ namespace XenAdmin.Actions #endregion } + private static string GetTitle(string filename, IXenConnection connection, Host affinity) + { + var toHost = affinity ?? connection.Resolve(Helpers.GetPoolOfOne(connection).master); + return string.Format(Messages.IMPORTVM_TITLE, filename, toHost.NameWithLocation()); + } + protected override void Run() { SafeToExit = false; From 0ffee712b74f9be9a0a1a8a428bb4bc4fc75475f Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 12:06:38 +0100 Subject: [PATCH 08/62] CP-36392: Add `null` check to `connection` call in `ExternalPluginAction.cs` Also remove `null` check that always resolves to true Also tidy up code Signed-off-by: Danilo Del Busso --- .../Actions/GUIActions/ExternalPluginAction.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs b/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs index 3f9582c94..07d38da0c 100644 --- a/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs +++ b/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs @@ -246,11 +246,11 @@ namespace XenAdmin.Actions } // Returns a set of params which relate to the object you have selected in the treeview - private List RetrieveParams(IXenObject obj) + private IEnumerable RetrieveParams(IXenObject obj) { - IXenConnection connection = obj.Connection; - Host coordinator = connection != null ? Helpers.GetCoordinator(connection) : null; // get coordinator asserts connection is not null - string coordinatorAddress = EmptyParameter; + var connection = obj.Connection; + var coordinator = connection != null ? Helpers.GetCoordinator(connection) : null; // get coordinator asserts connection is not null + var coordinatorAddress = EmptyParameter; if (coordinator != null) { @@ -258,9 +258,9 @@ namespace XenAdmin.Actions WriteTrustedCertificates(coordinator.Connection); } - string sessionRef = connection.Session != null ? connection.Session.opaque_ref : EmptyParameter; - string objCls = obj != null ? obj.GetType().Name : EmptyParameter; - string objUuid = obj != null && connection.Session != null ? Helpers.GetUuid(obj) : EmptyParameter; + var sessionRef = connection?.Session != null ? connection.Session.opaque_ref : EmptyParameter; + var objCls = obj.GetType().Name; + var objUuid = connection?.Session != null ? Helpers.GetUuid(obj) : EmptyParameter; return new List(new string[] { coordinatorAddress, sessionRef, objCls, objUuid }); } From 3c70dacecc2d011077804d19647eb85505a653d8 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 12:57:48 +0100 Subject: [PATCH 09/62] CP-36392: Change condition that always evaluates to `false` in `WlbOptimizePoolAction` Also tidy up code within constructor Signed-off-by: Danilo Del Busso --- XenAdmin/Actions/GUIActions/Wlb/WlbOptimizePoolAction.cs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/XenAdmin/Actions/GUIActions/Wlb/WlbOptimizePoolAction.cs b/XenAdmin/Actions/GUIActions/Wlb/WlbOptimizePoolAction.cs index 950973880..a4c51b782 100644 --- a/XenAdmin/Actions/GUIActions/Wlb/WlbOptimizePoolAction.cs +++ b/XenAdmin/Actions/GUIActions/Wlb/WlbOptimizePoolAction.cs @@ -55,13 +55,8 @@ namespace XenAdmin.Actions.Wlb public WlbOptimizePoolAction(Pool pool, Dictionary vmOptLst, string optId) : base(pool.Connection, string.Format(Messages.WLB_OPTIMIZING_POOL, Helpers.GetName(pool).Ellipsise(50))) { - if (pool == null) - throw new ArgumentNullException("pool"); - if (vmOptLst == null) - throw new ArgumentNullException("vmOptLst"); - - this.Pool = pool; - this.vmOptList = vmOptLst; + Pool = pool; + vmOptList = vmOptLst ?? throw new ArgumentNullException("vmOptLst"); this.optId = optId; #region RBAC Dependencies From f7c6984e6c9befb8e77fc1649e2b834d43c6016c Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 13:12:21 +0100 Subject: [PATCH 10/62] CP-36392: Update `CanRunCore` to reflect logic as described in comment Also addresses unreachable code block Also use `var` keywoard to tidy up code Signed-off-by: Danilo Del Busso --- .../Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs b/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs index 9f1d32218..e8ad4137b 100644 --- a/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs +++ b/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs @@ -99,16 +99,17 @@ namespace XenAdmin.Commands IXenConnection connection = null; - bool atLeastOneCanRun = false; - foreach (SelectedItem item in selection) + var atLeastOneCanRun = false; + foreach (var item in selection) { - VM vm = (VM)item.XenObject; + var vm = (VM)item.XenObject; // all VMs must be on the same connection if (connection != null && vm.Connection != connection) { return false; } + connection = vm.Connection; if (CanRun(item)) { From aa038cf0fcebe871ee123c5b3fe84069a5b40cfc Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 13:15:33 +0100 Subject: [PATCH 11/62] CP-36392: Remove condition that always evaluates to `false` Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/DragDropMigrateVMCommand.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenAdmin/Commands/DragDropMigrateVMCommand.cs b/XenAdmin/Commands/DragDropMigrateVMCommand.cs index a7422f6a7..088595875 100644 --- a/XenAdmin/Commands/DragDropMigrateVMCommand.cs +++ b/XenAdmin/Commands/DragDropMigrateVMCommand.cs @@ -140,7 +140,7 @@ namespace XenAdmin.Commands if(!LiveMigrateAllowedInVersion(targetHost, draggedVM)) { - Pool targetPool = targetHost == null ? null : Helpers.GetPool(targetHost.Connection); + Pool targetPool = Helpers.GetPool(targetHost.Connection); if(targetPool == null) return false; From 3ffd370d81b161b691bfbb9f7fb8d25432660388 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 13:21:52 +0100 Subject: [PATCH 12/62] CP-36392: Remove unused conditional structure in `VNCTabView` If check is virtually useless here Signed-off-by: Danilo Del Busso --- XenAdmin/ConsoleView/VNCTabView.cs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/XenAdmin/ConsoleView/VNCTabView.cs b/XenAdmin/ConsoleView/VNCTabView.cs index df4bb563b..7277fa8fc 100644 --- a/XenAdmin/ConsoleView/VNCTabView.cs +++ b/XenAdmin/ConsoleView/VNCTabView.cs @@ -711,18 +711,10 @@ namespace XenAdmin.ConsoleView } else if (source.power_state == vm_power_state.Paused) { - if (source.allowed_operations.Contains(vm_operations.unpause)) - { - //EnablePowerStateLabel(Messages.CONSOLE_POWER_STATE_PAUSED_UNPAUSE); - // CA-12637: Pause/UnPause is not supported in the GUI. Comment out - // the EnablePowerStateLabel because it gives the appearance that we - // support unpause via the GUI. - DisablePowerStateLabel(Messages.CONSOLE_POWER_STATE_PAUSED); - } - else - { - DisablePowerStateLabel(Messages.CONSOLE_POWER_STATE_PAUSED); - } + // CA-12637: Pause/UnPause is not supported in the GUI. Comment out + // the EnablePowerStateLabel because it gives the appearance that we + // support unpause via the GUI. + DisablePowerStateLabel(Messages.CONSOLE_POWER_STATE_PAUSED); } else if (source.power_state == vm_power_state.Suspended) { From f908abe28d60c99aa19df4a899c8de9f5db090ce Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 13:24:56 +0100 Subject: [PATCH 13/62] CP-36392: Refactor useless for loop into if statement in `ConsolePanel.cs` For loop is acting as if block Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/ConsolePanel.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/XenAdmin/Controls/ConsolePanel.cs b/XenAdmin/Controls/ConsolePanel.cs index 10faf287e..cf3ea7323 100644 --- a/XenAdmin/Controls/ConsolePanel.cs +++ b/XenAdmin/Controls/ConsolePanel.cs @@ -310,10 +310,9 @@ namespace XenAdmin.Controls // find the pair in vncViews and start timer on the vm var views = vncViews.Where(kvp => kvp.Value == vncView).ToList(); - foreach (var kvp in views) + if (views.Count > 0) { - StartCloseVNCTimer(kvp.Key); - break; + StartCloseVNCTimer(views.First().Key); } } From 825c795ea4ac698a6a134f34f650ba85e264ceb8 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 14 Sep 2021 13:27:40 +0100 Subject: [PATCH 14/62] CP-36392: Refactor for loop into `FirstOrDefault` expression Improves readability Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/CustomDataGraph/DataKey.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/XenAdmin/Controls/CustomDataGraph/DataKey.cs b/XenAdmin/Controls/CustomDataGraph/DataKey.cs index f9622b2c6..633a0b702 100644 --- a/XenAdmin/Controls/CustomDataGraph/DataKey.cs +++ b/XenAdmin/Controls/CustomDataGraph/DataKey.cs @@ -300,11 +300,7 @@ namespace XenAdmin.Controls.CustomDataGraph { get { - foreach (DataSet s in Sets.Values) - { - return s.CustomYRange; - } - return null; + return Sets.Values.Select(s => s.CustomYRange).FirstOrDefault(); } } From 2d1e6dcb92178b2620d7ef6ef5d1e03e918c92bd Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 15 Sep 2021 13:54:45 +0100 Subject: [PATCH 15/62] CP-36392: Remove `base` calls directly based on the object reference. Two objects will never have the same hash since base methods are based on direct object reference Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/CustomDataGraph/DataSet.cs | 10 +++------- XenAdmin/Controls/CustomGridView/GridRow.cs | 8 ++++---- .../PoolHostDataGridViewOneCheckboxRow.cs | 2 +- XenAdmin/Controls/XenSearch/QueryElement.cs | 4 ++-- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/XenAdmin/Controls/CustomDataGraph/DataSet.cs b/XenAdmin/Controls/CustomDataGraph/DataSet.cs index 615edc016..0044581b7 100644 --- a/XenAdmin/Controls/CustomDataGraph/DataSet.cs +++ b/XenAdmin/Controls/CustomDataGraph/DataSet.cs @@ -478,19 +478,15 @@ namespace XenAdmin.Controls.CustomDataGraph public override bool Equals(object obj) { - if(!(obj is DataSet)) - return base.Equals(obj); - - DataSet other = (DataSet)obj; + if (!(obj is DataSet other)) + return false; return Id == other.Id; } public override int GetHashCode() { - if (string.IsNullOrEmpty(Id)) - return base.GetHashCode(); - return Id.GetHashCode(); + return string.IsNullOrEmpty(Id) ? 0 : Id.GetHashCode(); } internal void InsertPointCollection(List list) diff --git a/XenAdmin/Controls/CustomGridView/GridRow.cs b/XenAdmin/Controls/CustomGridView/GridRow.cs index 78c38d3ce..0f2da5ce5 100644 --- a/XenAdmin/Controls/CustomGridView/GridRow.cs +++ b/XenAdmin/Controls/CustomGridView/GridRow.cs @@ -678,14 +678,14 @@ namespace XenAdmin.Controls.CustomGridView public override bool Equals(object obj) { - if(!(obj is GridRow)) - return base.Equals(obj); - return OpaqueRef == ((GridRow)obj).OpaqueRef; + if (!(obj is GridRow row)) + return false; + return OpaqueRef == row.OpaqueRef; } public override int GetHashCode() { - return base.GetHashCode(); + return (OpaqueRef != null ? OpaqueRef.GetHashCode() : 0); } } diff --git a/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs b/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs index 9b1ccbbef..c215cd51f 100644 --- a/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs +++ b/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs @@ -128,7 +128,7 @@ namespace XenAdmin.Controls.DataGridViewEx public override int GetHashCode() { - return base.GetHashCode(); + return _nameCell.GetHashCode(); } public CheckState Checked diff --git a/XenAdmin/Controls/XenSearch/QueryElement.cs b/XenAdmin/Controls/XenSearch/QueryElement.cs index 1bbd50e59..c101463e3 100644 --- a/XenAdmin/Controls/XenSearch/QueryElement.cs +++ b/XenAdmin/Controls/XenSearch/QueryElement.cs @@ -1121,7 +1121,7 @@ namespace XenAdmin.Controls.XenSearch public override int GetHashCode() { - return base.GetHashCode(); + return (int) type; } } @@ -1327,7 +1327,7 @@ namespace XenAdmin.Controls.XenSearch public override int GetHashCode() { - return base.GetHashCode(); + return (int) type; } } From c9e65a300094d32af5e2ae7e6f9a2d8bde3ffe02 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 15 Sep 2021 14:47:26 +0100 Subject: [PATCH 16/62] CP-36392: Refactor for loop into if statement For loop acts as if statement. Changed to address static analysis flag. Signed-off-by: Danilo Del Busso --- XenOvfApi/Conversions.cs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/XenOvfApi/Conversions.cs b/XenOvfApi/Conversions.cs index bbbb8befa..005b80bcd 100644 --- a/XenOvfApi/Conversions.cs +++ b/XenOvfApi/Conversions.cs @@ -486,10 +486,16 @@ namespace XenOvf try { searcher = new ManagementObjectSearcher(@"select * from Win32_ComputerSystem"); - foreach (ManagementObject mgtobj in searcher.Get()) + var mgtObjs = searcher.Get(); + + // only want one. + if (mgtObjs.Count > 0) { - Win32_ComputerSystem = mgtobj; // only want one. - break; + using (var iterator = mgtObjs.GetEnumerator()) + { + iterator.MoveNext(); + Win32_ComputerSystem = (ManagementObject) iterator.Current; + } } log.Debug("OVF.CollectionInformation Win32_ComputerSystem.1"); } @@ -511,11 +517,18 @@ namespace XenOvf try { searcher = new ManagementObjectSearcher(@"select * from Win32_Processor"); - foreach (ManagementObject mgtobj in searcher.Get()) + var mgtObjs = searcher.Get(); + + // only want one. + if (mgtObjs.Count > 0) { - Win32_Processor.Add(mgtobj); // only want one. - break; + using (var iterator = mgtObjs.GetEnumerator()) + { + iterator.MoveNext(); + Win32_Processor.Add((ManagementObject) iterator.Current); + } } + log.DebugFormat("OVF.CollectionInformation Win32_Processor.{0}", Win32_Processor.Count); } catch (Exception ex) From 062371762729ab121a4ef9dcd04836a422c63c45 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 15 Sep 2021 15:08:45 +0100 Subject: [PATCH 17/62] CP-36392: Replace custom Utils method with direct calls `ThrowIfEnumerableParameterNullOrEmpty` adds complexity Signed-off-by: Danilo Del Busso --- .../Controls/VMOperationToolStripMenuItem.cs | 2 +- XenAdmin/Commands/Controls/WlbRecommendations.cs | 3 ++- XenAdmin/Dialogs/RepairSRDialog.cs | 4 +++- XenModel/Actions/Host/ApplyLicenseEditionAction.cs | 6 ++++-- XenModel/Utils/Util.cs | 14 -------------- 5 files changed, 10 insertions(+), 19 deletions(-) diff --git a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs index 600e6350c..284ed42f1 100644 --- a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs +++ b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs @@ -167,7 +167,7 @@ namespace XenAdmin.Commands retrieveVmRecommendationsAction.Completed += delegate { if (Stopped || retrieveVmRecommendationsAction.Cancelled || - !retrieveVmRecommendationsAction.Succeeded) + !retrieveVmRecommendationsAction.Succeeded || vms == null || vms.Count == 0) return; var recommendations = new WlbRecommendations(vms, retrieveVmRecommendationsAction.Recommendations); diff --git a/XenAdmin/Commands/Controls/WlbRecommendations.cs b/XenAdmin/Commands/Controls/WlbRecommendations.cs index 435794d23..6a679a03a 100644 --- a/XenAdmin/Commands/Controls/WlbRecommendations.cs +++ b/XenAdmin/Commands/Controls/WlbRecommendations.cs @@ -54,7 +54,8 @@ namespace XenAdmin.Commands /// public WlbRecommendations(List vms, Dictionary, string[]>> recommendations) { - Util.ThrowIfEnumerableParameterNullOrEmpty(vms, "vms"); + if (vms == null || vms.Count == 0) + throw new ArgumentException(@"Parameter cannot be null or empty", nameof(vms)); _vms = new ReadOnlyCollection(vms); _recommendations = recommendations; diff --git a/XenAdmin/Dialogs/RepairSRDialog.cs b/XenAdmin/Dialogs/RepairSRDialog.cs index 1a0373855..d57e77393 100644 --- a/XenAdmin/Dialogs/RepairSRDialog.cs +++ b/XenAdmin/Dialogs/RepairSRDialog.cs @@ -75,7 +75,9 @@ namespace XenAdmin.Dialogs /// public RepairSRDialog(IEnumerable srs, bool runAction = true) { - Util.ThrowIfEnumerableParameterNullOrEmpty(srs, "srs"); + if (srs == null || !srs.Any()) + throw new ArgumentException("Parameter cannot be null or empty", nameof(srs)); + this.runAction = runAction; BoldFont = new Font(Font, FontStyle.Bold); List srList = new List(srs); diff --git a/XenModel/Actions/Host/ApplyLicenseEditionAction.cs b/XenModel/Actions/Host/ApplyLicenseEditionAction.cs index f4404cc20..769229e76 100644 --- a/XenModel/Actions/Host/ApplyLicenseEditionAction.cs +++ b/XenModel/Actions/Host/ApplyLicenseEditionAction.cs @@ -65,9 +65,11 @@ namespace XenAdmin.Actions Action, string> DoOnLicensingFailure) : base(null, Messages.LICENSE_UPDATING_LICENSES) { - LicenseFailures = new List(); - Util.ThrowIfEnumerableParameterNullOrEmpty(xos, "xenobjects"); + if (xos == null || !xos.Any()) + throw new ArgumentException(@"Parameter cannot be null or empty", nameof(xos)); + LicenseFailures = new List(); + _edition = edition; this.xos = xos; _licenseServerAddress = licenseServerAddress; diff --git a/XenModel/Utils/Util.cs b/XenModel/Utils/Util.cs index c04161159..6bd281da4 100644 --- a/XenModel/Utils/Util.cs +++ b/XenModel/Utils/Util.cs @@ -476,20 +476,6 @@ namespace XenAdmin } } - public static void ThrowIfEnumerableParameterNullOrEmpty(IEnumerable value, string name) - { - ThrowIfParameterNull(value, name); - -#pragma warning disable 0168 - foreach (object _ in value) - { - return; - } -#pragma warning restore 0168 - - ThrowBecauseZeroLength(name); - } - private static void ThrowBecauseZeroLength(string name) { throw new ArgumentException(string.Format("{0} cannot have 0 length.", name), name); From df53a4cd980c60afde5b3efa78444571cc533b49 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 15 Sep 2021 15:47:20 +0100 Subject: [PATCH 18/62] CP-36392: Refactor useless null checks in actions constructors Also remove useless `this` usage Signed-off-by: Danilo Del Busso --- XenAdmin/Dialogs/ControlDomainMemoryDialog.cs | 2 -- XenModel/Actions/Host/EnableHostAction.cs | 4 +--- XenModel/Actions/Host/EvacuateHostAction.cs | 2 -- XenModel/Actions/Host/RebootHostAction.cs | 4 +--- XenModel/Actions/Host/ShutdownHostAction.cs | 2 -- XenModel/Actions/Pool/EnableHAAction.cs | 4 +--- .../Actions/Pool_Patch/CheckDiskSpaceForPatchUploadAction.cs | 2 -- XenModel/Actions/Pool_Patch/CleanupDiskSpaceAction.cs | 2 -- XenModel/Actions/Pool_Patch/GetDiskSpaceRequirementsAction.cs | 2 -- XenModel/Actions/Pool_Patch/PoolPatchCleanAction.cs | 2 -- XenModel/Actions/SR/SrRepairAction.cs | 4 +--- 11 files changed, 4 insertions(+), 26 deletions(-) diff --git a/XenAdmin/Dialogs/ControlDomainMemoryDialog.cs b/XenAdmin/Dialogs/ControlDomainMemoryDialog.cs index 4522324ce..090ff451f 100644 --- a/XenAdmin/Dialogs/ControlDomainMemoryDialog.cs +++ b/XenAdmin/Dialogs/ControlDomainMemoryDialog.cs @@ -50,8 +50,6 @@ namespace XenAdmin.Dialogs public ControlDomainMemoryDialog(Host host) : base(host.Connection) { - if (host == null) throw new ArgumentNullException("host"); - InitializeComponent(); this.host = host; this.host.PropertyChanged += Server_PropertyChanged; diff --git a/XenModel/Actions/Host/EnableHostAction.cs b/XenModel/Actions/Host/EnableHostAction.cs index ebc07ffe3..d178fb753 100644 --- a/XenModel/Actions/Host/EnableHostAction.cs +++ b/XenModel/Actions/Host/EnableHostAction.cs @@ -44,10 +44,8 @@ namespace XenAdmin.Actions public EnableHostAction(Host host, bool resumeVMs,Func acceptNTolChangesOnEnable) : base(host.Connection, Messages.HOST_ENABLE, Messages.WAITING, null, acceptNTolChangesOnEnable) { - if (host == null) - throw new ArgumentNullException("host"); _resumeVMs = resumeVMs; - this.Host = host; + Host = host; AddCommonAPIMethodsToRoleCheck(); ApiMethodsToRoleCheck.Add("pool.ha_compute_hypothetical_max_host_failures_to_tolerate"); ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate"); diff --git a/XenModel/Actions/Host/EvacuateHostAction.cs b/XenModel/Actions/Host/EvacuateHostAction.cs index 2dc5e3a51..461557976 100644 --- a/XenModel/Actions/Host/EvacuateHostAction.cs +++ b/XenModel/Actions/Host/EvacuateHostAction.cs @@ -60,8 +60,6 @@ namespace XenAdmin.Actions public EvacuateHostAction(Host host, Host newCoordinator, Dictionary, String[]> hostRecommendations, Func acceptNTolChanges, Func acceptNTolChangesOnEnable) : base(host.Connection, null, Messages.HOST_EVACUATE, acceptNTolChanges, acceptNTolChangesOnEnable) { - if (host == null) - throw new ArgumentNullException("host"); Host = host; _newCoordinator = newCoordinator; _hostRecommendations = hostRecommendations; diff --git a/XenModel/Actions/Host/RebootHostAction.cs b/XenModel/Actions/Host/RebootHostAction.cs index 15ca51340..0650d163d 100644 --- a/XenModel/Actions/Host/RebootHostAction.cs +++ b/XenModel/Actions/Host/RebootHostAction.cs @@ -50,9 +50,7 @@ namespace XenAdmin.Actions public RebootHostAction(Host host, Func acceptNTolChanges) : base(host.Connection, Messages.HOST_REBOOTING, Messages.WAITING, acceptNTolChanges, null) { - if (host == null) - throw new ArgumentNullException("host"); - this.Host = host; + Host = host; AddCommonAPIMethodsToRoleCheck(); ApiMethodsToRoleCheck.Add("pool.ha_compute_hypothetical_max_host_failures_to_tolerate"); ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate"); diff --git a/XenModel/Actions/Host/ShutdownHostAction.cs b/XenModel/Actions/Host/ShutdownHostAction.cs index 9d819f386..99250f2be 100644 --- a/XenModel/Actions/Host/ShutdownHostAction.cs +++ b/XenModel/Actions/Host/ShutdownHostAction.cs @@ -44,8 +44,6 @@ namespace XenAdmin.Actions public ShutdownHostAction(Host host, Func acceptNTolChanges) : base(host.Connection, Messages.HOST_SHUTDOWN, Messages.WAITING, acceptNTolChanges, null) { - if (host == null) - throw new ArgumentNullException("host"); Host = host; ApiMethodsToRoleCheck.Add("pool.ha_compute_hypothetical_max_host_failures_to_tolerate"); ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate"); diff --git a/XenModel/Actions/Pool/EnableHAAction.cs b/XenModel/Actions/Pool/EnableHAAction.cs index 6015b1be1..e571646a6 100644 --- a/XenModel/Actions/Pool/EnableHAAction.cs +++ b/XenModel/Actions/Pool/EnableHAAction.cs @@ -49,12 +49,10 @@ namespace XenAdmin.Actions public EnableHAAction(Pool pool, Dictionary startupOptions, List heartbeatSRs, long failuresToTolerate) : base(pool.Connection, string.Format(Messages.ENABLING_HA_ON, Helpers.GetName(pool).Ellipsise(50)), Messages.ENABLING_HA, false) { - if (pool == null) - throw new ArgumentNullException("pool"); if (heartbeatSRs.Count == 0) throw new ArgumentException("You must specify at least 1 heartbeat SR"); - this.Pool = pool; + Pool = pool; this.startupOptions = startupOptions; this.heartbeatSRs = heartbeatSRs.ToArray(); this.failuresToTolerate = failuresToTolerate; diff --git a/XenModel/Actions/Pool_Patch/CheckDiskSpaceForPatchUploadAction.cs b/XenModel/Actions/Pool_Patch/CheckDiskSpaceForPatchUploadAction.cs index 40c6c885f..e340d4591 100644 --- a/XenModel/Actions/Pool_Patch/CheckDiskSpaceForPatchUploadAction.cs +++ b/XenModel/Actions/Pool_Patch/CheckDiskSpaceForPatchUploadAction.cs @@ -57,8 +57,6 @@ namespace XenAdmin.Actions public CheckDiskSpaceForPatchUploadAction(Host host, string fileName, long size, bool suppressHistory) : base(host.Connection, Messages.ACTION_CHECK_DISK_SPACE_TITLE, "", suppressHistory) { - if (host == null) - throw new ArgumentNullException("host"); Host = host; this.fileName = fileName; fileSize = size; diff --git a/XenModel/Actions/Pool_Patch/CleanupDiskSpaceAction.cs b/XenModel/Actions/Pool_Patch/CleanupDiskSpaceAction.cs index 970c1d4e1..9e2e58199 100644 --- a/XenModel/Actions/Pool_Patch/CleanupDiskSpaceAction.cs +++ b/XenModel/Actions/Pool_Patch/CleanupDiskSpaceAction.cs @@ -45,8 +45,6 @@ namespace XenAdmin.Actions public CleanupDiskSpaceAction(Host host, Pool_patch excludedPatch, bool suppressHistory) : base(host.Connection, Messages.ACTION_CLEANUP_DISK_SPACE_TITLE, "", suppressHistory) { - if (host == null) - throw new ArgumentNullException("host"); Host = host; this.excludedPatch = excludedPatch; } diff --git a/XenModel/Actions/Pool_Patch/GetDiskSpaceRequirementsAction.cs b/XenModel/Actions/Pool_Patch/GetDiskSpaceRequirementsAction.cs index 0da640e40..5b31a72a5 100644 --- a/XenModel/Actions/Pool_Patch/GetDiskSpaceRequirementsAction.cs +++ b/XenModel/Actions/Pool_Patch/GetDiskSpaceRequirementsAction.cs @@ -81,8 +81,6 @@ namespace XenAdmin.Actions public GetDiskSpaceRequirementsAction(Host host, string updateName, long size, bool suppressHistory) : base(host.Connection, Messages.ACTION_GET_DISK_SPACE_REQUIREMENTS_TITLE, suppressHistory) { - if (host == null) - throw new ArgumentNullException("host"); Host = host; this.updateName = updateName; updateSize = size; diff --git a/XenModel/Actions/Pool_Patch/PoolPatchCleanAction.cs b/XenModel/Actions/Pool_Patch/PoolPatchCleanAction.cs index 698458436..1806f45e2 100644 --- a/XenModel/Actions/Pool_Patch/PoolPatchCleanAction.cs +++ b/XenModel/Actions/Pool_Patch/PoolPatchCleanAction.cs @@ -43,8 +43,6 @@ namespace XenAdmin.Actions : base(pool.Connection, string.Format(Messages.UPDATES_WIZARD_REMOVING_UPDATE, patch.Name(), pool.Name()), suppressHistory) { this.patch = patch; - if (patch == null) - throw new ArgumentNullException("patch"); #region RBAC Dependencies ApiMethodsToRoleCheck.Add("pool_patch.pool_clean"); diff --git a/XenModel/Actions/SR/SrRepairAction.cs b/XenModel/Actions/SR/SrRepairAction.cs index 4568f45e6..16a6058b4 100644 --- a/XenModel/Actions/SR/SrRepairAction.cs +++ b/XenModel/Actions/SR/SrRepairAction.cs @@ -55,10 +55,8 @@ namespace XenAdmin.Actions public SrRepairAction(IXenConnection connection, SR sr,bool isSharedAction) : base(connection, isSharedAction ? string.Format(Messages.ACTION_SR_SHARING, sr.NameWithoutHost()) : string.Format(Messages.ACTION_SR_REPAIRING, sr.NameWithoutHost())) { - if (sr == null) - throw new ArgumentNullException("sr"); this.isSharedAction = isSharedAction; - this.SR = sr; + SR = sr; #region RBAC Dependencies ApiMethodsToRoleCheck.Add("pbd.plug"); From cfc7bd0ef931fae210920936bc51c22bb5c0fc54 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Fri, 1 Oct 2021 12:31:13 +0100 Subject: [PATCH 19/62] CP-36392: Update RebootPlanAction.cs to lock on a dedicated object instance Use dedicated instance to avoid deadlocks or lock contention Also fix typo and rename `private` variable Signed-off-by: Danilo Del Busso --- .../PlanActions/RebootPlanAction.cs | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/XenAdmin/Wizards/PatchingWizard/PlanActions/RebootPlanAction.cs b/XenAdmin/Wizards/PatchingWizard/PlanActions/RebootPlanAction.cs index 152f521a8..fe940b0ca 100644 --- a/XenAdmin/Wizards/PatchingWizard/PlanActions/RebootPlanAction.cs +++ b/XenAdmin/Wizards/PatchingWizard/PlanActions/RebootPlanAction.cs @@ -39,7 +39,8 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions public abstract class RebootPlanAction : HostPlanAction { private bool _cancelled; - private bool lostConnection; + private bool _lostConnection; + private readonly object _lockObj = new object(); protected RebootPlanAction(Host host) : base(host) @@ -50,9 +51,9 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions { _cancelled = true; - lock (this) + lock (_lockObj) { - Monitor.PulseAll(this); + Monitor.PulseAll(_lockObj); } } @@ -98,7 +99,7 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions { bool isCoordinator = GetResolvedHost().IsCoordinator(); - lostConnection = false; + _lostConnection = false; _cancelled = false; double metric = metricDelegate(session, HostXenRef.opaque_ref); @@ -134,7 +135,7 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions Connection.SuppressErrors = true; // - // Wait for a dissconnection + // Wait for a disconnection // WaitForDisconnection(); @@ -165,11 +166,11 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions { log.DebugFormat("{0}._WaitForReboot waiting for connection to go away...", GetType().Name); - lock (this) + lock (_lockObj) { - while (!lostConnection && !_cancelled) + while (!_lostConnection && !_cancelled) { - Monitor.Wait(this); + Monitor.Wait(_lockObj); } } @@ -274,10 +275,10 @@ namespace XenAdmin.Wizards.PatchingWizard.PlanActions private void connection_ConnectionLost(IXenConnection conn) { - lock (this) + lock (_lockObj) { - lostConnection = true; - Monitor.PulseAll(this); + _lostConnection = true; + Monitor.PulseAll(_lockObj); } } } From 02aa50f7a8caf270c5eeed9581f2881bb6ecbfa6 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Fri, 1 Oct 2021 14:44:55 +0100 Subject: [PATCH 20/62] CP-36392: Refactor conditions that result in unreachable code blocks Also tidy up surrounding code Signed-off-by: Danilo Del Busso --- .../Controls/NetworkingTab/NetworkList.cs | 7 ----- XenAdmin/TabPages/PvsPage.cs | 22 +++++++------- .../Actions/DR/ShutdownAndDestroyVMsAction.cs | 4 --- XenModel/XenSearch/QueryTypes.cs | 30 +++++++++++-------- 4 files changed, 28 insertions(+), 35 deletions(-) diff --git a/XenAdmin/Controls/NetworkingTab/NetworkList.cs b/XenAdmin/Controls/NetworkingTab/NetworkList.cs index 62dc98a5d..0a358ce04 100644 --- a/XenAdmin/Controls/NetworkingTab/NetworkList.cs +++ b/XenAdmin/Controls/NetworkingTab/NetworkList.cs @@ -305,8 +305,6 @@ namespace XenAdmin.Controls.NetworkingTab } NetworksGridView.Rows.AddRange(vifRowsToAdd.ToArray()); - bool selected = true; - if (selectedVIF != null) { foreach (VifRow row in NetworksGridView.Rows) @@ -319,11 +317,6 @@ namespace XenAdmin.Controls.NetworkingTab } } } - - if (!selected && NetworksGridView.Rows.Count > 0) - { - NetworksGridView.Rows[0].Selected = true; - } } else if (XenObject is Host || XenObject is Pool) { diff --git a/XenAdmin/TabPages/PvsPage.cs b/XenAdmin/TabPages/PvsPage.cs index 875ef8626..d7eee2122 100644 --- a/XenAdmin/TabPages/PvsPage.cs +++ b/XenAdmin/TabPages/PvsPage.cs @@ -231,17 +231,17 @@ namespace XenAdmin.TabPages { vm.PropertyChanged -= VmPropertyChanged; vm.PropertyChanged += VmPropertyChanged; - if (pvsProxy != null) - { - pvsProxy.PropertyChanged -= PvsProxyPropertyChanged; - pvsProxy.PropertyChanged += PvsProxyPropertyChanged; - PVS_site pvsSite = pvsProxy == null ? null : Connection.Resolve(pvsProxy.site); - if (pvsSite != null) - { - pvsSite.PropertyChanged -= PvsSitePropertyChanged; - pvsSite.PropertyChanged += PvsSitePropertyChanged; - } - } + + if (pvsProxy == null) + return; + pvsProxy.PropertyChanged -= PvsProxyPropertyChanged; + pvsProxy.PropertyChanged += PvsProxyPropertyChanged; + + var pvsSite = Connection.Resolve(pvsProxy.site); + if (pvsSite == null) + return; + pvsSite.PropertyChanged -= PvsSitePropertyChanged; + pvsSite.PropertyChanged += PvsSitePropertyChanged; } private void UnregisterVmEventHandlers() diff --git a/XenModel/Actions/DR/ShutdownAndDestroyVMsAction.cs b/XenModel/Actions/DR/ShutdownAndDestroyVMsAction.cs index c2e978dba..ab84fc2b2 100644 --- a/XenModel/Actions/DR/ShutdownAndDestroyVMsAction.cs +++ b/XenModel/Actions/DR/ShutdownAndDestroyVMsAction.cs @@ -84,7 +84,6 @@ namespace XenAdmin.Actions.DR internal static void DestroyVM(Session session, VM vm) { - Exception caught = null; log.DebugFormat("Destroying VM '{0}'", vm.Name()); if (vm.snapshots.Count > 0) @@ -143,9 +142,6 @@ namespace XenAdmin.Actions.DR } log.DebugFormat("VM '{0}' destroyed", vm.Name()); - - if (caught != null) - throw caught; } } } diff --git a/XenModel/XenSearch/QueryTypes.cs b/XenModel/XenSearch/QueryTypes.cs index 7ae873d7b..612ed13a3 100644 --- a/XenModel/XenSearch/QueryTypes.cs +++ b/XenModel/XenSearch/QueryTypes.cs @@ -481,27 +481,31 @@ namespace XenAdmin.XenSearch // item doesn't use a Server). public override bool? MatchProperty(List list) { - bool seenFalse = false; - bool seenNull = false; - foreach (T o in list) + var seenFalse = false; + var seenNull = false; + foreach (var o in list) { if (o != null) { - bool? b = subQuery.Match(o); - if (b == true) - return true; - else if (b == false) - seenFalse = true; - else - seenNull = true; + var b = subQuery.Match(o); + switch (b) + { + case true: + return true; + case false: + seenFalse = true; + break; + default: + seenNull = true; + break; + } } } if (seenFalse) return false; - else if (seenNull) + if (seenNull) return null; - else - return false; + return false; } } From 408cf98add73ecc89bfa64dda4c9506f27e6c457 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Fri, 1 Oct 2021 15:06:20 +0100 Subject: [PATCH 21/62] CP-36392: Add miscellaneous null checks Also tidy up code Also remove method in `SnapshotTreeView.cs` that wasn't used, which necessitated a null check Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/SnapshotTreeView.cs | 11 ---- .../Controls/TreeViews/FlickerFreeTreeView.cs | 2 +- .../XenSearch/ResourceSelectButton.cs | 7 +-- XenAdmin/Dialogs/ActionProgressDialog.cs | 4 +- XenAdmin/Dialogs/AddServerDialog.cs | 53 ++++++++++--------- 5 files changed, 35 insertions(+), 42 deletions(-) diff --git a/XenAdmin/Controls/SnapshotTreeView.cs b/XenAdmin/Controls/SnapshotTreeView.cs index 122e0a5d0..4ac183d0c 100644 --- a/XenAdmin/Controls/SnapshotTreeView.cs +++ b/XenAdmin/Controls/SnapshotTreeView.cs @@ -336,17 +336,6 @@ namespace XenAdmin.Controls [DllImport("user32.dll")] internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Win32.POINT pt); - - - public override Size GetPreferredSize(Size proposedSize) - { - if (root == null && Parent != null) - { - return DefaultSize; - } - return new Size(root.SubtreeWidth, root.SubtreeHeight); - } - #endregion #region Drawing diff --git a/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs b/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs index 0e2f355d0..090a93895 100644 --- a/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs +++ b/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs @@ -157,7 +157,7 @@ namespace XenAdmin.Controls { VirtualTreeNode.PersistenceInfo info = new VirtualTreeNode.PersistenceInfo(node); - if (!_persistedSelectionInfo.Contains(info)) + if (_persistedSelectionInfo != null && !_persistedSelectionInfo.Contains(info)) { // selection is different to old one. So fire an event. diff --git a/XenAdmin/Controls/XenSearch/ResourceSelectButton.cs b/XenAdmin/Controls/XenSearch/ResourceSelectButton.cs index 74210b619..af4df4ccc 100644 --- a/XenAdmin/Controls/XenSearch/ResourceSelectButton.cs +++ b/XenAdmin/Controls/XenSearch/ResourceSelectButton.cs @@ -139,11 +139,8 @@ namespace XenAdmin.Controls.XenSearch public void Populate(Search search) { ClearItems(); - if (search != null && search.Query != null) - scope = search.Query.QueryScope; - else - scope = null; - search.PopulateAdapters(this); + scope = search?.Query?.QueryScope; + search?.PopulateAdapters(this); } } } \ No newline at end of file diff --git a/XenAdmin/Dialogs/ActionProgressDialog.cs b/XenAdmin/Dialogs/ActionProgressDialog.cs index 18cf55cb8..5f0c2b37d 100644 --- a/XenAdmin/Dialogs/ActionProgressDialog.cs +++ b/XenAdmin/Dialogs/ActionProgressDialog.cs @@ -138,7 +138,9 @@ namespace XenAdmin.Dialogs var multipleAction = action as MultipleAction; labelSubActionStatus.Visible = multipleAction != null && multipleAction.ShowSubActionsDetails; if (labelSubActionStatus.Visible) - UpdateLabel(labelSubActionStatus, multipleAction.SubActionDescription, multipleAction.SubActionTitle); + { + UpdateLabel(labelSubActionStatus, multipleAction?.SubActionDescription, multipleAction?.SubActionTitle); + } } private void action_Completed(ActionBase sender) diff --git a/XenAdmin/Dialogs/AddServerDialog.cs b/XenAdmin/Dialogs/AddServerDialog.cs index 34a99bc2a..e0e94fbc3 100644 --- a/XenAdmin/Dialogs/AddServerDialog.cs +++ b/XenAdmin/Dialogs/AddServerDialog.cs @@ -137,31 +137,36 @@ namespace XenAdmin.Dialogs ServerNameComboBox.Enabled = true; AddButton.Text = Messages.ADD; } - if (_changedPass && connection.Password == null) + else { - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = Messages.CONNECT_TO_SERVER_BLURB; - labelError.Text = ""; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.CONNECT; - } - else if (_changedPass && connection.ExpectPasswordIsCorrect) - { - // This situation should be rare, it normally comes from logging in a new session after an existing one has been made - // We now use duplicate sessions instead most of the time which don't log in again. - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = string.Format(Messages.ADDSERVER_PASS_NEW, BrandManager.BrandConsole); - labelError.Text = ""; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.OK; - } - else if (_changedPass) // the password probably hasnt actually changed but we do know the user has typed it in wrong - { - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = string.Format(Messages.ERROR_CONNECTING_BLURB, BrandManager.BrandConsole); - labelError.Text = Messages.ADD_NEW_INCORRECT; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.CONNECT; + if (!_changedPass) + return; + if (connection.Password == null) + { + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = Messages.CONNECT_TO_SERVER_BLURB; + labelError.Text = ""; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.CONNECT; + } + else if (connection.ExpectPasswordIsCorrect) + { + // This situation should be rare, it normally comes from logging in a new session after an existing one has been made + // We now use duplicate sessions instead most of the time which don't log in again. + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = string.Format(Messages.ADDSERVER_PASS_NEW, BrandManager.BrandConsole); + labelError.Text = ""; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.OK; + } + else // the password probably hasn't actually changed but we do know the user has typed it in wrong + { + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = string.Format(Messages.ERROR_CONNECTING_BLURB, BrandManager.BrandConsole); + labelError.Text = Messages.ADD_NEW_INCORRECT; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.CONNECT; + } } } From a5ddcf1b97b9ff6aff89aae3b91fe29bcdd5fb6b Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 4 Oct 2021 15:09:42 +0100 Subject: [PATCH 22/62] CP-36392: Refactor loops into if blocks Loops are effectively used as if statements. Changed to improve readability. Signed-off-by: Danilo Del Busso --- .../FilterLocationToolStripDropDownButton.cs | 18 ++++++------ .../Controls/TreeViews/FlickerFreeTreeView.cs | 7 ++--- XenAdmin/Plugins/Features/MenuItemFeature.cs | 28 +++++++++---------- .../GenericSelectHostsPage.cs | 7 ++--- .../DRWizards/DRFailoverWizardStoragePage.cs | 12 ++++---- .../SelectMultipleVMDestinationPage.cs | 7 +++-- XenModel/Actions/AsyncAction.cs | 5 ++-- XenModel/Actions/DR/VdiLoadMetadataAction.cs | 23 +++++++-------- XenModel/Network/XenConnection.cs | 7 +++-- XenModel/ServerDBs/FakeAPI/fakeHost.cs | 11 ++++---- XenModel/Utils/Helpers.cs | 16 +++-------- XenModel/Utils/Util.cs | 11 +++----- XenModel/XenAPI-Extensions/Network.cs | 22 ++++++--------- XenModel/XenAPI-Extensions/SR.cs | 6 ++-- XenModel/XenSearch/Search.cs | 20 ++++++------- 15 files changed, 91 insertions(+), 109 deletions(-) diff --git a/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs b/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs index 1eef0ca0a..a833b6312 100644 --- a/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs +++ b/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs @@ -32,6 +32,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Linq; using System.Windows.Forms; using XenAdmin.Core; using XenAdmin.Network; @@ -119,19 +120,16 @@ namespace XenAdmin.Controls DeregisterEvents(); RegisterEvents(); - foreach (IXenConnection c in ConnectionsManager.XenConnectionsCopy) + foreach (var c in ConnectionsManager.XenConnectionsCopy) { - Pool p = Helpers.GetPool(c); + var p = Helpers.GetPool(c); - if (p == null)// Stand alone host + if (p == null && c.Cache.Hosts.Length > 0)// Stand alone host { - foreach (Host h in c.Cache.Hosts) - { - var item = GenerateFilterItem(h, h.uuid); - item.Checked = HostCheckStates.ContainsKey(h.uuid); - DropDownItems.Add(item); - break; - } + var host = c.Cache.Hosts.First(); + var item = GenerateFilterItem(host, host.uuid); + item.Checked = HostCheckStates.ContainsKey(host.uuid); + DropDownItems.Add(item); } else DropDownItems.Add(GeneratePoolFilterItem(p)); diff --git a/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs b/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs index 090a93895..75219a7db 100644 --- a/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs +++ b/XenAdmin/Controls/TreeViews/FlickerFreeTreeView.cs @@ -33,6 +33,7 @@ using System; using System.Windows.Forms; using XenAdmin.Core; using System.Collections.Generic; +using System.Linq; using XenAdmin.Network; using XenAdmin.XenSearch; using XenCenterLib; @@ -203,11 +204,9 @@ namespace XenAdmin.Controls if (newSelectedNodes.Count == 0) { - foreach (VirtualTreeNode.PersistenceInfo info in _persistedSelectionInfo) + if (_persistedSelectionInfo.Count > 0) { - // Finally, just select one of the parents - TryToSelectNode(newSelectedNodes, ClosestMatch(info.Path)); - break; + TryToSelectNode(newSelectedNodes, ClosestMatch(_persistedSelectionInfo.First().Path)); } } diff --git a/XenAdmin/Plugins/Features/MenuItemFeature.cs b/XenAdmin/Plugins/Features/MenuItemFeature.cs index b85cc06a8..22cb931e7 100644 --- a/XenAdmin/Plugins/Features/MenuItemFeature.cs +++ b/XenAdmin/Plugins/Features/MenuItemFeature.cs @@ -85,21 +85,21 @@ namespace XenAdmin.Plugins ContextMenu = Helpers.GetEnumXmlAttribute(node, ATT_CONTEXT_MENU, GetContextMenuFromMenu(Menu)); Serialized = Helpers.GetEnumXmlAttribute(node, ATT_SERIALIZED, PluginSerializationLevel.none); - foreach (XmlNode child in node.ChildNodes) - { - switch (child.Name) - { - case TYPE_SHELL: - ShellCmd = new ShellCmd(child, paramsFromXML(child)); - break; - case TYPE_POWERSHELL: - ShellCmd = new PowerShellCmd(child, paramsFromXML(child)); - break; - case TYPE_XENSERVER_POWERSHELL: - ShellCmd = new XenServerPowershellCmd(child, paramsFromXML(child)); - break; - } + if (node.ChildNodes.Count <= 0) return; + + var child = node.ChildNodes[0]; + switch (child.Name) + { + case TYPE_SHELL: + ShellCmd = new ShellCmd(child, paramsFromXML(child)); + break; + case TYPE_POWERSHELL: + ShellCmd = new PowerShellCmd(child, paramsFromXML(child)); + break; + case TYPE_XENSERVER_POWERSHELL: + ShellCmd = new XenServerPowershellCmd(child, paramsFromXML(child)); + break; } } diff --git a/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs b/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs index 92df49d32..bf9e733a5 100644 --- a/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs +++ b/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs @@ -32,6 +32,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Linq; using System.Windows.Forms; using XenAdmin.Controls; using XenAdmin.Core; @@ -120,12 +121,10 @@ namespace XenAdmin.Wizards.BugToolWizardFiles if (host != null && selectedObjects.Contains(host)) node.State = CheckState.Checked; } - //focus on first checked item so the user can find it in a long list - foreach (var node in HostListTreeView.CheckedItems()) + if (HostListTreeView.CheckedItems().Count > 0) { - HostListTreeView.SelectedItems.Add(node); - break; + HostListTreeView.SelectedItems.Add(HostListTreeView.CheckedItems().First()); } HostListTreeView.EndUpdate(); diff --git a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs index 7b4f4a0fd..1243a61a1 100644 --- a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs +++ b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs @@ -621,12 +621,12 @@ namespace XenAdmin.Wizards.DRWizards private bool FindRowByUuid(string uuid, out SrRow row) { row = null; - foreach (var srRow in dataGridViewSRs.Rows.Cast().Where(srRow => srRow.SrUuid == uuid)) - { - row = srRow; - return true; - } - return false; + var srRows = dataGridViewSRs.Rows.Cast().Where(srRow => srRow.SrUuid == uuid).ToList(); + if (srRows.Count <= 0) + return false; + + row = srRows.First(); + return true; } private void buttonSelectAll_Click(object sender, EventArgs e) diff --git a/XenAdmin/Wizards/GenericPages/SelectMultipleVMDestinationPage.cs b/XenAdmin/Wizards/GenericPages/SelectMultipleVMDestinationPage.cs index 3f4d11e79..0688804fa 100755 --- a/XenAdmin/Wizards/GenericPages/SelectMultipleVMDestinationPage.cs +++ b/XenAdmin/Wizards/GenericPages/SelectMultipleVMDestinationPage.cs @@ -413,16 +413,17 @@ namespace XenAdmin.Wizards.GenericPages { if (hasPoolSharedStorage) { - foreach (var pool in target.Item.Connection.Cache.Pools) + //there exists one pool per connection + var pools = target.Item.Connection.Cache.Pools; + if (pools.Length > 0) { + var pool = pools.First(); var item = new NoTargetServerPoolItem(pool); cb.Items.Add(item); if ((m_selectedObject != null && m_selectedObject.opaque_ref == pool.opaque_ref) || (target.Item.opaque_ref == pool.opaque_ref)) cb.Value = item; - - break; //there exists one pool per connection } } diff --git a/XenModel/Actions/AsyncAction.cs b/XenModel/Actions/AsyncAction.cs index 30db5aede..1d7d8b3bd 100644 --- a/XenModel/Actions/AsyncAction.cs +++ b/XenModel/Actions/AsyncAction.cs @@ -378,10 +378,9 @@ namespace XenAdmin.Actions doc.LoadXml(task.result); var nodes = doc.GetElementsByTagName("value"); - foreach (XmlNode node in nodes) + if (nodes.Count > 0) { - Result = node.InnerText; - break; + Result = nodes[0].InnerText; } } catch //CA-352946 diff --git a/XenModel/Actions/DR/VdiLoadMetadataAction.cs b/XenModel/Actions/DR/VdiLoadMetadataAction.cs index bcc10f36d..8b7bc5510 100644 --- a/XenModel/Actions/DR/VdiLoadMetadataAction.cs +++ b/XenModel/Actions/DR/VdiLoadMetadataAction.cs @@ -31,6 +31,7 @@ using System; using System.Collections.Generic; +using System.Linq; using XenAdmin.Core; using XenAdmin.Network; using XenAPI; @@ -91,25 +92,21 @@ namespace XenAdmin.Actions.DR MetadataSession = Session.get_record(Session, MetadataSessionRef); #region FIND POOL - Dictionary, XenAPI.Pool> pools = XenAPI.Pool.get_all_records(MetadataSession); - foreach (var pool in pools.Values) + var pools = Pool.get_all_records(MetadataSession); + var poolValues = pools.Values; + if (poolValues.Count > 0) { - _poolMetadata.Pool = pool; - string poolName = String.IsNullOrEmpty(pool.name_label) && pool.master != null - ? XenAPI.Host.get_name_label(MetadataSession, pool.master.opaque_ref) - : pool.name_label; + var pool = poolValues.First(); + var poolName = string.IsNullOrEmpty(pool.name_label) && pool.master != null + ? Host.get_name_label(MetadataSession, pool.master.opaque_ref) + : pool.name_label; _poolMetadata.Pool.name_label = poolName; log.DebugFormat("Found metadata of pool '{0}' (UUID={1})", _poolMetadata.Pool.Name(), - _poolMetadata.Pool.uuid); - break; + _poolMetadata.Pool.uuid); } + #endregion - /*if (_poolMetadata.Pool.uuid == Pool.uuid) // metadata of current pool - { - return; - }*/ - _poolMetadata.VmAppliances = VM_appliance.get_all_records(MetadataSession); foreach (var vmAppRef in _poolMetadata.VmAppliances.Keys) { diff --git a/XenModel/Network/XenConnection.cs b/XenModel/Network/XenConnection.cs index d69d895ee..b1d096096 100644 --- a/XenModel/Network/XenConnection.cs +++ b/XenModel/Network/XenConnection.cs @@ -41,6 +41,7 @@ using XenAdmin.Core; using XenAPI; using XenCenterLib; using System.Diagnostics; +using System.Linq; using System.Xml.Serialization; using XenAdmin.ServerDBs; @@ -1757,12 +1758,14 @@ namespace XenAdmin.Network private Pool getAPool(ICache objects, out string opaqueref) { - foreach (Pool pool in objects.Pools) + var pools = objects.Pools; + if (pools.Length > 0) { + var pool = pools.First(); opaqueref = pool.opaque_ref; return pool; } - System.Diagnostics.Trace.Assert(false); + Trace.Assert(false); opaqueref = null; return null; } diff --git a/XenModel/ServerDBs/FakeAPI/fakeHost.cs b/XenModel/ServerDBs/FakeAPI/fakeHost.cs index decdc3cc5..d86a9a0b3 100644 --- a/XenModel/ServerDBs/FakeAPI/fakeHost.cs +++ b/XenModel/ServerDBs/FakeAPI/fakeHost.cs @@ -34,6 +34,7 @@ using System.Collections.Generic; using XenAPI; using System.Collections; using System.Globalization; +using System.Linq; using System.Threading; namespace XenAdmin.ServerDBs.FakeAPI @@ -107,14 +108,14 @@ namespace XenAdmin.ServerDBs.FakeAPI public Response reboot(string session, string opaque_ref) { - string metrics_ref = (string)proxy.db.GetValue("host", opaque_ref, "metrics"); + var metrics_ref = (string)proxy.db.GetValue("host", opaque_ref, "metrics"); proxy.EditObject_(DbProxy.EditTypes.Replace, "host_metrics", metrics_ref, "live", false); - string coordinator_ref = ""; - foreach (string pool in proxy.db.Tables["pool"].Rows.Keys) + var coordinator_ref = ""; + var pools = proxy.db.Tables["pool"].Rows.Keys; + if (pools.Count > 0) { - coordinator_ref = (string)proxy.db.GetValue("pool", pool, "master"); - break; + coordinator_ref = (string)proxy.db.GetValue("pool", pools.First(), "master"); } if (opaque_ref == coordinator_ref) diff --git a/XenModel/Utils/Helpers.cs b/XenModel/Utils/Helpers.cs index 43c4648ef..06a988fa1 100755 --- a/XenModel/Utils/Helpers.cs +++ b/XenModel/Utils/Helpers.cs @@ -212,13 +212,7 @@ namespace XenAdmin.Core /// public static Pool GetPoolOfOne(IXenConnection connection) { - if (connection == null) - return null; - - foreach (Pool pool in connection.Cache.Pools) - return pool; - - return null; + return connection?.Cache.Pools.FirstOrDefault(); } /// @@ -1533,11 +1527,9 @@ namespace XenAdmin.Core public static string HostnameFromLocation(string p) { - foreach (Match m in HostnameOrIpRegex.Matches(p)) - { - return m.Value; // we only want the hostname or ip which should be the first match - } - return ""; + var matches = HostnameOrIpRegex.Matches(p); + // we only want the hostname or ip which should be the first match + return matches.Count > 0 ? matches[0].Value : string.Empty; } /// diff --git a/XenModel/Utils/Util.cs b/XenModel/Utils/Util.cs index 6bd281da4..d7fd2dc4e 100644 --- a/XenModel/Utils/Util.cs +++ b/XenModel/Utils/Util.cs @@ -33,6 +33,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Xml; @@ -560,17 +561,13 @@ namespace XenAdmin { ThrowIfStringParameterNullOrEmpty(xml, "xml"); - XmlDocument doc = new XmlDocument(); + var doc = new XmlDocument(); doc.LoadXml(xml); // If we've got this from an async task result, then it will be wrapped // in a element. - foreach (XmlNode node in doc.GetElementsByTagName("value")) - { - return node.InnerText; - } - - return null; + var nodes = doc.GetElementsByTagName("value"); + return nodes.Count > 0 ? nodes[0].InnerText : null; } } diff --git a/XenModel/XenAPI-Extensions/Network.cs b/XenModel/XenAPI-Extensions/Network.cs index 149189ee6..d24cfb213 100644 --- a/XenModel/XenAPI-Extensions/Network.cs +++ b/XenModel/XenAPI-Extensions/Network.cs @@ -31,6 +31,7 @@ using System; using System.Collections.Generic; +using System.Linq; using XenAdmin; using XenAdmin.Core; @@ -67,26 +68,21 @@ namespace XenAPI return name_label; } - Pool pool = Helpers.GetPoolOfOne(Connection); + var pool = Helpers.GetPoolOfOne(Connection); if (pool == null) return name_label; - string coordinator_ref = pool.master.opaque_ref; + var coordinator_ref = pool.master.opaque_ref; - foreach (PIF pif in Connection.ResolveAll(PIFs)) + var pifs = Connection.ResolveAll(PIFs); + + var filteredPifs = pifs.Where(pif => pif.host.opaque_ref == coordinator_ref).ToList(); + if (filteredPifs.Count > 0) { - if (pif.host.opaque_ref == coordinator_ref) - { - return PIFName(pif); - } + return PIFName(filteredPifs.First()); } - foreach (PIF pif in Connection.ResolveAll(PIFs)) - { - return PIFName(pif); - } - - return name_label; + return pifs.Count > 0 ? PIFName(pifs.First()) : name_label; } public bool AllHostsCanSeeNetwork() diff --git a/XenModel/XenAPI-Extensions/SR.cs b/XenModel/XenAPI-Extensions/SR.cs index 6b9aa0cc0..8b1779f3c 100644 --- a/XenModel/XenAPI-Extensions/SR.cs +++ b/XenModel/XenAPI-Extensions/SR.cs @@ -568,12 +568,12 @@ namespace XenAPI // If we've got this from an async task result, then it will be wrapped // in a element. Parse the contents instead. - foreach (XmlNode node in doc.GetElementsByTagName("value")) + var nodes = doc.GetElementsByTagName("value"); + if (nodes.Count > 0) { - xml = node.InnerText; + xml = nodes[0].InnerText; doc = new XmlDocument(); doc.LoadXml(xml); - break; } diff --git a/XenModel/XenSearch/Search.cs b/XenModel/XenSearch/Search.cs index e7324886a..27d77232b 100644 --- a/XenModel/XenSearch/Search.cs +++ b/XenModel/XenSearch/Search.cs @@ -32,6 +32,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using XenAPI; using XenAdmin.Core; @@ -280,8 +281,8 @@ namespace XenAdmin.XenSearch if (uuid == null) uuid = System.Guid.NewGuid().ToString(); - String key = SearchPrefix + uuid; - String value = GetXML(); + var key = SearchPrefix + uuid; + var value = GetXML(); if (connection == null) return false; @@ -289,16 +290,15 @@ namespace XenAdmin.XenSearch if (!connection.IsConnected) return false; - Session session = connection.DuplicateSession(); - foreach (Pool pool in connection.Cache.Pools) - { - Pool.remove_from_gui_config(session, pool.opaque_ref, key); - Pool.add_to_gui_config(session, pool.opaque_ref, key, value); + var session = connection.DuplicateSession(); - return true; - } + var pools = connection.Cache.Pools; + if (pools.Length <= 0) return false; - return false; + var pool = pools.First(); + Pool.remove_from_gui_config(session, pool.opaque_ref, key); + Pool.add_to_gui_config(session, pool.opaque_ref, key, value); + return true; } public void Save(String filename) From dcbaf5d1a44bbee00e350c3c97c9558907992549 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 4 Oct 2021 15:42:40 +0100 Subject: [PATCH 23/62] CP-36392: Amend calls that generate unused return values Mixture of correctly implementing `Trim()` calls, and removing calls that generate useless ephemeral variables. Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/LunPerVdiPicker.cs | 1 - .../Dialogs/LicenseManager/LicenseStatus.cs | 13 +++-- XenModel/Alerts/PerfmonDefinition.cs | 18 +++--- XenModel/Alerts/PerfmonOptionsDefinition.cs | 57 ++++++------------- XenModel/CustomFields/CustomFieldsCache.cs | 23 ++------ 5 files changed, 38 insertions(+), 74 deletions(-) diff --git a/XenAdmin/Controls/LunPerVdiPicker.cs b/XenAdmin/Controls/LunPerVdiPicker.cs index 3e3ca3c66..8b7c70480 100644 --- a/XenAdmin/Controls/LunPerVdiPicker.cs +++ b/XenAdmin/Controls/LunPerVdiPicker.cs @@ -271,7 +271,6 @@ namespace XenAdmin.Controls cbLUN.Items.Add(new LunComboBoxItem(vdi) { AdditionalConstraints = LunConstraints }); } - cbLUN.Items.OfType().OrderBy(i=>i.Enabled); Cells.AddRange(tbVDI, cbLUN, tbSR); Debug.Assert(cbLUN.Items.Count == Sr.VDIs.Count, "Not all combobox items were converted"); } diff --git a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs index a946477b3..4368eb589 100644 --- a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs +++ b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs @@ -213,12 +213,13 @@ namespace XenAdmin.Dialogs into g select new { ExpiryDate = g.Key, Hosts = g }; - if(expiryGroups.Count() > 1) - { - expiryGroups.OrderBy(g => g.ExpiryDate); - if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) - return true; - } + expiryGroups = expiryGroups.OrderBy(g => g.ExpiryDate).ToList(); + + if (expiryGroups.Count() <= 1) + return false; + + if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) + return true; } return false; } diff --git a/XenModel/Alerts/PerfmonDefinition.cs b/XenModel/Alerts/PerfmonDefinition.cs index b0027b48b..83d0cc0d1 100644 --- a/XenModel/Alerts/PerfmonDefinition.cs +++ b/XenModel/Alerts/PerfmonDefinition.cs @@ -287,24 +287,20 @@ namespace XenAdmin.Alerts public static PerfmonDefinition[] GetPerfmonDefinitions(IXenObject xo) { if (!(xo is VM) && !(xo is Host) && !(xo is SR)) - return new PerfmonDefinition[0]; + return Array.Empty(); - Dictionary other_config = Helpers.GetOtherConfig(xo); + var other_config = Helpers.GetOtherConfig(xo); if (other_config == null) - return new PerfmonDefinition[0]; + return Array.Empty(); if (!other_config.ContainsKey(PERFMON_KEY_NAME)) - return new PerfmonDefinition[0]; + return Array.Empty(); - string perfmonConfigXML = other_config[PERFMON_KEY_NAME]; + var perfmonConfigXML = other_config[PERFMON_KEY_NAME]; if (perfmonConfigXML == null) - return new PerfmonDefinition[0]; + return Array.Empty(); - perfmonConfigXML.Trim(); - if (String.IsNullOrEmpty(perfmonConfigXML)) - return new PerfmonDefinition[0]; - - return GetPerfmonDefinitions(perfmonConfigXML); + return string.IsNullOrEmpty(perfmonConfigXML) ? Array.Empty() : GetPerfmonDefinitions(perfmonConfigXML); } /// diff --git a/XenModel/Alerts/PerfmonOptionsDefinition.cs b/XenModel/Alerts/PerfmonOptionsDefinition.cs index dbb11ac43..9f0d26c39 100755 --- a/XenModel/Alerts/PerfmonOptionsDefinition.cs +++ b/XenModel/Alerts/PerfmonOptionsDefinition.cs @@ -205,74 +205,53 @@ namespace XenAdmin.Alerts public static string GetMailDestination(IXenConnection connection) { - Pool pool = Helpers.GetPoolOfOne(connection); + var pool = Helpers.GetPoolOfOne(connection); if (pool == null) return null; - Dictionary other_config = Helpers.GetOtherConfig(pool); - if (other_config == null) + var otherConfig = Helpers.GetOtherConfig(pool); + if (otherConfig == null) return null; - if (!other_config.ContainsKey(MAIL_DESTINATION_KEY_NAME)) + if (!otherConfig.ContainsKey(MAIL_DESTINATION_KEY_NAME)) return null; - String mailAddress = other_config[MAIL_DESTINATION_KEY_NAME]; - if (mailAddress == null) - return null; - - mailAddress.Trim(); - if (String.IsNullOrEmpty(mailAddress)) - return null; - - return mailAddress; + var mailAddress = otherConfig[MAIL_DESTINATION_KEY_NAME]?.Trim(); + return string.IsNullOrEmpty(mailAddress) ? null : mailAddress; } public static string GetSmtpMailHub(IXenConnection connection) { - Pool pool = Helpers.GetPoolOfOne(connection); + var pool = Helpers.GetPoolOfOne(connection); if (pool == null) return null; - Dictionary other_config = Helpers.GetOtherConfig(pool); - if (other_config == null) + var otherConfig = Helpers.GetOtherConfig(pool); + if (otherConfig == null) return null; - if (!other_config.ContainsKey(SMTP_MAILHUB_KEY_NAME)) + if (!otherConfig.ContainsKey(SMTP_MAILHUB_KEY_NAME)) return null; - String mailHub = other_config[SMTP_MAILHUB_KEY_NAME]; - if (mailHub == null) - return null; - - mailHub.Trim(); - if (String.IsNullOrEmpty(mailHub)) - return null; - - return mailHub; + var mailHub = otherConfig[SMTP_MAILHUB_KEY_NAME]?.Trim(); + return string.IsNullOrEmpty(mailHub) ? null : mailHub; } public static string GetMailLanguageCode(IXenConnection connection) { - Pool pool = Helpers.GetPoolOfOne(connection); + var pool = Helpers.GetPoolOfOne(connection); if (pool == null) return null; - Dictionary other_config = Helpers.GetOtherConfig(pool); - if (other_config == null) + var otherConfig = Helpers.GetOtherConfig(pool); + if (otherConfig == null) return null; - if (!other_config.ContainsKey(MAIL_LANGUAGE_KEY_NAME)) + if (!otherConfig.ContainsKey(MAIL_LANGUAGE_KEY_NAME)) return null; - String mailLanguageCode = other_config[MAIL_LANGUAGE_KEY_NAME]; - if (mailLanguageCode == null) - return null; - - mailLanguageCode.Trim(); - if (String.IsNullOrEmpty(mailLanguageCode)) - return null; - - return mailLanguageCode; + var mailLanguageCode = otherConfig[MAIL_LANGUAGE_KEY_NAME]?.Trim(); + return string.IsNullOrEmpty(mailLanguageCode) ? null : mailLanguageCode; } public static String MailLanguageNameFromCode(String code) diff --git a/XenModel/CustomFields/CustomFieldsCache.cs b/XenModel/CustomFields/CustomFieldsCache.cs index 28d1a6ede..6b18b9d39 100644 --- a/XenModel/CustomFields/CustomFieldsCache.cs +++ b/XenModel/CustomFields/CustomFieldsCache.cs @@ -68,36 +68,25 @@ namespace XenAdmin.CustomFields private static List GetCustomFieldsFromGuiConfig(IXenConnection connection) { - Pool pool = Helpers.GetPoolOfOne(connection); + var pool = Helpers.GetPoolOfOne(connection); if (pool == null) { return new List(); } - Dictionary other_config = Helpers.GetGuiConfig(pool); - if (other_config == null) + var otherConfig = Helpers.GetGuiConfig(pool); + if (otherConfig == null) { return new List(); } - if (!other_config.ContainsKey(CustomFieldsManager.CUSTOM_FIELD_BASE_KEY)) + if (!otherConfig.ContainsKey(CustomFieldsManager.CUSTOM_FIELD_BASE_KEY)) { return new List(); } - String customFields = other_config[CustomFieldsManager.CUSTOM_FIELD_BASE_KEY]; - if (customFields == null) - { - return new List(); - } - - customFields.Trim(); - if (String.IsNullOrEmpty(customFields)) - { - return new List(); - } - - return GetCustomFieldDefinitions(customFields); + var customFields = otherConfig[CustomFieldsManager.CUSTOM_FIELD_BASE_KEY]?.Trim(); + return string.IsNullOrEmpty(customFields) ? new List() : GetCustomFieldDefinitions(customFields); } public List GetCustomFields() From db2c00d54d785a30e8d7c65dbf066728bbeafd29 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 4 Oct 2021 16:22:29 +0100 Subject: [PATCH 24/62] CP-36392: Cast operands of divisions to not lose precision Cast to `decimal` or `float` to keep floating-point precision Signed-off-by: Danilo Del Busso --- XenAdmin/ConsoleView/VNCGraphicsClient.cs | 4 ++-- XenAdmin/Controls/SectionHeaderLabel.cs | 2 +- XenAdmin/Controls/XenSearch/QueryElement.cs | 2 +- XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs | 13 ++++++------- .../Dialogs/OptionsPages/ConnectionOptionsPage.cs | 2 +- XenAdmin/SettingsPanels/PerfmonAlertEditPage.cs | 2 +- XenModel/Actions/Pool/EnableHAAction.cs | 2 +- 7 files changed, 13 insertions(+), 14 deletions(-) diff --git a/XenAdmin/ConsoleView/VNCGraphicsClient.cs b/XenAdmin/ConsoleView/VNCGraphicsClient.cs index e4b54ff55..39c957ba7 100644 --- a/XenAdmin/ConsoleView/VNCGraphicsClient.cs +++ b/XenAdmin/ConsoleView/VNCGraphicsClient.cs @@ -1500,7 +1500,7 @@ namespace XenAdmin.ConsoleView if (this.Size.Height >= (displayBorder ? this.DesktopSize.Height + BORDER_PADDING + BORDER_PADDING : DesktopSize.Height)) { - this.dy = (this.Size.Height - this.DesktopSize.Height) / 2; + this.dy = ((float) this.Size.Height - this.DesktopSize.Height) / 2; } else { @@ -1518,7 +1518,7 @@ namespace XenAdmin.ConsoleView if (this.Size.Width >= (displayBorder ? this.DesktopSize.Width + BORDER_PADDING + BORDER_PADDING : DesktopSize.Width)) { - this.dx = (this.Size.Width - this.DesktopSize.Width) / 2; + this.dx = ((float) this.Size.Width - this.DesktopSize.Width) / 2; } else { diff --git a/XenAdmin/Controls/SectionHeaderLabel.cs b/XenAdmin/Controls/SectionHeaderLabel.cs index 492d30395..533c6973a 100644 --- a/XenAdmin/Controls/SectionHeaderLabel.cs +++ b/XenAdmin/Controls/SectionHeaderLabel.cs @@ -300,7 +300,7 @@ namespace XenAdmin.Controls } case VerticalAlignment.Middle: { - Y = (this.Height - this.Padding.Vertical) / 2; + Y = ((float) this.Height - this.Padding.Vertical) / 2; break; } case VerticalAlignment.Bottom: diff --git a/XenAdmin/Controls/XenSearch/QueryElement.cs b/XenAdmin/Controls/XenSearch/QueryElement.cs index c101463e3..f5afa254d 100644 --- a/XenAdmin/Controls/XenSearch/QueryElement.cs +++ b/XenAdmin/Controls/XenSearch/QueryElement.cs @@ -2498,7 +2498,7 @@ namespace XenAdmin.Controls.XenSearch if (intQuery == null) return; - queryElement.numericUpDown.Value = intQuery.query / multiplier; + queryElement.numericUpDown.Value = (decimal) intQuery.query / multiplier; } } diff --git a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs index 4368eb589..a946477b3 100644 --- a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs +++ b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs @@ -213,13 +213,12 @@ namespace XenAdmin.Dialogs into g select new { ExpiryDate = g.Key, Hosts = g }; - expiryGroups = expiryGroups.OrderBy(g => g.ExpiryDate).ToList(); - - if (expiryGroups.Count() <= 1) - return false; - - if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) - return true; + if(expiryGroups.Count() > 1) + { + expiryGroups.OrderBy(g => g.ExpiryDate); + if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) + return true; + } } return false; } diff --git a/XenAdmin/Dialogs/OptionsPages/ConnectionOptionsPage.cs b/XenAdmin/Dialogs/OptionsPages/ConnectionOptionsPage.cs index fd47ff9fb..2bf0b0992 100644 --- a/XenAdmin/Dialogs/OptionsPages/ConnectionOptionsPage.cs +++ b/XenAdmin/Dialogs/OptionsPages/ConnectionOptionsPage.cs @@ -120,7 +120,7 @@ namespace XenAdmin.Dialogs.OptionsPages log.Warn("Could not unprotect internet proxy password.", e); } - ConnectionTimeoutNud.Value = Properties.Settings.Default.ConnectionTimeout / 1000; + ConnectionTimeoutNud.Value = (decimal) Properties.Settings.Default.ConnectionTimeout / 1000; eventsDisabled = false; } diff --git a/XenAdmin/SettingsPanels/PerfmonAlertEditPage.cs b/XenAdmin/SettingsPanels/PerfmonAlertEditPage.cs index 0a2615e30..78ef3dce0 100644 --- a/XenAdmin/SettingsPanels/PerfmonAlertEditPage.cs +++ b/XenAdmin/SettingsPanels/PerfmonAlertEditPage.cs @@ -230,7 +230,7 @@ namespace XenAdmin.SettingsPanels Host host = (Host)_XenObject; Host_metrics metrics = host.Connection.Resolve(host.metrics); if (metrics != null) - nudMemoryUsage.Maximum = metrics.memory_total / (1024 * 1024); + nudMemoryUsage.Maximum = (decimal) metrics.memory_total / (1024 * 1024); } Repopulate(); diff --git a/XenModel/Actions/Pool/EnableHAAction.cs b/XenModel/Actions/Pool/EnableHAAction.cs index e571646a6..83b23e937 100644 --- a/XenModel/Actions/Pool/EnableHAAction.cs +++ b/XenModel/Actions/Pool/EnableHAAction.cs @@ -67,7 +67,7 @@ namespace XenAdmin.Actions { if (startupOptions != null) { - double increment = 10 / Math.Max(startupOptions.Count, 1); + double increment = 10.0 / Math.Max(startupOptions.Count, 1); int i = 0; // First set any VM restart priorities supplied foreach (VM vm in startupOptions.Keys) From 4e4747ecb890e9f6490c9bf82547f0bbad9c5e16 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 4 Oct 2021 16:27:42 +0100 Subject: [PATCH 25/62] CP-36392: Remove misleading `readonly` in collection/array fields `reaonly` should be used for items that can't be modified. The changed collections/arrays are modified, so `readonly` is misleading Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/CustomGridView/GridRow.cs | 4 ++-- XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs | 2 +- .../Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs | 4 ++-- XenModel/Actions/GetDataSourcesAction.cs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/XenAdmin/Controls/CustomGridView/GridRow.cs b/XenAdmin/Controls/CustomGridView/GridRow.cs index 0f2da5ce5..f0e1ef7c3 100644 --- a/XenAdmin/Controls/CustomGridView/GridRow.cs +++ b/XenAdmin/Controls/CustomGridView/GridRow.cs @@ -38,8 +38,8 @@ namespace XenAdmin.Controls.CustomGridView { public class GridRow : IComparable { - public readonly Dictionary Items = new Dictionary(); - public readonly List Rows = new List(); + public Dictionary Items = new Dictionary(); + public List Rows = new List(); public static Image ExpandedImage = Images.StaticImages.expanded_triangle; public static Image ShrunkenImage = Images.StaticImages.contracted_triangle; diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs index bd3e5f754..4460855fb 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs @@ -49,7 +49,7 @@ namespace XenAdmin.Wizards.PatchingWizard } #region Accessors - public readonly List PatchMappings = new List(); + public List PatchMappings = new List(); public UpdateType SelectedUpdateType { private get; set; } public string SelectedPatchFilePath { get; set; } diff --git a/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs b/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs index ceca7c1ef..46ee3c4af 100644 --- a/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs +++ b/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs @@ -42,8 +42,8 @@ namespace XenAdmin.Wizards.PatchingWizard public List HostPlans { get; private set; } public List FinalActions { get; private set; } public List CleanupActions { get; private set; } - public readonly List DoneActions = new List(); - public readonly List InProgressActions = new List(); + public List DoneActions = new List(); + public List InProgressActions = new List(); public Pool Pool { get; private set; } public string Name { get; private set; } diff --git a/XenModel/Actions/GetDataSourcesAction.cs b/XenModel/Actions/GetDataSourcesAction.cs index 2cbf41c0f..a7dde398e 100644 --- a/XenModel/Actions/GetDataSourcesAction.cs +++ b/XenModel/Actions/GetDataSourcesAction.cs @@ -38,7 +38,7 @@ namespace XenAdmin.Actions { public class GetDataSourcesAction : AsyncAction { - public readonly List DataSources = new List(); + public List DataSources = new List(); public readonly IXenObject IXenObject; public GetDataSourcesAction(IXenConnection connection, IXenObject xmo) From 2352dcc4bfad7012d929609da96b245e68e66fed Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 5 Oct 2021 10:13:25 +0100 Subject: [PATCH 26/62] CP-36392: Remove unused KeySet.cs File isn't used and contains 2 minor bug SonarQube flags Signed-off-by: Danilo Del Busso --- XenAdmin/VNC/KeySet.cs | 161 --------------------------------------- XenAdmin/XenAdmin.csproj | 1 - 2 files changed, 162 deletions(-) delete mode 100644 XenAdmin/VNC/KeySet.cs diff --git a/XenAdmin/VNC/KeySet.cs b/XenAdmin/VNC/KeySet.cs deleted file mode 100644 index 90bcef4ff..000000000 --- a/XenAdmin/VNC/KeySet.cs +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright (c) Citrix Systems, Inc. - * All rights reserved. - * - * 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.Windows.Forms; - -namespace DotNetVnc -{ - public class KeySet : IEquatable - { - List keys; - - public IList Keys - { - get - { - return keys.AsReadOnly(); - } - } - - public KeySet() - { - this.keys = new List(); - } - - public KeySet(List keys) - { - this.keys = new List(); - - foreach (Keys key in keys) - { - if (!this.keys.Contains(key)) - { - this.keys.Add(key); - } - } - - this.keys.Sort(); - } - - public KeySet(params Keys[] keys) - { - this.keys = new List(); - - foreach (Keys key in keys) - { - if (!this.keys.Contains(key)) - { - this.keys.Add(key); - } - } - - this.keys.Sort(); - } - - public KeySet Add(Keys _key) - { - List newKeys = new List(); - - foreach(Keys key in this.keys) - { - newKeys.Add(key); - } - - if (!newKeys.Contains(_key)) - newKeys.Add(_key); - - return new KeySet(newKeys); - } - - public KeySet Remove(Keys _key) - { - List newKeys = new List(); - - foreach (Keys key in this.keys) - { - if (key != _key) - { - newKeys.Add(key); - } - } - - return new KeySet(newKeys); - } - - public bool Equals(KeySet keySet) - { - foreach (Keys key in keySet.Keys) - { - if (!keys.Contains(key)) - { - return false; - } - } - - foreach (Keys key in this.keys) - { - if (!keySet.Keys.Contains(key)) - { - return false; - } - } - - return true; - } - - public override int GetHashCode() - { - if (this.keys.Count > 0) - { - return (int)this.keys[0]; - } - else - { - return 0; - } - } - - public override String ToString() - { - String result = ""; - - foreach (Keys key in this.keys) - { - result += key; - result += " "; - } - - return result; - } - } -} diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index 32b6494ca..826da53a4 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -748,7 +748,6 @@ KeyMap.cs - From 36b815f104d9ab6cc79dccf5dcba17d315ba1159 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 5 Oct 2021 11:32:19 +0100 Subject: [PATCH 27/62] CP-36382: Add missing `Equals` to `QueryTypes.cs` Class implements `GetHashCode` without `Equals` Signed-off-by: Danilo Del Busso --- XenModel/XenSearch/QueryTypes.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/XenModel/XenSearch/QueryTypes.cs b/XenModel/XenSearch/QueryTypes.cs index 612ed13a3..9d096ae98 100644 --- a/XenModel/XenSearch/QueryTypes.cs +++ b/XenModel/XenSearch/QueryTypes.cs @@ -1193,6 +1193,13 @@ namespace XenAdmin.XenSearch { return address.GetHashCode(); } + + public override bool Equals(object obj) + { + if (!(obj is IPAddressQuery other)) + return false; + return address.Equals(other.address); + } } public class BooleanQuery : PropertyQuery From 3a69fa0f8cce99fbc7517731c5812a38e87268a3 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 5 Oct 2021 11:33:53 +0100 Subject: [PATCH 28/62] CP-36392: Add `readonly` to fields used in `GetHashCode` Also tidy up some code Signed-off-by: Danilo Del Busso --- XenAdmin/GroupingTag.cs | 5 ++--- .../DRWizards/DRFailoverWizardPrecheckPage.cs | 4 ++-- .../PatchingWizard_PrecheckPage.cs | 4 ++-- XenModel/XenSearch/GroupAlg.cs | 19 +++++++++---------- XenModel/XenSearch/Query.cs | 4 ++-- XenModel/XenSearch/QueryScope.cs | 2 +- 6 files changed, 18 insertions(+), 20 deletions(-) diff --git a/XenAdmin/GroupingTag.cs b/XenAdmin/GroupingTag.cs index f7866490b..5bb67ac11 100644 --- a/XenAdmin/GroupingTag.cs +++ b/XenAdmin/GroupingTag.cs @@ -37,7 +37,7 @@ namespace XenAdmin { internal Grouping Grouping; internal object Parent; - internal object Group; + internal readonly object Group; /// /// @@ -55,8 +55,7 @@ namespace XenAdmin public override bool Equals(object obj) { - GroupingTag other = obj as GroupingTag; - return other != null && Grouping.Equals(other.Grouping) && Group.Equals(other.Group); + return obj is GroupingTag other && Grouping.Equals(other.Grouping) && Group.Equals(other.Group); } public override int GetHashCode() diff --git a/XenAdmin/Wizards/DRWizards/DRFailoverWizardPrecheckPage.cs b/XenAdmin/Wizards/DRWizards/DRFailoverWizardPrecheckPage.cs index d941c2694..f126922d0 100644 --- a/XenAdmin/Wizards/DRWizards/DRFailoverWizardPrecheckPage.cs +++ b/XenAdmin/Wizards/DRWizards/DRFailoverWizardPrecheckPage.cs @@ -596,8 +596,8 @@ namespace XenAdmin.Wizards.DRWizards private class PreCheckItemRow : PreCheckGridRow { - private Problem _problem = null; - private Check _check = null; + private readonly Problem _problem; + private readonly Check _check; public PreCheckItemRow(Problem problem) { _problem = problem; diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs index 2dea4c414..b7e968c54 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs @@ -611,8 +611,8 @@ namespace XenAdmin.Wizards.PatchingWizard private class PreCheckHostRow : PreCheckGridRow { - private Problem _problem = null; - private Check _check = null; + private readonly Problem _problem = null; + private readonly Check _check = null; public PreCheckHostRow(Problem problem) : base(new DataGridViewTextBoxCell()) { diff --git a/XenModel/XenSearch/GroupAlg.cs b/XenModel/XenSearch/GroupAlg.cs index 4e6ac63c0..65ce7cede 100644 --- a/XenModel/XenSearch/GroupAlg.cs +++ b/XenModel/XenSearch/GroupAlg.cs @@ -167,7 +167,7 @@ namespace XenAdmin.XenSearch return -1; if (other == null) return 1; - return Compare(one.key, other.key); + return Compare(one.Key, other.Key); } /// @@ -294,29 +294,28 @@ namespace XenAdmin.XenSearch public class GroupKey : IEquatable { - public Grouping grouping; - public object key; + public readonly Grouping Grouping; + public readonly object Key; public GroupKey(Grouping grouping, object key) { - this.grouping = grouping; - this.key = key; + Grouping = grouping; + Key = key; } public override int GetHashCode() { - return key.GetHashCode(); + return Key.GetHashCode(); } public bool Equals(GroupKey other) { - return other != null && grouping.Equals(other.grouping) && key.Equals(other.key); + return other != null && Grouping.Equals(other.Grouping) && Key.Equals(other.Key); } public override bool Equals(object obj) { - GroupKey other = obj as GroupKey; - return other != null && Equals(other); + return obj is GroupKey other && Equals(other); } } @@ -350,7 +349,7 @@ namespace XenAdmin.XenSearch foreach (GroupKey group in groups) { - IAcceptGroups subAdapter = adapter.Add(group.grouping, group.key, indent); + IAcceptGroups subAdapter = adapter.Add(group.Grouping, group.Key, indent); if (subAdapter == null) continue; diff --git a/XenModel/XenSearch/Query.cs b/XenModel/XenSearch/Query.cs index 49163729d..04f01c177 100644 --- a/XenModel/XenSearch/Query.cs +++ b/XenModel/XenSearch/Query.cs @@ -36,8 +36,8 @@ namespace XenAdmin.XenSearch { public class Query { - private QueryScope scope; - private QueryFilter filter; + private readonly QueryScope scope; + private readonly QueryFilter filter; public Query(QueryScope scope, QueryFilter filter) { diff --git a/XenModel/XenSearch/QueryScope.cs b/XenModel/XenSearch/QueryScope.cs index dd9da3cd2..6443c2803 100644 --- a/XenModel/XenSearch/QueryScope.cs +++ b/XenModel/XenSearch/QueryScope.cs @@ -37,7 +37,7 @@ namespace XenAdmin.XenSearch { public class QueryScope: IEquatable { - private ObjectTypes types; + private readonly ObjectTypes types; public QueryScope(ObjectTypes types) { From 69722d93bd7de8df42581ce95e4c293a2be18444 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 5 Oct 2021 11:56:15 +0100 Subject: [PATCH 29/62] CP-36392: Rename key constants in `WlbReportSubscription.cs` to avoid field clash Names are amibguous Also made the fields `const` Signed-off-by: Danilo Del Busso --- .../Wlb/WlbReportSubscriptionDialog.cs | 4 +- XenModel/WLB/WlbReportSubscription.cs | 220 +++++++++--------- 2 files changed, 112 insertions(+), 112 deletions(-) diff --git a/XenAdmin/Dialogs/Wlb/WlbReportSubscriptionDialog.cs b/XenAdmin/Dialogs/Wlb/WlbReportSubscriptionDialog.cs index bab414af2..b6096072b 100644 --- a/XenAdmin/Dialogs/Wlb/WlbReportSubscriptionDialog.cs +++ b/XenAdmin/Dialogs/Wlb/WlbReportSubscriptionDialog.cs @@ -378,8 +378,8 @@ namespace XenAdmin.Dialogs.Wlb Dictionary rps = new Dictionary(); foreach(string key in this._rpParams.Keys) { - if (String.Compare(key, WlbReportSubscription.REPORT_NAME, true) == 0) - _subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME]; + if (String.Compare(key, WlbReportSubscription.REPORT_NAME_KEY, true) == 0) + _subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME_KEY]; else { //Get start date range diff --git a/XenModel/WLB/WlbReportSubscription.cs b/XenModel/WLB/WlbReportSubscription.cs index 439a8def3..1b7feffaf 100644 --- a/XenModel/WLB/WlbReportSubscription.cs +++ b/XenModel/WLB/WlbReportSubscription.cs @@ -38,32 +38,32 @@ namespace XenAdmin.Wlb { #region Variables - private static string SUB_ID = "id"; - private static string CREATED = "created"; - private static string SUB_NAME = "name"; - private static string SUB_DESCRIPTION = "description"; - private static string SUBSCRIBER_ID = "subscriberId"; - private static string SUBSCRIBER_NAME = "subscriberName"; - private static string SCHEDULE_ID = "scheduleId"; - private static string DAYOFWEEK = "daysOfWeek"; - private static string EXECUTE_TIMEOFDAY = "executeTimeOfDay"; - private static string TRIGGER_TYPE = "triggerType"; - private static string ENABLED = "enabled"; - private static string ENABLE_DATE = "enableDate"; - private static string DISABLE_DATE = "disableDate"; - private static string LAST_TOUCHED = "lastTouched"; - private static string LAST_TOUCHEDBY = "lastTouchedBy"; - private static string LAST_RUN = "lastRun"; - private static string LAST_RUNRESULT = "lastRunResult"; - private static string EMAIL_TO = "emailTo"; - private static string EMAIL_REPLYTO = "emailReplyTo"; - private static string REPORT_RENDERFORMAT = "rpRenderFormat"; - private static string EMAIL_SUBJECT = "emailSubject"; - private static string EMAIL_COMMENT = "emailComment"; - private static string EMAIL_CC = "emailCc"; - private static string EMAIL_BCC = "emailBcc"; - private static string REPORT_ID = "reportId"; - public static string REPORT_NAME = "reportName"; + private const string SUB_ID_KEY = "id"; + private const string CREATED_KEY = "created"; + private const string SUB_NAME_KEY = "name"; + private const string SUB_DESCRIPTION_KEY = "description"; + private const string SUBSCRIBER_ID_KEY = "subscriberId"; + private const string SUBSCRIBER_NAME_KEY = "subscriberName"; + private const string SCHEDULE_ID_KEY = "scheduleId"; + private const string DAYOFWEEK_KEY = "daysOfWeek"; + private const string EXECUTE_TIMEOFDAY_KEY = "executeTimeOfDay"; + private const string TRIGGER_TYPE_KEY = "triggerType"; + private const string ENABLED_KEY = "enabled"; + private const string ENABLE_DATE_KEY = "enableDate"; + private const string DISABLE_DATE_KEY = "disableDate"; + private const string LAST_TOUCHED_KEY = "lastTouched"; + private const string LAST_TOUCHEDBY_KEY = "lastTouchedBy"; + private const string LAST_RUN_KEY = "lastRun"; + private const string LAST_RUNRESULT_KEY = "lastRunResult"; + private const string EMAIL_TO_KEY = "emailTo"; + private const string EMAIL_REPLYTO_KEY = "emailReplyTo"; + private const string REPORT_RENDERFORMAT_KEY = "rpRenderFormat"; + private const string EMAIL_SUBJECT_KEY = "emailSubject"; + private const string EMAIL_COMMENT_KEY = "emailComment"; + private const string EMAIL_CC_KEY = "emailCc"; + private const string EMAIL_BCC_KEY = "emailBcc"; + private const string REPORT_ID_KEY = "reportId"; + public const string REPORT_NAME_KEY = "reportName"; private string _reportDisplayName; @@ -101,41 +101,41 @@ namespace XenAdmin.Wlb /// Subscription id public WlbReportSubscription(string id) { - base.Configuration = new Dictionary(); - base.KeyBase = WlbConfigurationKeyBase.rpSub; - base.ItemId = (String.IsNullOrEmpty(id) ? "0" : id); - this._reportDisplayName = String.Empty; + Configuration = new Dictionary(); + KeyBase = WlbConfigurationKeyBase.rpSub; + ItemId = string.IsNullOrEmpty(id) ? "0" : id; + _reportDisplayName = string.Empty; //Define the known keys - base.WlbConfigurationKeys = - new List(new string[] + WlbConfigurationKeys = + new List(new[] { - SUB_ID, - CREATED, - SUB_NAME, - SUB_DESCRIPTION, - SUBSCRIBER_ID, - SUBSCRIBER_NAME, - SCHEDULE_ID, - DAYOFWEEK, - EXECUTE_TIMEOFDAY, - TRIGGER_TYPE, - ENABLED, - ENABLE_DATE, - DISABLE_DATE, - LAST_TOUCHED, - LAST_TOUCHEDBY, - LAST_RUN, - LAST_RUNRESULT, - EMAIL_TO, - EMAIL_REPLYTO, - REPORT_RENDERFORMAT, - EMAIL_SUBJECT, - EMAIL_COMMENT, - EMAIL_CC, - EMAIL_BCC, - REPORT_ID, - REPORT_NAME + SUB_ID_KEY, + CREATED_KEY, + SUB_NAME_KEY, + SUB_DESCRIPTION_KEY, + SUBSCRIBER_ID_KEY, + SUBSCRIBER_NAME_KEY, + SCHEDULE_ID_KEY, + DAYOFWEEK_KEY, + EXECUTE_TIMEOFDAY_KEY, + TRIGGER_TYPE_KEY, + ENABLED_KEY, + ENABLE_DATE_KEY, + DISABLE_DATE_KEY, + LAST_TOUCHED_KEY, + LAST_TOUCHEDBY_KEY, + LAST_RUN_KEY, + LAST_RUNRESULT_KEY, + EMAIL_TO_KEY, + EMAIL_REPLYTO_KEY, + REPORT_RENDERFORMAT_KEY, + EMAIL_SUBJECT_KEY, + EMAIL_COMMENT_KEY, + EMAIL_CC_KEY, + EMAIL_BCC_KEY, + REPORT_ID_KEY, + REPORT_NAME_KEY }); } @@ -148,8 +148,8 @@ namespace XenAdmin.Wlb /// public string Id { - get { return GetConfigValueString(base.BuildComplexKey(SUB_ID)); } - set { SetConfigValueString(base.BuildComplexKey(SUB_ID), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SUB_ID_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SUB_ID_KEY), value, true); } } /// @@ -157,8 +157,8 @@ namespace XenAdmin.Wlb /// public DateTime Created { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(CREATED)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(CREATED), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(CREATED_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(CREATED_KEY), value, true); } } /// @@ -166,8 +166,8 @@ namespace XenAdmin.Wlb /// public string Name { - get { return GetConfigValueString(base.BuildComplexKey(SUB_NAME)); } - set { SetConfigValueString(base.BuildComplexKey(SUB_NAME), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SUB_NAME_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SUB_NAME_KEY), value, true); } } /// @@ -175,8 +175,8 @@ namespace XenAdmin.Wlb /// public string Description { - get { return GetConfigValueString(base.BuildComplexKey(SUB_DESCRIPTION)); } - set { SetConfigValueString(base.BuildComplexKey(SUB_DESCRIPTION), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SUB_DESCRIPTION_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SUB_DESCRIPTION_KEY), value, true); } } /// @@ -184,8 +184,8 @@ namespace XenAdmin.Wlb /// public string SubscriberId { - get { return GetConfigValueString(base.BuildComplexKey(SUBSCRIBER_ID)); } - set { SetConfigValueString(base.BuildComplexKey(SUBSCRIBER_ID), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SUBSCRIBER_ID_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SUBSCRIBER_ID_KEY), value, true); } } /// @@ -193,8 +193,8 @@ namespace XenAdmin.Wlb /// public string SubscriberName { - get { return GetConfigValueString(base.BuildComplexKey(SUBSCRIBER_NAME)); } - set { SetConfigValueString(base.BuildComplexKey(SUBSCRIBER_NAME), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SUBSCRIBER_NAME_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SUBSCRIBER_NAME_KEY), value, true); } } /// @@ -202,8 +202,8 @@ namespace XenAdmin.Wlb /// public string ScheduleId { - get { return GetConfigValueString(base.BuildComplexKey(SCHEDULE_ID)); } - set { SetConfigValueString(base.BuildComplexKey(SCHEDULE_ID), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(SCHEDULE_ID_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(SCHEDULE_ID_KEY), value, true); } } /// @@ -211,8 +211,8 @@ namespace XenAdmin.Wlb /// public WlbScheduledTask.WlbTaskDaysOfWeek DaysOfWeek { - get { return (WlbScheduledTask.WlbTaskDaysOfWeek)GetConfigValueInt(base.BuildComplexKey(DAYOFWEEK)); } - set { SetConfigValueInt(base.BuildComplexKey(DAYOFWEEK), (int)value, true); } + get { return (WlbScheduledTask.WlbTaskDaysOfWeek)GetConfigValueInt(base.BuildComplexKey(DAYOFWEEK_KEY)); } + set { SetConfigValueInt(base.BuildComplexKey(DAYOFWEEK_KEY), (int)value, true); } } /// @@ -220,8 +220,8 @@ namespace XenAdmin.Wlb /// public DateTime RunTimeOfDay { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(EXECUTE_TIMEOFDAY)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(EXECUTE_TIMEOFDAY), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(EXECUTE_TIMEOFDAY_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(EXECUTE_TIMEOFDAY_KEY), value, true); } } /// @@ -229,8 +229,8 @@ namespace XenAdmin.Wlb /// public int TriggerType { - get { return GetConfigValueInt(base.BuildComplexKey(TRIGGER_TYPE)); } - set { SetConfigValueInt(base.BuildComplexKey(TRIGGER_TYPE), value, true); } + get { return GetConfigValueInt(base.BuildComplexKey(TRIGGER_TYPE_KEY)); } + set { SetConfigValueInt(base.BuildComplexKey(TRIGGER_TYPE_KEY), value, true); } } /// @@ -238,8 +238,8 @@ namespace XenAdmin.Wlb /// public bool Enabled { - get { return GetConfigValueBool(base.BuildComplexKey(ENABLED)); } - set { SetConfigValueBool(base.BuildComplexKey(ENABLED), value, true); } + get { return GetConfigValueBool(base.BuildComplexKey(ENABLED_KEY)); } + set { SetConfigValueBool(base.BuildComplexKey(ENABLED_KEY), value, true); } } /// @@ -247,8 +247,8 @@ namespace XenAdmin.Wlb /// public DateTime EnableDate { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(ENABLE_DATE)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(ENABLE_DATE), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(ENABLE_DATE_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(ENABLE_DATE_KEY), value, true); } } /// @@ -256,8 +256,8 @@ namespace XenAdmin.Wlb /// public DateTime DisableDate { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(DISABLE_DATE)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(DISABLE_DATE), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(DISABLE_DATE_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(DISABLE_DATE_KEY), value, true); } } /// @@ -265,8 +265,8 @@ namespace XenAdmin.Wlb /// public DateTime LastTouched { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(LAST_TOUCHED)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(LAST_TOUCHED), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(LAST_TOUCHED_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(LAST_TOUCHED_KEY), value, true); } } /// @@ -274,8 +274,8 @@ namespace XenAdmin.Wlb /// public string LastTouchedBy { - get { return GetConfigValueString(base.BuildComplexKey(LAST_TOUCHEDBY)); } - set { SetConfigValueString(base.BuildComplexKey(LAST_TOUCHEDBY), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(LAST_TOUCHEDBY_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(LAST_TOUCHEDBY_KEY), value, true); } } /// @@ -283,8 +283,8 @@ namespace XenAdmin.Wlb /// public DateTime LastRun { - get { return GetConfigValueUTCDateTime(base.BuildComplexKey(LAST_RUN)); } - set { SetConfigValueUTCDateTime(base.BuildComplexKey(LAST_RUN), value, true); } + get { return GetConfigValueUTCDateTime(base.BuildComplexKey(LAST_RUN_KEY)); } + set { SetConfigValueUTCDateTime(base.BuildComplexKey(LAST_RUN_KEY), value, true); } } /// @@ -292,8 +292,8 @@ namespace XenAdmin.Wlb /// public string LastRunResult { - get { return GetConfigValueString(base.BuildComplexKey(LAST_RUNRESULT)); } - set { SetConfigValueString(base.BuildComplexKey(LAST_RUNRESULT), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(LAST_RUNRESULT_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(LAST_RUNRESULT_KEY), value, true); } } /// @@ -301,8 +301,8 @@ namespace XenAdmin.Wlb /// public string EmailTo { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_TO)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_TO), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_TO_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_TO_KEY), value, true); } } /// @@ -310,8 +310,8 @@ namespace XenAdmin.Wlb /// public string EmailReplyTo { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_REPLYTO)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_REPLYTO), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_REPLYTO_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_REPLYTO_KEY), value, true); } } /// @@ -319,8 +319,8 @@ namespace XenAdmin.Wlb /// public int ReportRenderFormat { - get { return GetConfigValueInt(base.BuildComplexKey(REPORT_RENDERFORMAT)); } - set { SetConfigValueInt(base.BuildComplexKey(REPORT_RENDERFORMAT), (int)value, true); } + get { return GetConfigValueInt(base.BuildComplexKey(REPORT_RENDERFORMAT_KEY)); } + set { SetConfigValueInt(base.BuildComplexKey(REPORT_RENDERFORMAT_KEY), (int)value, true); } } /// @@ -328,8 +328,8 @@ namespace XenAdmin.Wlb /// public string EmailSubject { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_SUBJECT)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_SUBJECT), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_SUBJECT_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_SUBJECT_KEY), value, true); } } /// @@ -337,8 +337,8 @@ namespace XenAdmin.Wlb /// public string EmailComment { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_COMMENT)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_COMMENT), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_COMMENT_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_COMMENT_KEY), value, true); } } /// @@ -346,8 +346,8 @@ namespace XenAdmin.Wlb /// public string EmailCc { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_CC)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_CC), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_CC_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_CC_KEY), value, true); } } /// @@ -355,8 +355,8 @@ namespace XenAdmin.Wlb /// public string EmailBcc { - get { return GetConfigValueString(base.BuildComplexKey(EMAIL_BCC)); } - set { SetConfigValueString(base.BuildComplexKey(EMAIL_BCC), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(EMAIL_BCC_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(EMAIL_BCC_KEY), value, true); } } /// @@ -364,8 +364,8 @@ namespace XenAdmin.Wlb /// public int ReportId { - get { return GetConfigValueInt(base.BuildComplexKey(REPORT_ID)); } - set { SetConfigValueInt(base.BuildComplexKey(REPORT_ID), value, true); } + get { return GetConfigValueInt(base.BuildComplexKey(REPORT_ID_KEY)); } + set { SetConfigValueInt(base.BuildComplexKey(REPORT_ID_KEY), value, true); } } /// @@ -373,8 +373,8 @@ namespace XenAdmin.Wlb /// public string ReportName { - get { return GetConfigValueString(base.BuildComplexKey(REPORT_NAME)); } - set { SetConfigValueString(base.BuildComplexKey(REPORT_NAME), value, true); } + get { return GetConfigValueString(base.BuildComplexKey(REPORT_NAME_KEY)); } + set { SetConfigValueString(base.BuildComplexKey(REPORT_NAME_KEY), value, true); } } /// From 6f6c768913ae50117d12f60fa43e3637f4ef1e2e Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 26 Oct 2021 13:49:06 +0100 Subject: [PATCH 30/62] CP-38424: Bump `dotnet-packages` build location Signed-off-by: Danilo Del Busso --- packages/DOTNET_BUILD_LOCATION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/DOTNET_BUILD_LOCATION b/packages/DOTNET_BUILD_LOCATION index 28c745af7..4e274d991 100644 --- a/packages/DOTNET_BUILD_LOCATION +++ b/packages/DOTNET_BUILD_LOCATION @@ -1 +1 @@ -xc-local-release/dotnet-packages/master/37 +xc-local-release/dotnet-packages/master/39 From 688fe99e3e611bc2c174348789859b5523c7274b Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Mon, 18 Oct 2021 22:28:47 +0100 Subject: [PATCH 31/62] CA-359969: Do not rebuild the list if the scanning of the SRs has not finished yet. Removed unused code. Signed-off-by: Konstantina Chremmou --- XenAdmin/Controls/FlickerFreeListBox.cs | 128 +----------------------- XenAdmin/Controls/SrPicker.cs | 15 +-- 2 files changed, 14 insertions(+), 129 deletions(-) diff --git a/XenAdmin/Controls/FlickerFreeListBox.cs b/XenAdmin/Controls/FlickerFreeListBox.cs index 693ea129c..7fcdf6869 100644 --- a/XenAdmin/Controls/FlickerFreeListBox.cs +++ b/XenAdmin/Controls/FlickerFreeListBox.cs @@ -33,7 +33,6 @@ using System; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; -using XenAdmin.Core; using XenCenterLib; namespace XenAdmin.Controls @@ -62,8 +61,8 @@ namespace XenAdmin.Controls /// The handle of the horizontal scrollbar of this ListBox /// private IntPtr _hScrollbarHandle = IntPtr.Zero; - public WndProcCancelDelegate CancelWndProc = new WndProcCancelDelegate(delegate(Message msg) { return false; }); + public Func CancelWndProc = msg => false; protected override void WndProc(ref Message msg) { @@ -92,7 +91,7 @@ namespace XenAdmin.Controls base.Invalidate(); } - if(!CancelWndProc(msg)) + if (!CancelWndProc(msg)) base.WndProc(ref msg); } @@ -118,18 +117,12 @@ namespace XenAdmin.Controls base.OnMouseWheel(e); } - private ContextMenuStrip _contextMenuStrip = null; + private ContextMenuStrip _contextMenuStrip; public override ContextMenuStrip ContextMenuStrip { - get - { - return _contextMenuStrip; - } - set - { - _contextMenuStrip = value; - } + get => _contextMenuStrip; + set => _contextMenuStrip = value; } protected override void OnKeyUp(KeyEventArgs e) @@ -233,115 +226,6 @@ namespace XenAdmin.Controls Refresh(); } - public const int RIGHT_PADDING = 5; - - public void WilkieSpecial(Image icon, string text, string extraText, Color extraTextColor, Font extraTextFont, DrawItemEventArgs e) - { - Graphics g = e.Graphics; - - WSPaintBG(e, this); - - // This is the rect where we want to put the text pair - Rectangle bounds = new Rectangle(e.Bounds.Height, e.Bounds.Y, e.Bounds.Width - e.Bounds.Height - RIGHT_PADDING, e.Bounds.Height); - - String display; - Size s = WSDrawTextPair(this, text, extraText, extraTextColor, extraTextFont, e, bounds, true, out display); - - WSDrawSelectRect(e, bounds.Height + s.Width); - - WSDrawLeftImage(icon, e); - - // And the text - Drawing.DrawText(g, display, e.Font, - bounds, e.ForeColor, e.BackColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter); - } - - private static void WSDrawSelectRect(DrawItemEventArgs e, int width) - { - Graphics g = e.Graphics; - - Rectangle selectionRectangle = new Rectangle(e.Bounds.Location, e.Bounds.Size); - selectionRectangle.Width = width; - - using (SolidBrush backBrush = new SolidBrush(e.BackColor)) - { - g.FillRectangle(backBrush, selectionRectangle); - } - } - - private static Color GetBackColorFor(Control control) - { - return !control.Enabled ? SystemColors.Control : control.BackColor; - } - - private static void WSDrawLeftImage(Image icon, DrawItemEventArgs e) - { - Graphics g = e.Graphics; - - g.DrawImage(icon, e.Bounds.Left + 1, e.Bounds.Top + 1, e.Bounds.Height - 2, e.Bounds.Height - 2); - } - - private static Size WSDrawTextPair(Control control, String text, String extraText, Color extraTextColor, Font extraTextFont, DrawItemEventArgs e, Rectangle bounds, bool ShowSelectOnExtraText, out String display) - { - Graphics g = e.Graphics; - g.TextRenderingHint = Drawing.TextRenderingHint; - - display = text; - Size s = Drawing.MeasureText(g, display, e.Font, - bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter); - - if (extraText == null) - return s; - - // We're going to have the extra text take precedent over the text, - // so shrink the text and put ellipses on until it measures up - - Size t = Drawing.MeasureText(g, extraText, extraTextFont, - bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter); - - int trim = text.Length; - - while (s.Width + t.Width + 10 > bounds.Width && trim > 0) - { - trim--; - - display = text.Ellipsise(trim); - - s = Drawing.MeasureText(g, display, e.Font, - bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter); - } - - Color backColor = ShowSelectOnExtraText && control.Focused && e.State == DrawItemState.Selected - ? Color.LightGray - : GetBackColorFor(control); - - if (ShowSelectOnExtraText) - { - Rectangle greySelectionRectangle = new Rectangle(bounds.Width - t.Width + bounds.X, bounds.Y + 2, t.Width, t.Height); - - using (SolidBrush brush = new SolidBrush(backColor)) - { - g.FillRectangle(brush, greySelectionRectangle); - } - } - - Drawing.DrawText(g, extraText, extraTextFont, - bounds, extraTextColor, backColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter); - - return s; - } - - private static void WSPaintBG(DrawItemEventArgs e, Control control) - { - Graphics g = e.Graphics; - Color color = GetBackColorFor(control); - - using (SolidBrush backBrush = new SolidBrush(color)) - { - g.FillRectangle(backBrush, e.Bounds); - } - } - protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); @@ -354,6 +238,4 @@ namespace XenAdmin.Controls this.Refresh(); } } - - public delegate bool WndProcCancelDelegate(Message msg); } diff --git a/XenAdmin/Controls/SrPicker.cs b/XenAdmin/Controls/SrPicker.cs index 9917e5a3e..35bbb5845 100644 --- a/XenAdmin/Controls/SrPicker.cs +++ b/XenAdmin/Controls/SrPicker.cs @@ -137,12 +137,8 @@ namespace XenAdmin.Controls if (_scanCount > 0) return; - - Program.Invoke(this, () => - { - Invalidate(); - Rebuild(items, preselectedSR); - }); + + Program.Invoke(this, () => Rebuild(items, preselectedSR)); }; action.RunAsync(); } @@ -177,6 +173,7 @@ namespace XenAdmin.Controls private void Rebuild(List items = null, SR preselectedSr = null) { Program.AssertOnEventThread(); + Invalidate(); SR selectedSr = preselectedSr ?? SR; var theItems = items ?? GetSrPickerItems(); @@ -213,12 +210,18 @@ namespace XenAdmin.Controls private void Server_PropertyChanged(object sender, PropertyChangedEventArgs e) { + if (_scanCount > 0) + return; + if (e.PropertyName == "name_label" || e.PropertyName == "PBDs" || e.PropertyName == "physical_utilisation" || e.PropertyName == "currently_attached" || e.PropertyName == "default_SR") Program.Invoke(this, () => Rebuild()); } private void SR_CollectionChanged(object sender, CollectionChangeEventArgs e) { + if (_scanCount > 0) + return; + Program.Invoke(this, () => Rebuild()); } From 2978f60f8a0deab25287b04c1108f517d63f6d01 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 3 Nov 2021 10:23:21 +0000 Subject: [PATCH 32/62] CP-36392: Improve readability of latest changes Signed-off-by: Danilo Del Busso --- XenAdmin/Plugins/Features/MenuItemFeature.cs | 28 +++++++++---------- .../GenericSelectHostsPage.cs | 6 ++-- .../DRWizards/DRFailoverWizardStoragePage.cs | 2 +- XenModel/ServerDBs/FakeAPI/fakeHost.cs | 2 +- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/XenAdmin/Plugins/Features/MenuItemFeature.cs b/XenAdmin/Plugins/Features/MenuItemFeature.cs index 22cb931e7..4c215b65f 100644 --- a/XenAdmin/Plugins/Features/MenuItemFeature.cs +++ b/XenAdmin/Plugins/Features/MenuItemFeature.cs @@ -85,21 +85,21 @@ namespace XenAdmin.Plugins ContextMenu = Helpers.GetEnumXmlAttribute(node, ATT_CONTEXT_MENU, GetContextMenuFromMenu(Menu)); Serialized = Helpers.GetEnumXmlAttribute(node, ATT_SERIALIZED, PluginSerializationLevel.none); - if (node.ChildNodes.Count <= 0) - return; - - var child = node.ChildNodes[0]; - switch (child.Name) + if (node.ChildNodes.Count > 0) { - case TYPE_SHELL: - ShellCmd = new ShellCmd(child, paramsFromXML(child)); - break; - case TYPE_POWERSHELL: - ShellCmd = new PowerShellCmd(child, paramsFromXML(child)); - break; - case TYPE_XENSERVER_POWERSHELL: - ShellCmd = new XenServerPowershellCmd(child, paramsFromXML(child)); - break; + var child = node.ChildNodes[0]; + switch (child.Name) + { + case TYPE_SHELL: + ShellCmd = new ShellCmd(child, paramsFromXML(child)); + break; + case TYPE_POWERSHELL: + ShellCmd = new PowerShellCmd(child, paramsFromXML(child)); + break; + case TYPE_XENSERVER_POWERSHELL: + ShellCmd = new XenServerPowershellCmd(child, paramsFromXML(child)); + break; + } } } diff --git a/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs b/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs index bf9e733a5..24ada42d0 100644 --- a/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs +++ b/XenAdmin/Wizards/BugToolWizardFiles/GenericSelectHostsPage.cs @@ -121,10 +121,12 @@ namespace XenAdmin.Wizards.BugToolWizardFiles if (host != null && selectedObjects.Contains(host)) node.State = CheckState.Checked; } + + var checkedItems = HostListTreeView.CheckedItems(); //focus on first checked item so the user can find it in a long list - if (HostListTreeView.CheckedItems().Count > 0) + if (checkedItems.Count > 0) { - HostListTreeView.SelectedItems.Add(HostListTreeView.CheckedItems().First()); + HostListTreeView.SelectedItems.Add(checkedItems.First()); } HostListTreeView.EndUpdate(); diff --git a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs index 1243a61a1..b119be54e 100644 --- a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs +++ b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs @@ -622,7 +622,7 @@ namespace XenAdmin.Wizards.DRWizards { row = null; var srRows = dataGridViewSRs.Rows.Cast().Where(srRow => srRow.SrUuid == uuid).ToList(); - if (srRows.Count <= 0) + if (srRows.Count == 0) return false; row = srRows.First(); diff --git a/XenModel/ServerDBs/FakeAPI/fakeHost.cs b/XenModel/ServerDBs/FakeAPI/fakeHost.cs index d86a9a0b3..8fc2a30ea 100644 --- a/XenModel/ServerDBs/FakeAPI/fakeHost.cs +++ b/XenModel/ServerDBs/FakeAPI/fakeHost.cs @@ -111,7 +111,7 @@ namespace XenAdmin.ServerDBs.FakeAPI var metrics_ref = (string)proxy.db.GetValue("host", opaque_ref, "metrics"); proxy.EditObject_(DbProxy.EditTypes.Replace, "host_metrics", metrics_ref, "live", false); - var coordinator_ref = ""; + var coordinator_ref = string.Empty; var pools = proxy.db.Tables["pool"].Rows.Keys; if (pools.Count > 0) { From 0924563cffa1a822a3fff4b68f80f9bc89e1342e Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 2 Aug 2021 14:25:40 +0100 Subject: [PATCH 33/62] CA-350411: Add conditional page control refresh in Import Wizard Signed-off-by: Danilo Del Busso CA-350411: Tidy up local variables within ImportWizard * Use of local variables for readibility. * Fixed ordering issue which caused if block to check for condition too late. * Add connection and type of import checks before adding/removing boot options page Signed-off-by: Danilo Del Busso CA-350411: Update visibility settings in fields needed for fix Fields were either read-only, or private. Internal accessor settings allows for external modification and checks. Signed-off-by: Danilo Del Busso CA-350411: Add checks for the `ImportSourcePage` and `GlobalSelectHost` page types Also remove unused methods in `NetworkPickerPage.cs` and `StoragePickerPage.cs` Signed-off-by: Danilo Del Busso --- .../Wizards/ImportWizard/ImageVMConfigPage.cs | 2 +- .../Wizards/ImportWizard/ImportEulaPage.cs | 2 +- .../ImportWizard/ImportSecurityPage.cs | 2 +- .../ImportWizard/ImportSelectHostPage.cs | 2 +- .../ImportWizard/ImportSelectNetworkPage.cs | 2 +- .../ImportWizard/ImportSelectStoragePage.cs | 2 +- XenAdmin/Wizards/ImportWizard/ImportWizard.cs | 776 ++++++++++-------- .../ImportWizard/LunPerVdiImportPage.cs | 2 +- .../Wizards/ImportWizard/NetworkPickerPage.cs | 40 +- .../Wizards/ImportWizard/StoragePickerPage.cs | 36 +- 10 files changed, 445 insertions(+), 421 deletions(-) diff --git a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs index 3bf250a90..70bb08e0b 100644 --- a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs @@ -97,7 +97,7 @@ namespace XenAdmin.Wizards.ImportWizard #region Accessors - public bool IsWim { private get; set; } + public bool IsWim { internal get; set; } public string VmName { get { return m_textBoxVMName.Text; } } diff --git a/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs b/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs index eb576a959..7cf5d7da1 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs @@ -141,7 +141,7 @@ namespace XenAdmin.Wizards.ImportWizard #region Accessors - public EnvelopeType SelectedOvfEnvelope { private get; set; } + public EnvelopeType SelectedOvfEnvelope { internal get; set; } #endregion diff --git a/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs index 9d8695ff9..ffaabb95f 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs @@ -137,7 +137,7 @@ namespace XenAdmin.Wizards.ImportWizard /// /// Package containing the selected OVF appliance. /// - public Package SelectedOvfPackage { private get; set; } + public Package SelectedOvfPackage { internal get; set; } #endregion diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs index e7b8f55d2..21612b073 100755 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs @@ -80,7 +80,7 @@ namespace XenAdmin.Wizards.ImportWizard public EnvelopeType SelectedOvfEnvelope { - private get + internal get { return _selectedOvfEnvelope; } diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs index 724463242..807903505 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs @@ -85,7 +85,7 @@ namespace XenAdmin.Wizards.ImportWizard return false; } - public EnvelopeType SelectedOvfEnvelope { private get; set; } + public EnvelopeType SelectedOvfEnvelope { get; set; } protected override string IntroductionText => Messages.IMPORT_WIZARD_NETWORKING_INTRO; diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs index b58f8f434..cbd6732f5 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs @@ -56,7 +56,7 @@ namespace XenAdmin.Wizards.ImportWizard return true; } - public EnvelopeType SelectedOvfEnvelope { private get; set; } + public EnvelopeType SelectedOvfEnvelope { get; set; } public override StorageResourceContainer ResourceData(string sysId) { diff --git a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs index 6c424e291..ab06d95a1 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs @@ -51,9 +51,9 @@ using Tuple = System.Collections.Generic.KeyValuePair; namespace XenAdmin.Wizards.ImportWizard { - internal partial class ImportWizard : XenWizardBase - { - #region Private fields + internal partial class ImportWizard : XenWizardBase + { + #region Private fields private readonly ImportSelectStoragePage m_pageStorage; private readonly ImportSelectNetworkPage m_pageNetwork; private readonly ImportSelectHostPage m_pageHost; @@ -71,63 +71,63 @@ namespace XenAdmin.Wizards.ImportWizard private readonly ImportBootOptionPage m_pageBootOptions; private IXenObject m_selectedObject; - private Dictionary m_vmMappings = new Dictionary(); - /// - /// Make this nullable and initialize with null so the pages are added correctly to the wizard progress the first time - /// - private ImportType? m_typeOfImport; - private bool m_ignoreAffinitySet; - private EnvelopeType m_envelopeFromVhd; + private Dictionary m_vmMappings = new Dictionary(); + /// + /// Make this nullable and initialize with null so the pages are added correctly to the wizard progress the first time + /// + private ImportType? m_typeOfImport; + private bool m_ignoreAffinitySet; + private EnvelopeType m_envelopeFromVhd; private IXenConnection TargetConnection { get; set; } - #endregion + #endregion - public ImportWizard(IXenConnection con, IXenObject xenObject, string filename, bool ovfModeOnly) - : base(con) - { - InitializeComponent(); + public ImportWizard(IXenConnection con, IXenObject xenObject, string filename, bool ovfModeOnly) + : base(con) + { + InitializeComponent(); - m_pageStorage = new ImportSelectStoragePage(); - m_pageNetwork = new ImportSelectNetworkPage(); - m_pageHost = new ImportSelectHostPage(); - m_pageSecurity = new ImportSecurityPage(); - m_pageEula = new ImportEulaPage(); - m_pageOptions = new ImportOptionsPage(); - m_pageFinish = new ImportFinishPage(); - m_pageRbac = new RBACWarningPage(); - m_pageVMconfig = new ImageVMConfigPage(); - m_pageImportSource = new ImportSourcePage(); - m_pageXvaStorage = new StoragePickerPage(); - m_pageXvaNetwork = new NetworkPickerPage(); - m_pageXvaHost = new GlobalSelectHost(); + m_pageStorage = new ImportSelectStoragePage(); + m_pageNetwork = new ImportSelectNetworkPage(); + m_pageHost = new ImportSelectHostPage(); + m_pageSecurity = new ImportSecurityPage(); + m_pageEula = new ImportEulaPage(); + m_pageOptions = new ImportOptionsPage(); + m_pageFinish = new ImportFinishPage(); + m_pageRbac = new RBACWarningPage(); + m_pageVMconfig = new ImageVMConfigPage(); + m_pageImportSource = new ImportSourcePage(); + m_pageXvaStorage = new StoragePickerPage(); + m_pageXvaNetwork = new NetworkPickerPage(); + m_pageXvaHost = new GlobalSelectHost(); lunPerVdiMappingPage = new LunPerVdiImportPage { Connection = con }; - m_pageBootOptions = new ImportBootOptionPage(); + m_pageBootOptions = new ImportBootOptionPage(); - m_selectedObject = xenObject; - m_pageFinish.SummaryRetriever = GetSummary; - m_pageXvaStorage.ImportVmCompleted += m_pageXvaStorage_ImportVmCompleted; + m_selectedObject = xenObject; + m_pageFinish.SummaryRetriever = GetSummary; + m_pageXvaStorage.ImportVmCompleted += m_pageXvaStorage_ImportVmCompleted; - if (!string.IsNullOrEmpty(filename)) - m_pageImportSource.SetFileName(filename); + if (!string.IsNullOrEmpty(filename)) + m_pageImportSource.SetFileName(filename); - m_pageImportSource.OvfModeOnly = ovfModeOnly; + m_pageImportSource.OvfModeOnly = ovfModeOnly; AddPages(m_pageImportSource, m_pageHost, m_pageStorage, m_pageNetwork, m_pageFinish); m_pageHost.ConnectionSelectionChanged += pageHost_ConnectionSelectionChanged; m_pageXvaHost.ConnectionSelectionChanged += pageHost_ConnectionSelectionChanged; ShowXenAppXenDesktopWarning(con); - } + } - #region Override (XenWizardBase) Methods + #region Override (XenWizardBase) Methods protected override void FinishWizard() - { - switch (m_typeOfImport) - { - case ImportType.Xva: - if (m_pageXvaStorage.ImportXvaAction != null) - m_pageXvaStorage.ImportXvaAction.EndWizard(m_pageFinish.StartVmsAutomatically, m_pageXvaNetwork.VIFs); - break; - case ImportType.Ovf: + { + switch (m_typeOfImport) + { + case ImportType.Xva: + if (m_pageXvaStorage.ImportXvaAction != null) + m_pageXvaStorage.ImportXvaAction.EndWizard(m_pageFinish.StartVmsAutomatically, m_pageXvaNetwork.VIFs); + break; + case ImportType.Ovf: new ImportApplianceAction(TargetConnection, m_pageImportSource.SelectedOvfPackage, m_vmMappings, @@ -137,8 +137,8 @@ namespace XenAdmin.Wizards.ImportWizard m_pageOptions.RunFixups, m_pageOptions.SelectedIsoSR, m_pageFinish.StartVmsAutomatically).RunAsync(); - break; - case ImportType.Vhd: + break; + case ImportType.Vhd: new ImportImageAction(TargetConnection, m_envelopeFromVhd, Path.GetDirectoryName(m_pageImportSource.FilePath), @@ -148,180 +148,228 @@ namespace XenAdmin.Wizards.ImportWizard m_pageFinish.StartVmsAutomatically, VMOperationCommand.WarningDialogHAInvalidConfig, VMOperationCommand.StartDiagnosisForm).RunAsync(); - break; - } + break; + } - base.FinishWizard(); - } + base.FinishWizard(); + } - protected override void OnCancel(ref bool cancel) - { - base.OnCancel(ref cancel); + protected override void OnCancel(ref bool cancel) + { + base.OnCancel(ref cancel); - if (cancel) - return; + if (cancel) + return; - if (m_pageXvaStorage.ImportXvaAction != null) - { - m_pageXvaStorage.ImportXvaAction.EndWizard(false, null); - m_pageXvaStorage.ImportXvaAction.Cancel(); - } - } + if (m_pageXvaStorage.ImportXvaAction != null) + { + m_pageXvaStorage.ImportXvaAction.EndWizard(false, null); + m_pageXvaStorage.ImportXvaAction.Cancel(); + } + } protected override void UpdateWizardContent(XenTabPage page) - { - Type type = page.GetType(); + { + var type = page.GetType(); + var oldTypeOfImport = m_typeOfImport; //store previous type - if (type == typeof(ImportSourcePage)) - { - #region ImportSourcePage + if (type == typeof(ImportSourcePage)) + { + #region ImportSourcePage - var oldTypeOfImport = m_typeOfImport;//store previous type - m_typeOfImport = m_pageImportSource.TypeOfImport; - var appliancePages = new XenTabPage[] {m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions}; + m_typeOfImport = m_pageImportSource.TypeOfImport; + var appliancePages = new XenTabPage[] { m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions }; var imagePages = new XenTabPage[] { m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions }; var xvaPages = new XenTabPage[] { m_pageXvaHost, m_pageXvaStorage, m_pageXvaNetwork }; + var newVmMappings = m_vmMappings; - switch (m_typeOfImport) - { - case ImportType.Ovf: - if (oldTypeOfImport != ImportType.Ovf) - { - Text = Messages.WIZARD_TEXT_IMPORT_OVF; - pictureBoxWizard.Image = Images.StaticImages._000_ImportVirtualAppliance_h32bit_32; + switch (m_typeOfImport) + { + case ImportType.Ovf: + if (oldTypeOfImport != ImportType.Ovf) + { + Text = Messages.WIZARD_TEXT_IMPORT_OVF; + pictureBoxWizard.Image = Images.StaticImages._000_ImportVirtualAppliance_h32bit_32; RemovePages(imagePages); RemovePage(m_pageBootOptions); RemovePages(xvaPages); AddAfterPage(m_pageImportSource, appliancePages); - } + } + var newSelectedOvfPackage = m_pageImportSource.SelectedOvfPackage; + var newSelectedOvfEnvelope = newSelectedOvfPackage.OvfEnvelope; - m_pageEula.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope; - m_pageSecurity.SelectedOvfPackage = m_pageImportSource.SelectedOvfPackage; + if (oldTypeOfImport != ImportType.Ovf + || m_pageSecurity.SelectedOvfPackage != newSelectedOvfPackage + || m_pageEula.SelectedOvfEnvelope != newSelectedOvfEnvelope + || m_pageHost.SelectedOvfEnvelope != newSelectedOvfEnvelope + || m_pageHost.VmMappings != newVmMappings + || m_pageStorage.SelectedOvfEnvelope != newSelectedOvfEnvelope + || lunPerVdiMappingPage.SelectedOvfEnvelope != newSelectedOvfEnvelope + || m_pageHost.SelectedOvfEnvelope != newSelectedOvfEnvelope) + { + m_pageEula.SelectedOvfEnvelope = newSelectedOvfEnvelope; + m_pageSecurity.SelectedOvfPackage = newSelectedOvfPackage; - CheckDisabledPages(m_pageEula, m_pageSecurity); //decide whether to disable these progress steps - ResetVmMappings(m_pageImportSource.SelectedOvfPackage.OvfEnvelope); - m_pageHost.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope; - m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); - m_pageHost.VmMappings = m_vmMappings; - m_pageStorage.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope; - lunPerVdiMappingPage.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope; - m_pageNetwork.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope; - - NotifyNextPagesOfChange(m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions); - break; - case ImportType.Vhd: - if (oldTypeOfImport != ImportType.Vhd) - { - Text = Messages.WIZARD_TEXT_IMPORT_VHD; - pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32; + CheckDisabledPages(m_pageEula, m_pageSecurity); //decide whether to disable these progress steps + ResetVmMappings(newSelectedOvfEnvelope); + m_pageHost.SelectedOvfEnvelope = newSelectedOvfEnvelope; + m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); + m_pageHost.VmMappings = newVmMappings; + m_pageStorage.SelectedOvfEnvelope = newSelectedOvfEnvelope; + lunPerVdiMappingPage.SelectedOvfEnvelope = newSelectedOvfEnvelope; + m_pageNetwork.SelectedOvfEnvelope = newSelectedOvfEnvelope; + + NotifyNextPagesOfChange(m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions); + } + break; + case ImportType.Vhd: + if (oldTypeOfImport != ImportType.Vhd) + { + Text = Messages.WIZARD_TEXT_IMPORT_VHD; + pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32; RemovePages(appliancePages); RemovePages(xvaPages); AddAfterPage(m_pageImportSource, imagePages); - } - m_pageVMconfig.IsWim = m_pageImportSource.IsWIM; - m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); - m_pageHost.SelectedOvfEnvelope = null; - m_pageHost.VmMappings = m_vmMappings; - NotifyNextPagesOfChange(m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions); - break; - case ImportType.Xva: - if (oldTypeOfImport != ImportType.Xva) - { - Text = Messages.WIZARD_TEXT_IMPORT_XVA; - pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32; + } + + var newIsWim = m_pageImportSource.IsWIM; + + if (oldTypeOfImport != ImportType.Vhd + || m_pageVMconfig.IsWim != newIsWim + || m_pageHost.VmMappings != newVmMappings + || m_pageHost.SelectedOvfEnvelope != null) + { + m_pageVMconfig.IsWim = newIsWim; + m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); + m_pageHost.SelectedOvfEnvelope = null; + m_pageHost.VmMappings = newVmMappings; + NotifyNextPagesOfChange(m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions); + } + break; + case ImportType.Xva: + if (oldTypeOfImport != ImportType.Xva) + { + Text = Messages.WIZARD_TEXT_IMPORT_XVA; + pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32; RemovePages(imagePages); - RemovePage(m_pageBootOptions); + RemovePage(m_pageBootOptions); RemovePages(appliancePages); AddAfterPage(m_pageImportSource, xvaPages); - } - m_pageXvaHost.SetDefaultTarget(m_selectedObject); - m_pageXvaStorage.FilePath = m_pageImportSource.FilePath; - break; - } + } + m_pageXvaHost.SetDefaultTarget(m_selectedObject); + m_pageXvaStorage.FilePath = m_pageImportSource.FilePath; + break; + } - #endregion - } - else if (type == typeof(ImageVMConfigPage)) - { + #endregion + } + else if (type == typeof(ImageVMConfigPage)) + { //then use it to create an ovf for the import - m_envelopeFromVhd = OVF.CreateOvfEnvelope(m_pageVMconfig.VmName, + var newEnvelope = OVF.CreateOvfEnvelope(m_pageVMconfig.VmName, m_pageVMconfig.CpuCount, m_pageVMconfig.Memory, m_pageBootOptions.BootParams, m_pageBootOptions.PlatformSettings, m_pageImportSource.DiskCapacity, m_pageImportSource.IsWIM, m_pageVMconfig.AdditionalSpace, m_pageImportSource.FilePath, m_pageImportSource.ImageLength, BrandManager.ProductBrand); - m_pageStorage.SelectedOvfEnvelope = m_envelopeFromVhd; - lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd; - m_pageNetwork.SelectedOvfEnvelope = m_envelopeFromVhd; - ResetVmMappings(m_envelopeFromVhd); - NotifyNextPagesOfChange(m_pageHost, m_pageStorage, m_pageNetwork); - } - else if (type == typeof(ImportSelectHostPage)) - { - TargetConnection = m_pageHost.ChosenItem == null ? null : m_pageHost.ChosenItem.Connection; + if (newEnvelope != m_envelopeFromVhd) + { + ResetVmMappings(m_envelopeFromVhd); + NotifyNextPagesOfChange(m_pageHost, m_pageStorage, m_pageNetwork); + } + + m_envelopeFromVhd = newEnvelope; + m_pageStorage.SelectedOvfEnvelope = m_envelopeFromVhd; + lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd; + m_pageNetwork.SelectedOvfEnvelope = m_envelopeFromVhd; + } + else if (type == typeof(ImportSelectHostPage)) + { + var newConnection = m_pageHost.ChosenItem?.Connection; + var newMappings = m_pageHost.VmMappings; + RemovePage(m_pageRbac); ConfigureRbacPage(TargetConnection); - m_vmMappings = m_pageHost.VmMappings; + + if (m_pageStorage.VmMappings != newMappings + || m_pageNetwork.Connection != newConnection + || m_pageOptions.Connection != newConnection) + NotifyNextPagesOfChange(m_pageStorage, m_pageNetwork, m_pageOptions); + + if (m_pageBootOptions.Connection != newConnection && m_typeOfImport != oldTypeOfImport) + { + RemovePage(m_pageBootOptions); + if (m_typeOfImport == ImportType.Vhd && BootModesControl.ShowBootModeOptions(TargetConnection)) + { + AddAfterPage(m_pageNetwork, m_pageBootOptions); + } + } + + m_vmMappings = newMappings; + TargetConnection = newConnection; + m_pageStorage.VmMappings = m_vmMappings; m_pageStorage.Connection = TargetConnection; m_pageNetwork.Connection = TargetConnection; m_pageOptions.Connection = TargetConnection; - RemovePage(m_pageBootOptions); - if (m_typeOfImport == ImportType.Vhd && BootModesControl.ShowBootModeOptions(TargetConnection)) - { - AddAfterPage(m_pageNetwork, m_pageBootOptions); - m_pageBootOptions.Connection = TargetConnection; - } - m_pageBootOptions.Connection = TargetConnection; - NotifyNextPagesOfChange(m_pageStorage, m_pageNetwork, m_pageOptions); - } - else if (type == typeof(ImportSelectStoragePage)) - { - RemovePage(lunPerVdiMappingPage); - lunPerVdiMappingPage.ClearPickerData(); - m_vmMappings = m_pageStorage.VmMappings; - m_pageNetwork.VmMappings = m_vmMappings; + m_pageBootOptions.Connection = TargetConnection; + } + else if (type == typeof(ImportSelectStoragePage)) + { + RemovePage(lunPerVdiMappingPage); + lunPerVdiMappingPage.ClearPickerData(); + m_vmMappings = m_pageStorage.VmMappings; + m_pageNetwork.VmMappings = m_vmMappings; lunPerVdiMappingPage.VmMappings = m_vmMappings; - if (lunPerVdiMappingPage.IsAnyPickerDataMappable + if (lunPerVdiMappingPage.IsAnyPickerDataMappable && lunPerVdiMappingPage.MapLunsToVdisRequired && m_typeOfImport == ImportType.Ovf) AddAfterPage(m_pageStorage, lunPerVdiMappingPage); - } + } else if (type == typeof(LunPerVdiImportPage)) { m_vmMappings = lunPerVdiMappingPage.VmMappings; m_pageNetwork.VmMappings = m_vmMappings; } - else if (type == typeof(ImportSelectNetworkPage)) - { - m_vmMappings = m_pageNetwork.VmMappings; - m_pageOptions.VmMappings = m_vmMappings; - } - else if (type == typeof(GlobalSelectHost)) - { - var con = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection; + else if (type == typeof(ImportSelectNetworkPage)) + { + m_vmMappings = m_pageNetwork.VmMappings; + m_pageOptions.VmMappings = m_vmMappings; + } + else if (type == typeof(GlobalSelectHost)) + { + var newConnection = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection; + var newStorageTargetHost = m_ignoreAffinitySet ? null : m_pageXvaHost.SelectedHost; + var newNetworkSelectedHost = m_pageXvaHost.SelectedHost; + RemovePage(m_pageRbac); - ConfigureRbacPage(con); + ConfigureRbacPage(newConnection); - m_pageXvaStorage.SetConnection(con); - m_pageXvaStorage.SetTargetHost(m_ignoreAffinitySet ? null : m_pageXvaHost.SelectedHost); + if (m_pageXvaStorage.MTargetConnection != newConnection + || m_pageXvaNetwork.MSelectedConnection != newConnection + || !m_pageXvaNetwork.MSelectedAffinity.Equals(newNetworkSelectedHost) + || !m_pageXvaStorage.MTargetHost.Equals(newStorageTargetHost) + ) + NotifyNextPagesOfChange(m_pageXvaStorage, m_pageXvaNetwork); - m_pageXvaNetwork.SetConnection(con); - m_pageXvaNetwork.SetAffinity(m_pageXvaHost.SelectedHost); - - NotifyNextPagesOfChange(m_pageXvaStorage, m_pageXvaNetwork); - } - else if (type == typeof(StoragePickerPage)) - { - m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; - m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); - NotifyNextPagesOfChange(m_pageXvaNetwork); - } + m_pageXvaStorage.MTargetConnection = newConnection; + m_pageXvaStorage.MTargetHost = newStorageTargetHost; - if (type != typeof(ImportFinishPage)) - NotifyNextPagesOfChange(m_pageFinish); - } + m_pageXvaNetwork.MSelectedConnection = newConnection; + m_pageXvaNetwork.MSelectedAffinity = m_pageXvaHost.SelectedHost; + + } + else if (type == typeof(StoragePickerPage)) + { + m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; + m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); + NotifyNextPagesOfChange(m_pageXvaNetwork); + } + + if (type != typeof(ImportFinishPage)) + NotifyNextPagesOfChange(m_pageFinish); + } protected override string WizardPaneHelpID() { @@ -395,9 +443,9 @@ namespace XenAdmin.Wizards.ImportWizard return base.WizardPaneHelpID(); } - #endregion + #endregion - #region Private methods + #region Private methods private void ConfigureRbacPage(IXenConnection selectedConnection) { @@ -405,34 +453,34 @@ namespace XenAdmin.Wizards.ImportWizard Helpers.GetCoordinator(selectedConnection).external_auth_type == Auth.AUTH_TYPE_NONE) return; - m_pageRbac.ClearPermissionChecks(); - m_ignoreAffinitySet = false; + m_pageRbac.ClearPermissionChecks(); + m_ignoreAffinitySet = false; - switch (m_typeOfImport) - { - case ImportType.Ovf: - case ImportType.Vhd: - { - var check = m_typeOfImport == ImportType.Ovf - ? new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_APPLIANCE) {Blocking = true} - : new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_IMAGE) {Blocking = true}; - check.AddApiCheckRange(ApplianceAction.StaticRBACDependencies); - m_pageRbac.AddPermissionChecks(selectedConnection, check); + switch (m_typeOfImport) + { + case ImportType.Ovf: + case ImportType.Vhd: + { + var check = m_typeOfImport == ImportType.Ovf + ? new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_APPLIANCE) { Blocking = true } + : new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_IMAGE) { Blocking = true }; + check.AddApiCheckRange(ApplianceAction.StaticRBACDependencies); + m_pageRbac.AddPermissionChecks(selectedConnection, check); AddAfterPage(m_pageHost, m_pageRbac); - } - break; - case ImportType.Xva: - { - //Check to see if they can import VMs at all - var importCheck = new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_XVA) {Blocking = true}; - importCheck.ApiCallsToCheck.AddRange(ImportVmAction.ConstantRBACRequirements); + } + break; + case ImportType.Xva: + { + //Check to see if they can import VMs at all + var importCheck = new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_XVA) { Blocking = true }; + importCheck.ApiCallsToCheck.AddRange(ImportVmAction.ConstantRBACRequirements); importCheck.ApiCallsToCheck.Add("sr.scan");//CA-337323 - //Check to see if they can set the VM's affinity - var affinityCheck = new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_AFFINITY); - affinityCheck.ApiCallsToCheck.Add("vm.set_affinity"); - affinityCheck.WarningAction = delegate + //Check to see if they can set the VM's affinity + var affinityCheck = new RBACWarningPage.WizardPermissionCheck(Messages.RBAC_WARNING_IMPORT_WIZARD_AFFINITY); + affinityCheck.ApiCallsToCheck.Add("vm.set_affinity"); + affinityCheck.WarningAction = delegate { //We cannot allow them to set the affinity, so we are only going //to offer them the choice of connection, not specific host @@ -440,167 +488,167 @@ namespace XenAdmin.Wizards.ImportWizard }; m_pageRbac.AddPermissionChecks(selectedConnection, importCheck, affinityCheck); AddAfterPage(m_pageXvaHost, m_pageRbac); - } - break; - } + } + break; + } - //set page Connection after the page has been added to the wizard - //(because the Connection is reset when the page is added - m_pageRbac.Connection = selectedConnection; - } + //set page Connection after the page has been added to the wizard + //(because the Connection is reset when the page is added + m_pageRbac.Connection = selectedConnection; + } private void CheckDisabledPages(params XenTabPage[] pages) - { - foreach (var p in pages) - p.CheckPageDisabled(); - } + { + foreach (var p in pages) + p.CheckPageDisabled(); + } - protected override IEnumerable GetSummary() - { - switch (m_typeOfImport) - { - case ImportType.Xva: - return GetSummaryXva(); - case ImportType.Ovf: - return GetSummaryOvf(); - case ImportType.Vhd: - return GetSummaryVhd(); - default: - return new List(); - } - } + protected override IEnumerable GetSummary() + { + switch (m_typeOfImport) + { + case ImportType.Xva: + return GetSummaryXva(); + case ImportType.Ovf: + return GetSummaryOvf(); + case ImportType.Vhd: + return GetSummaryVhd(); + default: + return new List(); + } + } - private IEnumerable GetSummaryXva() - { - var temp = new List(); - temp.Add(new Tuple(Messages.FINISH_PAGE_VMNAME, m_pageXvaStorage.ImportedVm.Name())); - temp.Add(new Tuple(Messages.FINISH_PAGE_TARGET, m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection.Name : m_pageXvaHost.SelectedHost.Name())); - temp.Add(new Tuple(Messages.FINISH_PAGE_STORAGE, m_pageXvaStorage.SR.Name())); + private IEnumerable GetSummaryXva() + { + var temp = new List(); + temp.Add(new Tuple(Messages.FINISH_PAGE_VMNAME, m_pageXvaStorage.ImportedVm.Name())); + temp.Add(new Tuple(Messages.FINISH_PAGE_TARGET, m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection.Name : m_pageXvaHost.SelectedHost.Name())); + temp.Add(new Tuple(Messages.FINISH_PAGE_STORAGE, m_pageXvaStorage.SR.Name())); - var con = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection; + var con = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection; - bool first = true; - foreach (var vif in m_pageXvaNetwork.VIFs) - { - var netref = new XenRef(vif.network); - var network = con.Resolve(netref); - // CA-218956 - Expose HIMN when showing hidden objects - if (network == null || (network.IsGuestInstallerNetwork() && !XenAdmin.Properties.Settings.Default.ShowHiddenVMs)) - continue; + bool first = true; + foreach (var vif in m_pageXvaNetwork.VIFs) + { + var netref = new XenRef(vif.network); + var network = con.Resolve(netref); + // CA-218956 - Expose HIMN when showing hidden objects + if (network == null || (network.IsGuestInstallerNetwork() && !XenAdmin.Properties.Settings.Default.ShowHiddenVMs)) + continue; - temp.Add(new Tuple(first ? Messages.FINISH_PAGE_NETWORK : "", network.Name())); - first = false; - } + temp.Add(new Tuple(first ? Messages.FINISH_PAGE_NETWORK : "", network.Name())); + first = false; + } - return temp; - } + return temp; + } - private IEnumerable GetSummaryOvf() - { - var temp = new List(); - - var appName = m_pageImportSource.SelectedOvfPackage.Name; - temp.Add(new Tuple(Messages.FINISH_PAGE_REVIEW_APPLIANCE, appName)); - temp.Add(new Tuple(Messages.FINISH_PAGE_VERIFY_MANIFEST, m_pageSecurity.VerifyManifest.ToYesNoStringI18n())); - temp.Add(new Tuple(Messages.FINISH_PAGE_VERIFY_SIGNATURE, m_pageSecurity.VerifySignature.ToYesNoStringI18n())); + private IEnumerable GetSummaryOvf() + { + var temp = new List(); - temp.Add(new Tuple(Messages.FINISH_PAGE_RUN_FIXUPS, m_pageOptions.RunFixups.ToYesNoStringI18n())); - if (m_pageOptions.RunFixups) - temp.Add(new Tuple(Messages.FINISH_PAGE_ISOSR, m_pageOptions.SelectedIsoSR.Name())); + var appName = m_pageImportSource.SelectedOvfPackage.Name; + temp.Add(new Tuple(Messages.FINISH_PAGE_REVIEW_APPLIANCE, appName)); + temp.Add(new Tuple(Messages.FINISH_PAGE_VERIFY_MANIFEST, m_pageSecurity.VerifyManifest.ToYesNoStringI18n())); + temp.Add(new Tuple(Messages.FINISH_PAGE_VERIFY_SIGNATURE, m_pageSecurity.VerifySignature.ToYesNoStringI18n())); - temp.AddRange(GetVmMappingsSummary()); - return temp; - } + temp.Add(new Tuple(Messages.FINISH_PAGE_RUN_FIXUPS, m_pageOptions.RunFixups.ToYesNoStringI18n())); + if (m_pageOptions.RunFixups) + temp.Add(new Tuple(Messages.FINISH_PAGE_ISOSR, m_pageOptions.SelectedIsoSR.Name())); - private IEnumerable GetSummaryVhd() - { - var temp = new List(); - temp.Add(new Tuple(Messages.FINISH_PAGE_IMAGEPATH, m_pageImportSource.FilePath)); - temp.Add(new Tuple(Messages.FINISH_PAGE_VMNAME, m_pageVMconfig.VmName)); - temp.Add(new Tuple(Messages.FINISH_PAGE_CPUCOUNT, m_pageVMconfig.CpuCount.ToString())); - temp.Add(new Tuple(Messages.FINISH_PAGE_MEMORY, string.Format(Messages.VAL_MB, m_pageVMconfig.Memory))); - if (Helpers.NaplesOrGreater(TargetConnection)) - temp.Add(new Tuple(Messages.BOOT_MODE, m_pageBootOptions.SelectedBootMode.StringOf())); + temp.AddRange(GetVmMappingsSummary()); + return temp; + } - if (m_pageImportSource.IsWIM) - temp.Add(new Tuple(Messages.FINISH_PAGE_ADDSPACE, Util.DiskSizeString(m_pageVMconfig.AdditionalSpace))); + private IEnumerable GetSummaryVhd() + { + var temp = new List(); + temp.Add(new Tuple(Messages.FINISH_PAGE_IMAGEPATH, m_pageImportSource.FilePath)); + temp.Add(new Tuple(Messages.FINISH_PAGE_VMNAME, m_pageVMconfig.VmName)); + temp.Add(new Tuple(Messages.FINISH_PAGE_CPUCOUNT, m_pageVMconfig.CpuCount.ToString())); + temp.Add(new Tuple(Messages.FINISH_PAGE_MEMORY, string.Format(Messages.VAL_MB, m_pageVMconfig.Memory))); + if (Helpers.NaplesOrGreater(TargetConnection)) + temp.Add(new Tuple(Messages.BOOT_MODE, m_pageBootOptions.SelectedBootMode.StringOf())); - temp.Add(new Tuple(Messages.FINISH_PAGE_RUN_FIXUPS, m_pageOptions.RunFixups.ToYesNoStringI18n())); - if (m_pageOptions.RunFixups) - temp.Add(new Tuple(Messages.FINISH_PAGE_ISOSR, m_pageOptions.SelectedIsoSR.Name())); + if (m_pageImportSource.IsWIM) + temp.Add(new Tuple(Messages.FINISH_PAGE_ADDSPACE, Util.DiskSizeString(m_pageVMconfig.AdditionalSpace))); - temp.AddRange(GetVmMappingsSummary()); - return temp; - } + temp.Add(new Tuple(Messages.FINISH_PAGE_RUN_FIXUPS, m_pageOptions.RunFixups.ToYesNoStringI18n())); + if (m_pageOptions.RunFixups) + temp.Add(new Tuple(Messages.FINISH_PAGE_ISOSR, m_pageOptions.SelectedIsoSR.Name())); - private IEnumerable GetVmMappingsSummary() - { - var temp = new List(); + temp.AddRange(GetVmMappingsSummary()); + return temp; + } - foreach (var mapping in m_vmMappings.Values) - { - var targetLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_TARGET : string.Format(Messages.FINISH_PAGE_TARGET_FOR_VM, mapping.VmNameLabel); - var storageLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_STORAGE : string.Format(Messages.FINISH_PAGE_STORAGE_FOR_VM, mapping.VmNameLabel); - var networkLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_NETWORK : string.Format(Messages.FINISH_PAGE_NETWORK_FOR_VM, mapping.VmNameLabel); + private IEnumerable GetVmMappingsSummary() + { + var temp = new List(); - temp.Add(new Tuple(targetLbl, mapping.TargetName)); - bool first = true; - foreach (var sr in mapping.Storage) - { - temp.Add(new Tuple(first ? storageLbl : "", sr.Value.Name())); - first = false; - } + foreach (var mapping in m_vmMappings.Values) + { + var targetLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_TARGET : string.Format(Messages.FINISH_PAGE_TARGET_FOR_VM, mapping.VmNameLabel); + var storageLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_STORAGE : string.Format(Messages.FINISH_PAGE_STORAGE_FOR_VM, mapping.VmNameLabel); + var networkLbl = m_vmMappings.Count == 1 ? Messages.FINISH_PAGE_NETWORK : string.Format(Messages.FINISH_PAGE_NETWORK_FOR_VM, mapping.VmNameLabel); - first = true; - foreach (var net in mapping.Networks) - { - temp.Add(new Tuple(first ? networkLbl : "", net.Value.Name())); - first = false; - } - } - return temp; - } + temp.Add(new Tuple(targetLbl, mapping.TargetName)); + bool first = true; + foreach (var sr in mapping.Storage) + { + temp.Add(new Tuple(first ? storageLbl : "", sr.Value.Name())); + first = false; + } - private void ResetVmMappings(EnvelopeType ovfEnvelope) - { - string[] sysIds = OVF.FindSystemIds(ovfEnvelope); - m_vmMappings.Clear(); + first = true; + foreach (var net in mapping.Networks) + { + temp.Add(new Tuple(first ? networkLbl : "", net.Value.Name())); + first = false; + } + } + return temp; + } - foreach (string sysId in sysIds) - { - var vmMap = new VmMapping - { - VmNameLabel = (m_typeOfImport == ImportType.Ovf) - ? FindVMName(ovfEnvelope, sysId) - : m_pageVMconfig.VmName //it should only iterate once - }; - m_vmMappings.Add(sysId, vmMap); - } - } + private void ResetVmMappings(EnvelopeType ovfEnvelope) + { + string[] sysIds = OVF.FindSystemIds(ovfEnvelope); + m_vmMappings.Clear(); - private bool IsGUID(string expression) - { - if (expression != null) - { - Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"); + foreach (string sysId in sysIds) + { + var vmMap = new VmMapping + { + VmNameLabel = (m_typeOfImport == ImportType.Ovf) + ? FindVMName(ovfEnvelope, sysId) + : m_pageVMconfig.VmName //it should only iterate once + }; + m_vmMappings.Add(sysId, vmMap); + } + } - return guidRegEx.IsMatch(expression); - } - return false; - } + private bool IsGUID(string expression) + { + if (expression != null) + { + Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"); + + return guidRegEx.IsMatch(expression); + } + return false; + } // Find a name to use of a VM within an envelope that could have come from any hypervisor. // TODO: Consider refactoring this method because it is very similar to OVF.FindSystemName(). - private string FindVMName(EnvelopeType ovfEnv, string systemid) - { - VirtualSystem_Type vSystem = OVF.FindVirtualSystemById(ovfEnv, systemid); + private string FindVMName(EnvelopeType ovfEnv, string systemid) + { + VirtualSystem_Type vSystem = OVF.FindVirtualSystemById(ovfEnv, systemid); // Use the given name if present and valid. // The given name is Envelope.VirtualSystem.Name specified in the OVF Specification 1.1 clause 7.2. // XenServer sets the name property. // vSphere 4.1 and Virtual Box 4.0.6 do not. if ((Tools.ValidateProperty("Name", vSystem)) && !String.IsNullOrEmpty(vSystem.Name[0].Value)) - return vSystem.Name[0].Value; + return vSystem.Name[0].Value; // The VM wasn't given a name. // Build a list of choices from various properties. @@ -611,7 +659,7 @@ namespace XenAdmin.Wizards.ImportWizard choices.Add(vSystem.id); // VirtualHardwareSection_Type.VirtualSystemIdentifier is next preference because Virtual Box will also set this property to the VM name. - VirtualHardwareSection_Type[] vhsList = OVF.FindVirtualHardwareSection(ovfEnv, systemid); + VirtualHardwareSection_Type[] vhsList = OVF.FindVirtualHardwareSection(ovfEnv, systemid); foreach (VirtualHardwareSection_Type vhs in vhsList) { @@ -623,11 +671,11 @@ namespace XenAdmin.Wizards.ImportWizard } // Operating system description is next preference. - OperatingSystemSection_Type[] ossList = OVF.FindSections(vSystem.Items); + OperatingSystemSection_Type[] ossList = OVF.FindSections(vSystem.Items); foreach (OperatingSystemSection_Type oss in ossList) { - if (Tools.ValidateProperty("Description", oss)) + if (Tools.ValidateProperty("Description", oss)) choices.Add(oss.Description.Value); } @@ -636,7 +684,7 @@ namespace XenAdmin.Wizards.ImportWizard choices.Add(Path.GetFileNameWithoutExtension(ovfEnv.Name)); // Last preference is file name. - choices.Add(Path.GetFileNameWithoutExtension(m_pageImportSource.SelectedOvfPackage.PackageSourceFile)); + choices.Add(Path.GetFileNameWithoutExtension(m_pageImportSource.SelectedOvfPackage.PackageSourceFile)); // First choice is one that is not a GUID. foreach (var choice in choices) @@ -654,23 +702,23 @@ namespace XenAdmin.Wizards.ImportWizard // Last resort is a new GUID. return Guid.NewGuid().ToString(); - } + } - #endregion + #endregion - private void m_pageXvaStorage_ImportVmCompleted() - { - Program.Invoke(this, () => - { - if (CurrentStepTabPage.GetType() == typeof(StoragePickerPage)) - { - m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; - m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); - NotifyNextPagesOfChange(m_pageXvaNetwork); - NextStep(); - } - }); - } + private void m_pageXvaStorage_ImportVmCompleted() + { + Program.Invoke(this, () => + { + if (CurrentStepTabPage.GetType() == typeof(StoragePickerPage)) + { + m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; + m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); + NotifyNextPagesOfChange(m_pageXvaNetwork); + NextStep(); + } + }); + } private void ShowXenAppXenDesktopWarning(IXenConnection connection) { @@ -690,27 +738,27 @@ namespace XenAdmin.Wizards.ImportWizard ShowXenAppXenDesktopWarning(connection); } - #region Nested items + #region Nested items - /// - /// Type of the object we want to import - /// - public enum ImportType - { - /// - /// Exported VM or template; filetype *.xva, *.xva.gz - /// - Xva, - /// - /// Appliance; filetypes *.ovf, *.ova, *.ova.gz - /// - Ovf, - /// - /// Virtual disk image; filetypes *.vhd, *.vmdk (CA-61385: remove ".vdi", ".wim" support for Boston) - /// - Vhd - } + /// + /// Type of the object we want to import + /// + public enum ImportType + { + /// + /// Exported VM or template; filetype *.xva, *.xva.gz + /// + Xva, + /// + /// Appliance; filetypes *.ovf, *.ova, *.ova.gz + /// + Ovf, + /// + /// Virtual disk image; filetypes *.vhd, *.vmdk (CA-61385: remove ".vdi", ".wim" support for Boston) + /// + Vhd + } - #endregion - } + #endregion + } } diff --git a/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs b/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs index db036272f..f8c570d74 100644 --- a/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs +++ b/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs @@ -99,7 +99,7 @@ namespace XenAdmin.Wizards.ImportWizard } } - public EnvelopeType SelectedOvfEnvelope { private get; set; } + public EnvelopeType SelectedOvfEnvelope { get; set; } private StorageResourceContainer ResourceData(string sysId) { diff --git a/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs b/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs index 16d8c4e00..6b36caeba 100644 --- a/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs +++ b/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs @@ -49,8 +49,8 @@ namespace XenAdmin.Wizards.ImportWizard #region Private fields private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private IXenConnection m_selectedConnection; - private Host m_selectedAffinity; + internal IXenConnection MSelectedConnection { get; set; } + internal Host MSelectedAffinity { get; set; } private VM m_vm; private bool m_buttonNextEnabled; #endregion @@ -136,24 +136,12 @@ namespace XenAdmin.Wizards.ImportWizard #endregion - public void SetAffinity(Host host) - { - m_selectedAffinity = host; - } public void SetVm(VM vm) { m_vm = vm; } - - /// - /// Should be called before the Affinity is set. - /// - public void SetConnection(IXenConnection con) - { - m_selectedConnection = con; - } - + #region Private methods private void UpdateControlsEnabledState(bool enabled) @@ -167,7 +155,7 @@ namespace XenAdmin.Wizards.ImportWizard { NetworkNetworkColumn.Items.Clear(); - var networks = m_selectedConnection.Cache.Networks.Where(ShowNetwork); + var networks = MSelectedConnection.Cache.Networks.Where(ShowNetwork); foreach (XenAPI.Network network in networks) { @@ -190,14 +178,14 @@ namespace XenAdmin.Wizards.ImportWizard { // We need to automatically generate VIFs for Networks marked AutoPlug=true - var networks = m_selectedConnection.Cache.Networks; + var networks = MSelectedConnection.Cache.Networks; foreach (XenAPI.Network network in networks) { if (m_networkGridView.Rows.Count < m_vm.MaxVIFsAllowed() && ShowNetwork(network) && network.GetAutoPlug()) { AddVIFRow(new VIF { - Connection = m_selectedConnection, + Connection = MSelectedConnection, device = m_networkGridView.Rows.Count.ToString(), network = new XenRef(network.opaque_ref), MAC = Messages.MAC_AUTOGENERATE @@ -209,12 +197,12 @@ namespace XenAdmin.Wizards.ImportWizard { // We need to create off the _vmTemplate - var vifs = m_selectedConnection.ResolveAll(m_vm.VIFs); + var vifs = MSelectedConnection.ResolveAll(m_vm.VIFs); foreach (VIF vif in vifs) { AddVIFRow(new VIF { - Connection = m_selectedConnection, + Connection = MSelectedConnection, device = vif.device, network = vif.network, MAC = Messages.MAC_AUTOGENERATE @@ -224,7 +212,7 @@ namespace XenAdmin.Wizards.ImportWizard else { //We need to recreate off vm - var vifs = m_selectedConnection.ResolveAll(m_vm.VIFs); + var vifs = MSelectedConnection.ResolveAll(m_vm.VIFs); foreach (VIF vif in vifs) AddVIFRow(vif); } @@ -240,7 +228,7 @@ namespace XenAdmin.Wizards.ImportWizard private XenAPI.Network GetDefaultNetwork() { - foreach (XenAPI.Network network in m_selectedConnection.Cache.Networks) + foreach (XenAPI.Network network in MSelectedConnection.Cache.Networks) if (ShowNetwork(network)) return network; @@ -261,10 +249,10 @@ namespace XenAdmin.Wizards.ImportWizard if (network.IsMember()) return false; - if (m_selectedAffinity != null && !m_selectedAffinity.CanSeeNetwork(network)) + if (MSelectedAffinity != null && !MSelectedAffinity.CanSeeNetwork(network)) return false; - if (m_selectedAffinity == null && !network.AllHostsCanSeeNetwork()) + if (MSelectedAffinity == null && !network.AllHostsCanSeeNetwork()) return false; if (network.IsSriov() && !m_vm.HasSriovRecommendation()) @@ -276,7 +264,7 @@ namespace XenAdmin.Wizards.ImportWizard private void AddVIFRow(VIF vif) { var row = new VifRow(vif); - XenAPI.Network network = m_selectedConnection.Resolve(vif.network); + XenAPI.Network network = MSelectedConnection.Resolve(vif.network); bool isGuestInstallerNetwork = network != null && network.IsGuestInstallerNetwork(); ToStringWrapper comboBoxEntry = FindComboBoxEntryForNetwork(network); @@ -354,7 +342,7 @@ namespace XenAdmin.Wizards.ImportWizard return; } - VIF vif = new VIF {Connection = m_selectedConnection}; + VIF vif = new VIF {Connection = MSelectedConnection}; int i = 0; while (true) diff --git a/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs b/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs index 600d5c4ca..ae57f26c6 100644 --- a/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs +++ b/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs @@ -45,8 +45,9 @@ namespace XenAdmin.Wizards.ImportWizard public partial class StoragePickerPage : XenTabPage { #region Private fields - private Host m_targetHost; - private IXenConnection m_targetConnection; + + internal Host MTargetHost { set; get; } + internal IXenConnection MTargetConnection { get; set; } private volatile Task m_importTask; private bool m_alreadyFoundVM; private ActionProgressDialog m_actionDialog; @@ -98,8 +99,8 @@ namespace XenAdmin.Wizards.ImportWizard SetButtonNextEnabled(false); m_buttonPreviousEnabled = false; OnPageUpdated(); - ImportXvaAction = new ImportVmAction(m_targetHost == null ? m_targetConnection : m_targetHost.Connection, - m_targetHost, FilePath, SR, + ImportXvaAction = new ImportVmAction(MTargetHost == null ? MTargetConnection : MTargetHost.Connection, + MTargetHost, FilePath, SR, VMOperationCommand.WarningDialogHAInvalidConfig, VMOperationCommand.StartDiagnosisForm); ImportXvaAction.Completed += m_importXvaAction_Completed; @@ -119,7 +120,7 @@ namespace XenAdmin.Wizards.ImportWizard public override void PopulatePage() { SetButtonNextEnabled(false); - m_srPicker.PopulateAsync(SrPicker.SRPickerType.VM, m_targetConnection, m_targetHost, null, null); + m_srPicker.PopulateAsync(SrPicker.SRPickerType.VM, MTargetConnection, MTargetHost, null, null); IsDirty = true; } @@ -147,19 +148,6 @@ namespace XenAdmin.Wizards.ImportWizard #endregion - /// - /// Should be called before the Affinity is set. - /// - public void SetConnection(IXenConnection con) - { - m_targetConnection = con; - } - - public void SetTargetHost(Host host) - { - m_targetHost = host; - } - #region Private methods private void SetButtonNextEnabled(bool enabled) @@ -196,12 +184,12 @@ namespace XenAdmin.Wizards.ImportWizard while (ImportXvaAction.RelatedTask == null) Thread.Sleep(100); - while ((m_importTask = m_targetConnection.Resolve(ImportXvaAction.RelatedTask)) == null) + while ((m_importTask = MTargetConnection.Resolve(ImportXvaAction.RelatedTask)) == null) Thread.Sleep(100); // We register a XenObjectsUpdated event handler where we check that the import task has the object creation phase marked as "complete"; // Once the object creation is complete, we look for the vm; When we found the vm we unregister this event handler; - m_targetConnection.XenObjectsUpdated += targetConnection_XenObjectsUpdated; + MTargetConnection.XenObjectsUpdated += targetConnection_XenObjectsUpdated; Program.Invoke(this, CheckTask); } @@ -233,11 +221,11 @@ namespace XenAdmin.Wizards.ImportWizard { // Should never get here (as we unregister XenObjectsUpdated event handler after we find the vm) but just in case, // unregister XenObjectsUpdated event handler - m_targetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; return; } - foreach (VM vm in m_targetConnection.Cache.VMs) + foreach (VM vm in MTargetConnection.Cache.VMs) { if (!vm.other_config.ContainsKey(ImportVmAction.IMPORT_TASK)) continue; @@ -250,7 +238,7 @@ namespace XenAdmin.Wizards.ImportWizard ImportedVm = vm; // We found the VM, unregister XenObjectsUpdated event handler - m_targetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; // And close the dialog, flick to next page. m_actionDialog.Close(); @@ -279,7 +267,7 @@ namespace XenAdmin.Wizards.ImportWizard if (!(ImportXvaAction.Succeeded) || ImportXvaAction.Cancelled) { // task failed or has been cancelled, unregister XenObjectsUpdated event handler - m_targetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; // Give the user a chance to correct any errors m_actionDialog = null; From 6ce0a4b49da0ed5b41dc39a1697a2e299a7fd8a8 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 3 Nov 2021 16:07:36 +0000 Subject: [PATCH 34/62] CP-36392: Remove repetitive count and null check Check is performed within the constructor of `WlbRecommendations` Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs index 284ed42f1..daa212302 100644 --- a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs +++ b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs @@ -166,8 +166,7 @@ namespace XenAdmin.Commands var retrieveVmRecommendationsAction = new WlbRetrieveVmRecommendationsAction(connection, vms); retrieveVmRecommendationsAction.Completed += delegate { - if (Stopped || retrieveVmRecommendationsAction.Cancelled || - !retrieveVmRecommendationsAction.Succeeded || vms == null || vms.Count == 0) + if (Stopped || retrieveVmRecommendationsAction.Cancelled || !retrieveVmRecommendationsAction.Succeeded) return; var recommendations = new WlbRecommendations(vms, retrieveVmRecommendationsAction.Recommendations); From 45512b4cde49f6944b6e255f47f5640b4b87d271 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:18:09 +0000 Subject: [PATCH 35/62] CP-36392: Add removed `null` check in `WlbOptiomizePool.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/Actions/GUIActions/ExternalPluginAction.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs b/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs index 07d38da0c..79e4c66d3 100644 --- a/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs +++ b/XenAdmin/Actions/GUIActions/ExternalPluginAction.cs @@ -248,7 +248,7 @@ namespace XenAdmin.Actions // Returns a set of params which relate to the object you have selected in the treeview private IEnumerable RetrieveParams(IXenObject obj) { - var connection = obj.Connection; + var connection = obj?.Connection; var coordinator = connection != null ? Helpers.GetCoordinator(connection) : null; // get coordinator asserts connection is not null var coordinatorAddress = EmptyParameter; @@ -259,7 +259,7 @@ namespace XenAdmin.Actions } var sessionRef = connection?.Session != null ? connection.Session.opaque_ref : EmptyParameter; - var objCls = obj.GetType().Name; + var objCls = obj != null ? obj.GetType().Name : EmptyParameter; var objUuid = connection?.Session != null ? Helpers.GetUuid(obj) : EmptyParameter; return new List(new string[] { coordinatorAddress, sessionRef, objCls, objUuid }); } From b6a70e2ffc200eeed3bcdec98e4e31a10ca708fc Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:18:55 +0000 Subject: [PATCH 36/62] CP-36392: Add null check for `_vmOptList` in `WlbOptimizePoolAction.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/Wlb/WlbOptimizePool.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenAdmin/Controls/Wlb/WlbOptimizePool.cs b/XenAdmin/Controls/Wlb/WlbOptimizePool.cs index f1bfa4817..a15360d9e 100644 --- a/XenAdmin/Controls/Wlb/WlbOptimizePool.cs +++ b/XenAdmin/Controls/Wlb/WlbOptimizePool.cs @@ -422,7 +422,7 @@ namespace XenAdmin.Controls.Wlb /// EventArgs private void ButtonApply_Click(object sender, EventArgs e) { - if (this._pool == null) + if (_pool == null || _vmOptList == null) return; applyButton.Enabled = false; From 5f117e90c55ab93abffda1c3fa748d9b5fed37c8 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:21:25 +0000 Subject: [PATCH 37/62] CP-36392: Add `null` check in `EnableHostAction.cs` Signed-off-by: Danilo Del Busso --- XenModel/Actions/Host/EnableHostAction.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XenModel/Actions/Host/EnableHostAction.cs b/XenModel/Actions/Host/EnableHostAction.cs index d178fb753..7e287b03b 100644 --- a/XenModel/Actions/Host/EnableHostAction.cs +++ b/XenModel/Actions/Host/EnableHostAction.cs @@ -42,10 +42,10 @@ namespace XenAdmin.Actions private readonly bool _resumeVMs; public EnableHostAction(Host host, bool resumeVMs,Func acceptNTolChangesOnEnable) - : base(host.Connection, Messages.HOST_ENABLE, Messages.WAITING, null, acceptNTolChangesOnEnable) + : base(host?.Connection, Messages.HOST_ENABLE, Messages.WAITING, null, acceptNTolChangesOnEnable) { + Host = host ?? throw new ArgumentNullException("host"); _resumeVMs = resumeVMs; - Host = host; AddCommonAPIMethodsToRoleCheck(); ApiMethodsToRoleCheck.Add("pool.ha_compute_hypothetical_max_host_failures_to_tolerate"); ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate"); From caf608344e45affb4a67e2c9e246d4dfb3f5983f Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:24:17 +0000 Subject: [PATCH 38/62] CP-36392: remuve redundant iteration in `ResumeVMOnHostToolStripMenuItem.cs` Signed-off-by: Danilo Del Busso --- .../Controls/ResumeVMOnHostToolStripMenuItem.cs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs b/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs index e8ad4137b..e55162a0c 100644 --- a/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs +++ b/XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs @@ -92,18 +92,14 @@ namespace XenAdmin.Commands protected override bool CanRunCore(SelectedItemCollection selection) { - if (!selection.AllItemsAre()) - { - return false; - } - IXenConnection connection = null; var atLeastOneCanRun = false; foreach (var item in selection) { - var vm = (VM)item.XenObject; - + if (!(item.XenObject is VM vm)) + return false; + // all VMs must be on the same connection if (connection != null && vm.Connection != connection) { From 47884376a39038e029c24a7f00714db21e4c04d1 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:27:56 +0000 Subject: [PATCH 39/62] CP-36392: Fix typo in `VNCTabView.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/ConsoleView/VNCTabView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenAdmin/ConsoleView/VNCTabView.cs b/XenAdmin/ConsoleView/VNCTabView.cs index 7277fa8fc..45af1cba3 100644 --- a/XenAdmin/ConsoleView/VNCTabView.cs +++ b/XenAdmin/ConsoleView/VNCTabView.cs @@ -712,7 +712,7 @@ namespace XenAdmin.ConsoleView else if (source.power_state == vm_power_state.Paused) { // CA-12637: Pause/UnPause is not supported in the GUI. Comment out - // the EnablePowerStateLabel because it gives the appearance that we + // the EnablePowerStateLabel because it gives the impression that we // support unpause via the GUI. DisablePowerStateLabel(Messages.CONSOLE_POWER_STATE_PAUSED); } From 5d5d971c745e0bc4ee81183275e683b4cc799d29 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:28:57 +0000 Subject: [PATCH 40/62] CP-36329: Remove redundant verbatim in `WlbRecommendations.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/Controls/WlbRecommendations.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenAdmin/Commands/Controls/WlbRecommendations.cs b/XenAdmin/Commands/Controls/WlbRecommendations.cs index 6a679a03a..4d4b6edca 100644 --- a/XenAdmin/Commands/Controls/WlbRecommendations.cs +++ b/XenAdmin/Commands/Controls/WlbRecommendations.cs @@ -55,7 +55,7 @@ namespace XenAdmin.Commands public WlbRecommendations(List vms, Dictionary, string[]>> recommendations) { if (vms == null || vms.Count == 0) - throw new ArgumentException(@"Parameter cannot be null or empty", nameof(vms)); + throw new ArgumentException("Parameter cannot be null or empty", nameof(vms)); _vms = new ReadOnlyCollection(vms); _recommendations = recommendations; From 02439d53032fa0f019eab613d4fddbf02d5ef606 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:36:42 +0000 Subject: [PATCH 41/62] CP-36382: Replace `_nameCell` with ad-hoc `_xenObject` readonly field To ensure that the field in the `GetHasCode` call is `readonly` Also remove unused constructor Signed-off-by: Danilo Del Busso --- .../PoolHostDataGridViewOneCheckboxRow.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs b/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs index c215cd51f..0770e1d34 100644 --- a/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs +++ b/XenAdmin/Controls/DataGridViewEx/PoolHostDataGridViewOneCheckboxRow.cs @@ -90,7 +90,9 @@ namespace XenAdmin.Controls.DataGridViewEx } } } - + + private readonly IXenObject _xenObject; + /// /// If the row is either a pool row or else a stanadlone host row /// @@ -128,7 +130,7 @@ namespace XenAdmin.Controls.DataGridViewEx public override int GetHashCode() { - return _nameCell.GetHashCode(); + return _xenObject?.GetHashCode() ?? 0; } public CheckState Checked @@ -143,11 +145,10 @@ namespace XenAdmin.Controls.DataGridViewEx } } - protected PoolHostDataGridViewOneCheckboxRow(){} - protected PoolHostDataGridViewOneCheckboxRow(Pool pool) : base(pool) { + _xenObject = pool; SetupCells(); } @@ -159,6 +160,7 @@ namespace XenAdmin.Controls.DataGridViewEx protected PoolHostDataGridViewOneCheckboxRow(Host host, bool hasPool) : base(host, hasPool) { + _xenObject = host; SetupCells(); } From 494f78966d94680da520d5a1b9b786fcc2344d5c Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:43:50 +0000 Subject: [PATCH 42/62] CP-36392: Address logic issue in `FilterLocationToolStripDropDownButton.cs` As suggested during review: > The check after the `&&` should go in a nested if block: if we are in a split second where the cache has not been populated yet, there should be no item added, however, this code will add a `p` item. Signed-off-by: Danilo Del Busso --- .../FilterLocationToolStripDropDownButton.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs b/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs index a833b6312..aad9997fc 100644 --- a/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs +++ b/XenAdmin/Controls/FilterLocationToolStripDropDownButton.cs @@ -124,12 +124,15 @@ namespace XenAdmin.Controls { var p = Helpers.GetPool(c); - if (p == null && c.Cache.Hosts.Length > 0)// Stand alone host + if (p == null)// Stand alone host { - var host = c.Cache.Hosts.First(); - var item = GenerateFilterItem(host, host.uuid); - item.Checked = HostCheckStates.ContainsKey(host.uuid); - DropDownItems.Add(item); + if (c.Cache.Hosts.Length > 0) + { + var host = c.Cache.Hosts.First(); + var item = GenerateFilterItem(host, host.uuid); + item.Checked = HostCheckStates.ContainsKey(host.uuid); + DropDownItems.Add(item); + } } else DropDownItems.Add(GeneratePoolFilterItem(p)); From 396bcb0e356101d085c593e8ecdfdc1d52f56fba Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:46:12 +0000 Subject: [PATCH 43/62] CP-36392: Make `type` field `readonly` in `QueryElement.cs` field is used in `GetHashCode` Signed-off-by: Danilo Del Busso --- XenAdmin/Controls/XenSearch/QueryElement.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenAdmin/Controls/XenSearch/QueryElement.cs b/XenAdmin/Controls/XenSearch/QueryElement.cs index f5afa254d..74be953d8 100644 --- a/XenAdmin/Controls/XenSearch/QueryElement.cs +++ b/XenAdmin/Controls/XenSearch/QueryElement.cs @@ -1080,7 +1080,7 @@ namespace XenAdmin.Controls.XenSearch public class ExtraComboEntry { - public StringPropertyQuery.PropertyQueryType type; + public readonly StringPropertyQuery.PropertyQueryType type; public ExtraComboEntry(StringPropertyQuery.PropertyQueryType type) { this.type = type; From 1acce3638cde93b5c0923012c4d44703fbd81704 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:51:38 +0000 Subject: [PATCH 44/62] CP-36392: Move vms `null` and `Count` checks outside of `WlbRecommendations.cs` Signed-off-by: Danilo Del Busso damni Signed-off-by: Danilo Del Busso --- .../Controls/VMOperationToolStripMenuItem.cs | 20 ++++++++++--------- .../Commands/Controls/WlbRecommendations.cs | 3 --- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs index daa212302..9e4874214 100644 --- a/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs +++ b/XenAdmin/Commands/Controls/VMOperationToolStripMenuItem.cs @@ -33,12 +33,11 @@ using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; -using XenAdmin.Controls; -using XenAPI; -using XenAdmin.Core; -using XenAdmin.Actions; using XenAdmin.Actions.Wlb; +using XenAdmin.Controls; +using XenAdmin.Core; using XenAdmin.Network; +using XenAPI; namespace XenAdmin.Commands @@ -112,7 +111,7 @@ namespace XenAdmin.Commands // Adds the migrate wizard button, do this before the enable checks on the other items AddAdditionalMenuItems(selection); - + UpdateHostList(); } @@ -163,6 +162,9 @@ namespace XenAdmin.Commands if (Helpers.WlbEnabled(connection)) { var vms = selection.AsXenObjects(); + if (vms == null || vms.Count == 0) + return; + var retrieveVmRecommendationsAction = new WlbRetrieveVmRecommendationsAction(connection, vms); retrieveVmRecommendationsAction.Completed += delegate { @@ -243,7 +245,7 @@ namespace XenAdmin.Commands var firstItem = DropDownItems[0] as VMOperationToolStripMenuSubItem; if (firstItem == null) return; - + // API calls could happen in CanRun(), which take time to wait. So a Producer-Consumer-Queue with size 25 is used here to : // 1. Make API calls for different menu items happen in parallel; // 2. Limit the count of concurrent threads (now it's 25). @@ -253,7 +255,7 @@ namespace XenAdmin.Commands var connection = selection[0].Connection; var session = connection.DuplicateSession(); - var affinityHost = connection.Resolve(((VM) selection[0].XenObject).affinity); + var affinityHost = connection.Resolve(((VM)selection[0].XenObject).affinity); EnqueueHostMenuItem(this, session, affinityHost, firstItem, true); @@ -278,7 +280,7 @@ namespace XenAdmin.Commands workerQueueWithoutWlb.EnqueueItem(() => { var selection = menu.Command.GetSelection(); - var cmd = isHomeServer + var cmd = isHomeServer ? new VMOperationHomeServerCommand(menu.Command.MainWindowCommandInterface, selection, menu._operation, session) : new VMOperationHostCommand(menu.Command.MainWindowCommandInterface, selection, delegate { return host; }, host.Name().EscapeAmpersands(), menu._operation, session); @@ -320,7 +322,7 @@ namespace XenAdmin.Commands } }); } - + #endregion /// diff --git a/XenAdmin/Commands/Controls/WlbRecommendations.cs b/XenAdmin/Commands/Controls/WlbRecommendations.cs index 4d4b6edca..257af1b4e 100644 --- a/XenAdmin/Commands/Controls/WlbRecommendations.cs +++ b/XenAdmin/Commands/Controls/WlbRecommendations.cs @@ -54,9 +54,6 @@ namespace XenAdmin.Commands /// public WlbRecommendations(List vms, Dictionary, string[]>> recommendations) { - if (vms == null || vms.Count == 0) - throw new ArgumentException("Parameter cannot be null or empty", nameof(vms)); - _vms = new ReadOnlyCollection(vms); _recommendations = recommendations; _isError = recommendations == null; From cc917e2a660c3f6f4878bcc0d2f7942aeafbbe2f Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 09:57:08 +0000 Subject: [PATCH 45/62] CP-36392: Simplify `if` and `else if` blocks to reduce nesting in `AddServerDialog.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/Dialogs/AddServerDialog.cs | 58 ++++++++++++++--------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/XenAdmin/Dialogs/AddServerDialog.cs b/XenAdmin/Dialogs/AddServerDialog.cs index e0e94fbc3..dc72c5b78 100644 --- a/XenAdmin/Dialogs/AddServerDialog.cs +++ b/XenAdmin/Dialogs/AddServerDialog.cs @@ -137,37 +137,35 @@ namespace XenAdmin.Dialogs ServerNameComboBox.Enabled = true; AddButton.Text = Messages.ADD; } - else + else if (!_changedPass) + return; + else if (connection.Password == null) { - if (!_changedPass) - return; - if (connection.Password == null) - { - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = Messages.CONNECT_TO_SERVER_BLURB; - labelError.Text = ""; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.CONNECT; - } - else if (connection.ExpectPasswordIsCorrect) - { - // This situation should be rare, it normally comes from logging in a new session after an existing one has been made - // We now use duplicate sessions instead most of the time which don't log in again. - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = string.Format(Messages.ADDSERVER_PASS_NEW, BrandManager.BrandConsole); - labelError.Text = ""; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.OK; - } - else // the password probably hasn't actually changed but we do know the user has typed it in wrong - { - Text = Messages.CONNECT_TO_SERVER; - labelInstructions.Text = string.Format(Messages.ERROR_CONNECTING_BLURB, BrandManager.BrandConsole); - labelError.Text = Messages.ADD_NEW_INCORRECT; - ServerNameComboBox.Enabled = false; - AddButton.Text = Messages.CONNECT; - } + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = Messages.CONNECT_TO_SERVER_BLURB; + labelError.Text = ""; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.CONNECT; } + else if (connection.ExpectPasswordIsCorrect) + { + // This situation should be rare, it normally comes from logging in a new session after an existing one has been made + // We now use duplicate sessions instead most of the time which don't log in again. + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = string.Format(Messages.ADDSERVER_PASS_NEW, BrandManager.BrandConsole); + labelError.Text = ""; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.OK; + } + else // the password probably hasn't actually changed but we do know the user has typed it in wrong + { + Text = Messages.CONNECT_TO_SERVER; + labelInstructions.Text = string.Format(Messages.ERROR_CONNECTING_BLURB, BrandManager.BrandConsole); + labelError.Text = Messages.ADD_NEW_INCORRECT; + ServerNameComboBox.Enabled = false; + AddButton.Text = Messages.CONNECT; + } + } private void AddButton_Click(object sender, EventArgs e) @@ -205,7 +203,7 @@ namespace XenAdmin.Dialogs { if (conn == null) { - conn = new XenConnection {fromDialog = true}; + conn = new XenConnection { fromDialog = true }; conn.CachePopulated += conn_CachePopulated; } else if (!_changedPass) From 31702c9e434ffcf4961351c049aab88739859439 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:00:50 +0000 Subject: [PATCH 46/62] CP-36392: Add `null` checks for `ControlDomainMemoryDialog`'s constructor params Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs | 9 ++++++--- XenAdmin/Controls/Ballooning/HostMemoryControls.cs | 7 +++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs b/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs index c5b3ad38c..bb133cab3 100644 --- a/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs +++ b/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs @@ -58,9 +58,12 @@ namespace XenAdmin.Commands protected override void RunCore(SelectedItemCollection selection) { - Host host = selection[0].HostAncestor; - using (var dlg = new ControlDomainMemoryDialog(host)) - dlg.ShowDialog(Program.MainWindow); + var host = selection[0].HostAncestor; + if (host != null) + { + using (var dlg = new ControlDomainMemoryDialog(host)) + dlg.ShowDialog(Program.MainWindow); + } } protected override bool ConfirmationRequired diff --git a/XenAdmin/Controls/Ballooning/HostMemoryControls.cs b/XenAdmin/Controls/Ballooning/HostMemoryControls.cs index 501301d4e..138503859 100644 --- a/XenAdmin/Controls/Ballooning/HostMemoryControls.cs +++ b/XenAdmin/Controls/Ballooning/HostMemoryControls.cs @@ -127,8 +127,11 @@ namespace XenAdmin.Controls.Ballooning private void valueControlDomain_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - using (var dlg = new ControlDomainMemoryDialog(host)) - dlg.ShowDialog(Program.MainWindow); + if (host != null) + { + using (var dlg = new ControlDomainMemoryDialog(host)) + dlg.ShowDialog(Program.MainWindow); + } } internal void UnregisterHandlers() From 68b54682ae24bd5d38936f1711409dad47f5319a Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:05:08 +0000 Subject: [PATCH 47/62] CP-36392: Move param checks outside of `RepairSRDialog.cs`'s constructor Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/RepairSRCommand.cs | 5 ++++- XenAdmin/Dialogs/RepairSRDialog.cs | 3 --- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/XenAdmin/Commands/RepairSRCommand.cs b/XenAdmin/Commands/RepairSRCommand.cs index 8b61ee2a7..77efee06f 100644 --- a/XenAdmin/Commands/RepairSRCommand.cs +++ b/XenAdmin/Commands/RepairSRCommand.cs @@ -78,7 +78,10 @@ namespace XenAdmin.Commands dlg.ShowDialog(Parent); } - new RepairSRDialog(srList).Show(Parent); + if (srList.Count != 0) + { + new RepairSRDialog(srList).Show(Parent); + } } protected override bool CanRunCore(SelectedItemCollection selection) diff --git a/XenAdmin/Dialogs/RepairSRDialog.cs b/XenAdmin/Dialogs/RepairSRDialog.cs index d57e77393..46ce46533 100644 --- a/XenAdmin/Dialogs/RepairSRDialog.cs +++ b/XenAdmin/Dialogs/RepairSRDialog.cs @@ -75,9 +75,6 @@ namespace XenAdmin.Dialogs /// public RepairSRDialog(IEnumerable srs, bool runAction = true) { - if (srs == null || !srs.Any()) - throw new ArgumentException("Parameter cannot be null or empty", nameof(srs)); - this.runAction = runAction; BoldFont = new Font(Font, FontStyle.Bold); List srList = new List(srs); From 6f7faefce1345a9079d550a81a4d2a242e7d16e9 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:09:11 +0000 Subject: [PATCH 48/62] CP-36392: Replace complex method with single LINQ calls in `DRFailoverWizardStoragePage` Signed-off-by: Danilo Del Busso --- .../DRWizards/DRFailoverWizardStoragePage.cs | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs index b119be54e..22864e8f3 100644 --- a/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs +++ b/XenAdmin/Wizards/DRWizards/DRFailoverWizardStoragePage.cs @@ -179,8 +179,8 @@ namespace XenAdmin.Wizards.DRWizards var vdis = sr.Connection.ResolveAll(sr.VDIs); bool poolMetadataDetected = vdis.Any(vdi => vdi.type == vdi_type.metadata); - SrRow row; - if (!FindRowByUuid(sr.uuid, out row)) + var row = dataGridViewSRs.Rows.Cast().FirstOrDefault(r => r.SrUuid == sr.uuid); + if (row != null) { row = new SrRow(sr, poolMetadataDetected, SelectedSRsUuids.Contains(sr.uuid)); dataGridViewSRs.Rows.Add(row); @@ -192,8 +192,8 @@ namespace XenAdmin.Wizards.DRWizards { foreach (var srInfo in scannedDevice.SRList) { - SrRow row; - if (!FindRowByUuid(srInfo.UUID, out row)) + var row = dataGridViewSRs.Rows.Cast().FirstOrDefault(r => r.SrUuid == srInfo.UUID); + if (row != null) { row = new SrRow(srInfo, scannedDevice.Type, srInfo.PoolMetadataDetected, SelectedSRsUuids.Contains(srInfo.UUID)); @@ -356,8 +356,9 @@ namespace XenAdmin.Wizards.DRWizards foreach (SR.SRInfo srInfo in metadataSrs) { - SrRow row; - if (!FindRowByUuid(srInfo.UUID, out row)) + var row = dataGridViewSRs.Rows.Cast().FirstOrDefault(r => r.SrUuid == srInfo.UUID); + + if (row != null) { row = new SrRow(srInfo, type, srInfo.PoolMetadataDetected, srInfo.PoolMetadataDetected); dataGridViewSRs.Rows.Add(row); @@ -618,17 +619,6 @@ namespace XenAdmin.Wizards.DRWizards OnPageUpdated(); } - private bool FindRowByUuid(string uuid, out SrRow row) - { - row = null; - var srRows = dataGridViewSRs.Rows.Cast().Where(srRow => srRow.SrUuid == uuid).ToList(); - if (srRows.Count == 0) - return false; - - row = srRows.First(); - return true; - } - private void buttonSelectAll_Click(object sender, EventArgs e) { SelectAllRows(true); From cfff0722c73ce371c913423f045d2bae129c5244 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:11:41 +0000 Subject: [PATCH 49/62] CP-36392: Limit ex-`readonly` public lists to `{get;}` usages only Signed-off-by: Danilo Del Busso --- XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs | 2 +- .../Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs index 4460855fb..0590d4912 100644 --- a/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs +++ b/XenAdmin/Wizards/PatchingWizard/PatchingWizard_UploadPage.cs @@ -49,7 +49,7 @@ namespace XenAdmin.Wizards.PatchingWizard } #region Accessors - public List PatchMappings = new List(); + public List PatchMappings { get; } = new List(); public UpdateType SelectedUpdateType { private get; set; } public string SelectedPatchFilePath { get; set; } diff --git a/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs b/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs index 46ee3c4af..6a8ea909f 100644 --- a/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs +++ b/XenAdmin/Wizards/PatchingWizard/UpdateProgressBackgroundWorker.cs @@ -42,8 +42,8 @@ namespace XenAdmin.Wizards.PatchingWizard public List HostPlans { get; private set; } public List FinalActions { get; private set; } public List CleanupActions { get; private set; } - public List DoneActions = new List(); - public List InProgressActions = new List(); + public List DoneActions { get; } = new List(); + public List InProgressActions { get; } = new List(); public Pool Pool { get; private set; } public string Name { get; private set; } From 9b4f96033604b20d0b5c3f8e5a91eb300167ede4 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:15:29 +0000 Subject: [PATCH 50/62] CP-36392: Check for whitespace-only values in `GEtPerfmonDefinitions` Signed-off-by: Danilo Del Busso --- XenModel/Alerts/PerfmonDefinition.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XenModel/Alerts/PerfmonDefinition.cs b/XenModel/Alerts/PerfmonDefinition.cs index 83d0cc0d1..9b05ff224 100644 --- a/XenModel/Alerts/PerfmonDefinition.cs +++ b/XenModel/Alerts/PerfmonDefinition.cs @@ -300,7 +300,7 @@ namespace XenAdmin.Alerts if (perfmonConfigXML == null) return Array.Empty(); - return string.IsNullOrEmpty(perfmonConfigXML) ? Array.Empty() : GetPerfmonDefinitions(perfmonConfigXML); + return string.IsNullOrWhiteSpace(perfmonConfigXML) ? Array.Empty() : GetPerfmonDefinitions(perfmonConfigXML); } /// From f66216bf7b1a1634d0487ca1f13f96f596016440 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:18:32 +0000 Subject: [PATCH 51/62] CP-36392: Improve readability in `Name` method of `Network`'s xapi extension Signed-off-by: Danilo Del Busso --- XenModel/XenAPI-Extensions/Network.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/XenModel/XenAPI-Extensions/Network.cs b/XenModel/XenAPI-Extensions/Network.cs index d24cfb213..2d0c071c9 100644 --- a/XenModel/XenAPI-Extensions/Network.cs +++ b/XenModel/XenAPI-Extensions/Network.cs @@ -74,15 +74,16 @@ namespace XenAPI var coordinator_ref = pool.master.opaque_ref; - var pifs = Connection.ResolveAll(PIFs); + var pifs = Connection.ResolveAll(PIFs); + var pif = pifs.FirstOrDefault(p => p.host.opaque_ref == coordinator_ref); + if (pif != null) + return PIFName(pif); - var filteredPifs = pifs.Where(pif => pif.host.opaque_ref == coordinator_ref).ToList(); - if (filteredPifs.Count > 0) - { - return PIFName(filteredPifs.First()); - } - - return pifs.Count > 0 ? PIFName(pifs.First()) : name_label; + pif = pifs.FirstOrDefault(); + if (pif != null) + return PIFName(pif); + + return name_label; } public bool AllHostsCanSeeNetwork() From 11e90940e0bfa8b261a28bb5cce50a98429aa3f3 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:21:08 +0000 Subject: [PATCH 52/62] CP-36392: Simplify `Equals` method in `QueryTypes.cs` Signed-off-by: Danilo Del Busso --- XenModel/XenSearch/QueryTypes.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/XenModel/XenSearch/QueryTypes.cs b/XenModel/XenSearch/QueryTypes.cs index 9d096ae98..109902220 100644 --- a/XenModel/XenSearch/QueryTypes.cs +++ b/XenModel/XenSearch/QueryTypes.cs @@ -1196,9 +1196,7 @@ namespace XenAdmin.XenSearch public override bool Equals(object obj) { - if (!(obj is IPAddressQuery other)) - return false; - return address.Equals(other.address); + return obj is IPAddressQuery other && address.Equals(other.address); } } From e791b70ba7b10a4205626b6dc89b032a62682796 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Mon, 15 Nov 2021 10:21:39 +0000 Subject: [PATCH 53/62] CP-36392: Move `return` to new line in `Search.cs` Signed-off-by: Danilo Del Busso --- XenModel/XenSearch/Search.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/XenModel/XenSearch/Search.cs b/XenModel/XenSearch/Search.cs index 27d77232b..cad88e364 100644 --- a/XenModel/XenSearch/Search.cs +++ b/XenModel/XenSearch/Search.cs @@ -293,7 +293,8 @@ namespace XenAdmin.XenSearch var session = connection.DuplicateSession(); var pools = connection.Cache.Pools; - if (pools.Length <= 0) return false; + if (pools.Length <= 0) + return false; var pool = pools.First(); Pool.remove_from_gui_config(session, pool.opaque_ref, key); From 5078c4db0d54f745f4f64ac77e4fd115c9729582 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 7 Oct 2021 23:31:42 +0100 Subject: [PATCH 54/62] CP-38086: Block upgrade for PV guests. Signed-off-by: Konstantina Chremmou # Conflicts: # Branding/Branding.resx # XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs # XenAdmin/Wizards/PatchingWizard/PatchingWizard_PrecheckPage.cs # XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs # XenModel/BrandManager.cs # XenModel/Utils/Helpers.cs --- Branding/Branding.resx | 3 +++ XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs | 18 ++++----------- .../PoolProblem/PoolHasPVGuestWarningUrl.cs | 23 +++++++++++++++++++ .../RollingUpgradeWizardPrecheckPage.cs | 2 +- XenModel/BrandManager.cs | 2 ++ XenModel/Utils/Helpers.cs | 6 +++++ 6 files changed, 40 insertions(+), 14 deletions(-) diff --git a/Branding/Branding.resx b/Branding/Branding.resx index 6c38eff7d..77fbebc14 100644 --- a/Branding/Branding.resx +++ b/Branding/Branding.resx @@ -182,6 +182,9 @@ 8.2 + + 8.2.1 + [BRANDING_PRODUCT_VERSION_TEXT] diff --git a/XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs b/XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs index 2969af695..3422b0555 100644 --- a/XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs +++ b/XenAdmin/Diagnostics/Checks/PVGuestsCheck.cs @@ -43,41 +43,30 @@ namespace XenAdmin.Diagnostics.Checks class PVGuestsCheck : HostPostLivenessCheck { private readonly Pool _pool; - private readonly bool _upgrade; private readonly bool _manualUpgrade; private readonly Dictionary _installMethodConfig; - public PVGuestsCheck(Host coordinator, bool upgrade, bool manualUpgrade = false, Dictionary installMethodConfig = null) + public PVGuestsCheck(Host coordinator, bool manualUpgrade = false, Dictionary installMethodConfig = null) : base(coordinator) { _pool = Helpers.GetPoolOfOne(Host?.Connection); - _upgrade = upgrade; _manualUpgrade = manualUpgrade; _installMethodConfig = installMethodConfig; } public override bool CanRun() { - if (Helpers.QuebecOrGreater(Host)) + if (Helpers.YangtzeOrGreater(Host)) return false; if (_pool == null || !_pool.Connection.Cache.VMs.Any(vm => vm.IsPvVm())) return false; - if (!_upgrade && !Helpers.NaplesOrGreater(Host)) - return false; - return true; } protected override Problem RunHostCheck() { - //update case - if (!_upgrade) - return new PoolHasPVGuestWarningUrl(this, _pool); - - //upgrade case - if (!_manualUpgrade) { var hotfix = HotfixFactory.Hotfix(Host); @@ -95,6 +84,9 @@ namespace XenAdmin.Diagnostics.Checks if (string.IsNullOrEmpty(upgradePlatformVersion)) return new PoolHasPVGuestWarningUrl(this, _pool); + if (Helpers.YangtzeOrGreater(upgradePlatformVersion)) + return new PoolHasPVGuestProblem(this, _pool); + if (Helpers.QuebecOrGreater(upgradePlatformVersion)) return new PoolHasPVGuestWarningUrl(this, _pool); diff --git a/XenAdmin/Diagnostics/Problems/PoolProblem/PoolHasPVGuestWarningUrl.cs b/XenAdmin/Diagnostics/Problems/PoolProblem/PoolHasPVGuestWarningUrl.cs index 1ae4f6322..b75a3e8d2 100644 --- a/XenAdmin/Diagnostics/Problems/PoolProblem/PoolHasPVGuestWarningUrl.cs +++ b/XenAdmin/Diagnostics/Problems/PoolProblem/PoolHasPVGuestWarningUrl.cs @@ -57,4 +57,27 @@ namespace XenAdmin.Diagnostics.Problems.PoolProblem public override string HelpMessage => LinkText; public override string LinkText => Messages.LEARN_MORE; } + + + class PoolHasPVGuestProblem : ProblemWithInformationUrl + { + private readonly Pool _pool; + + public PoolHasPVGuestProblem(Check check, Pool pool) + : base(check) + { + _pool = pool; + } + + private string PVGuestCheckUrl => string.Format(InvisibleMessages.PV_GUESTS_CHECK_URL); + public override Uri UriToLaunch => new Uri(PVGuestCheckUrl); + public override string Title => Description; + + public override string Description => + string.Format(Messages.POOL_HAS_PV_GUEST_WARNING, _pool.Name(), + string.Format(Messages.STRING_SPACE_STRING, BrandManager.ProductBrand, BrandManager.ProductVersion81)); + + public override string HelpMessage => LinkText; + public override string LinkText => Messages.LEARN_MORE; + } } diff --git a/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs b/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs index 886e68870..b74722b7c 100644 --- a/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs +++ b/XenAdmin/Wizards/RollingUpgradeWizard/RollingUpgradeWizardPrecheckPage.cs @@ -240,7 +240,7 @@ namespace XenAdmin.Wizards.RollingUpgradeWizard //Checking PV guests - for hosts that have any PV guests and warn the user before the upgrade. var pvChecks = (from Host server in SelectedCoordinators - let check = new PVGuestsCheck(server, true, ManualUpgrade, InstallMethodConfig) + let check = new PVGuestsCheck(server, ManualUpgrade, InstallMethodConfig) where check.CanRun() select check as Check).ToList(); diff --git a/XenModel/BrandManager.cs b/XenModel/BrandManager.cs index 2f2416c70..cd05cbcbc 100644 --- a/XenModel/BrandManager.cs +++ b/XenModel/BrandManager.cs @@ -82,6 +82,8 @@ namespace XenAdmin.Core public static readonly string ProductVersion82 = Get("PRODUCT_VERSION_8_2"); + public static readonly string ProductVersion821 = Get("PRODUCT_VERSION_8_2_1"); + public static readonly string ProductVersionPost82 = Get("PRODUCT_VERSION_POST_8_2"); public static readonly string ProductVersionText = Get("PRODUCT_VERSION_TEXT"); diff --git a/XenModel/Utils/Helpers.cs b/XenModel/Utils/Helpers.cs index 1141fe6d3..7641d8216 100755 --- a/XenModel/Utils/Helpers.cs +++ b/XenModel/Utils/Helpers.cs @@ -497,6 +497,12 @@ namespace XenAdmin.Core return platformVersion != null && productVersionCompare(platformVersion, "3.2.50") >= 0; } + /// May be null, in which case true is returned. + public static bool YangtzeOrGreater(IXenConnection conn) + { + return conn == null || YangtzeOrGreater(Helpers.GetCoordinator(conn)); + } + /// May be null, in which case true is returned. public static bool YangtzeOrGreater(Host host) { From 47510f5b07fa1410052abbef4e63cc0bfe80d173 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 16 Nov 2021 11:39:50 +0000 Subject: [PATCH 55/62] CP-36392: Reassign `expiryGroups` after ordering regression from db2c00d5 Signed-off-by: Danilo Del Busso --- XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs index a946477b3..7d33edbab 100644 --- a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs +++ b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs @@ -213,9 +213,9 @@ namespace XenAdmin.Dialogs into g select new { ExpiryDate = g.Key, Hosts = g }; - if(expiryGroups.Count() > 1) + if (expiryGroups.Count() > 1) { - expiryGroups.OrderBy(g => g.ExpiryDate); + expiryGroups = expiryGroups.OrderBy(g => g.ExpiryDate).ToList(); if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) return true; } From 3e861411db045c031b9b54663e6762d83edae192 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 16 Nov 2021 11:42:18 +0000 Subject: [PATCH 56/62] CP-36392: Invert `if` statements to reduce nesting in `HostMemoryControls` and `changeControlDomainMemoryCommand` Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs | 10 +++++----- XenAdmin/Controls/Ballooning/HostMemoryControls.cs | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs b/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs index bb133cab3..df40022e6 100644 --- a/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs +++ b/XenAdmin/Commands/ChangeControlDomainMemoryCommand.cs @@ -59,11 +59,11 @@ namespace XenAdmin.Commands protected override void RunCore(SelectedItemCollection selection) { var host = selection[0].HostAncestor; - if (host != null) - { - using (var dlg = new ControlDomainMemoryDialog(host)) - dlg.ShowDialog(Program.MainWindow); - } + if (host == null) + return; + + using (var dlg = new ControlDomainMemoryDialog(host)) + dlg.ShowDialog(Program.MainWindow); } protected override bool ConfirmationRequired diff --git a/XenAdmin/Controls/Ballooning/HostMemoryControls.cs b/XenAdmin/Controls/Ballooning/HostMemoryControls.cs index 138503859..07e7c3bf0 100644 --- a/XenAdmin/Controls/Ballooning/HostMemoryControls.cs +++ b/XenAdmin/Controls/Ballooning/HostMemoryControls.cs @@ -127,11 +127,11 @@ namespace XenAdmin.Controls.Ballooning private void valueControlDomain_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - if (host != null) - { - using (var dlg = new ControlDomainMemoryDialog(host)) - dlg.ShowDialog(Program.MainWindow); - } + if (host == null) + return; + + using (var dlg = new ControlDomainMemoryDialog(host)) + dlg.ShowDialog(Program.MainWindow); } internal void UnregisterHandlers() From f2fdf31a5a5ca7d467eb9722ed4c89d76db8ac7c Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Wed, 17 Nov 2021 09:01:25 +0000 Subject: [PATCH 57/62] CP-36392: Avoid multiple enumerations in `LicenseStatus.cs` Signed-off-by: Danilo Del Busso --- XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs index 7d33edbab..8772390ca 100644 --- a/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs +++ b/XenAdmin/Dialogs/LicenseManager/LicenseStatus.cs @@ -207,13 +207,13 @@ namespace XenAdmin.Dialogs if (freeCount == 0 || freeCount < xenObject.Connection.Cache.Hosts.Length) return false; - var expiryGroups = from Host h in xenObject.Connection.Cache.Hosts + var expiryGroups = (from Host h in xenObject.Connection.Cache.Hosts let exp = h.LicenseExpiryUTC() group h by exp into g - select new { ExpiryDate = g.Key, Hosts = g }; + select new { ExpiryDate = g.Key, Hosts = g }).ToList(); - if (expiryGroups.Count() > 1) + if (expiryGroups.Count > 1) { expiryGroups = expiryGroups.OrderBy(g => g.ExpiryDate).ToList(); if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) From 8281ae5c05bb167228adddd1f2bc97808855a7a3 Mon Sep 17 00:00:00 2001 From: CitrixChris <86611314+CitrixChris@users.noreply.github.com> Date: Mon, 22 Nov 2021 12:02:26 +0000 Subject: [PATCH 58/62] CA-359809 improved illegal character message (#2898) * CA-359809 improved illegal character message Signed-off-by: Christophe25 * CA-359809 cleared whitespace, improve code readability Signed-off-by: Christophe25 * CA-359809 implemented reviewer comments. Moved Path validator to XenModel Project where other language files have already been set up. Improved error messages. Signed-off-by: Christophe25 * CA-359809 improved string localisation, Code tidy Cannot became can not, messages file alphabetised, improved readability with using xenmodel as opposed to direct call Signed-off-by: Christophe25 * CA-359809 changed can not to cannot Signed-off-by: Christophe25 --- .../BugToolPageDestination.cs | 9 +- .../ExportWizard/ExportAppliancePage.cs | 9 +- .../Wizards/ExportWizard/ExportOptionsPage.cs | 18 +- .../Wizards/ImportWizard/ImageVMConfigPage.cs | 7 +- .../Wizards/ImportWizard/ImportSourcePage.cs | 15 +- XenCenterLib/PathValidator.cs | 100 ------- XenCenterLib/XenCenterLib.csproj | 1 - XenModel/Messages.Designer.cs | 36 +++ XenModel/Messages.resx | 270 +++++++++--------- XenModel/PathValidator.cs | 135 +++++++++ XenModel/XenModel.csproj | 1 + 11 files changed, 343 insertions(+), 258 deletions(-) delete mode 100644 XenCenterLib/PathValidator.cs create mode 100644 XenModel/PathValidator.cs diff --git a/XenAdmin/Wizards/BugToolWizardFiles/BugToolPageDestination.cs b/XenAdmin/Wizards/BugToolWizardFiles/BugToolPageDestination.cs index 91b4ba9b4..03f8b497f 100644 --- a/XenAdmin/Wizards/BugToolWizardFiles/BugToolPageDestination.cs +++ b/XenAdmin/Wizards/BugToolWizardFiles/BugToolPageDestination.cs @@ -38,6 +38,7 @@ using XenAdmin.Controls.Common; using XenAdmin.Core; using XenAdmin.Dialogs; using XenCenterLib; +using XenModel; using Registry = XenAdmin.Core.Registry; @@ -206,9 +207,9 @@ namespace XenAdmin.Wizards.BugToolWizardFiles if (String.IsNullOrEmpty(name)) return false; - if (!PathValidator.IsFileNameValid(name)) + if (!PathValidator.IsFileNameValid(name, out string invalidNameMsg)) { - error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_NAME; + error = $"{Messages.BUGTOOL_PAGE_DESTINATION_INVALID_NAME} {invalidNameMsg}"; return false; } @@ -217,9 +218,9 @@ namespace XenAdmin.Wizards.BugToolWizardFiles string path = String.Format("{0}\\{1}", folder, name); - if (!PathValidator.IsPathValid(path)) + if (!PathValidator.IsPathValid(path, out string invalidPathMsg)) { - error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_FOLDER; + error = $"{Messages.BUGTOOL_PAGE_DESTINATION_INVALID_FOLDER} {invalidPathMsg}"; return false; } diff --git a/XenAdmin/Wizards/ExportWizard/ExportAppliancePage.cs b/XenAdmin/Wizards/ExportWizard/ExportAppliancePage.cs index 7f2ca33b9..78823b63f 100644 --- a/XenAdmin/Wizards/ExportWizard/ExportAppliancePage.cs +++ b/XenAdmin/Wizards/ExportWizard/ExportAppliancePage.cs @@ -36,6 +36,7 @@ using XenAdmin.Controls; using XenAdmin.Controls.Common; using XenAdmin.Wizards.ExportWizard.ApplianceChecks; using XenCenterLib; +using XenModel; namespace XenAdmin.Wizards.ExportWizard { @@ -166,9 +167,9 @@ namespace XenAdmin.Wizards.ExportWizard if (String.IsNullOrEmpty(ApplianceFileName)) return false; - if (!PathValidator.IsFileNameValid(ApplianceFileName)) + if (!PathValidator.IsFileNameValid(ApplianceFileName, out string invalidNameMsg)) { - error = Messages.EXPORT_APPLIANCE_PAGE_ERROR_INALID_APP; + error = string.Join(" ", new []{ Messages.EXPORT_APPLIANCE_PAGE_ERROR_INALID_APP , invalidNameMsg}); return false; } @@ -177,9 +178,9 @@ namespace XenAdmin.Wizards.ExportWizard string path = String.Format("{0}\\{1}", ApplianceDirectory, ApplianceFileName); - if (!PathValidator.IsPathValid(path)) + if (!PathValidator.IsPathValid(path, out string invalidPathMsg)) { - error = Messages.EXPORT_APPLIANCE_PAGE_ERROR_INVALID_DIR; + error = string.Join(" ", new[] { Messages.EXPORT_APPLIANCE_PAGE_ERROR_INVALID_DIR, invalidPathMsg }); return false; } diff --git a/XenAdmin/Wizards/ExportWizard/ExportOptionsPage.cs b/XenAdmin/Wizards/ExportWizard/ExportOptionsPage.cs index 60762d632..b4e98b98c 100644 --- a/XenAdmin/Wizards/ExportWizard/ExportOptionsPage.cs +++ b/XenAdmin/Wizards/ExportWizard/ExportOptionsPage.cs @@ -35,18 +35,18 @@ using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Windows.Forms; -using XenCenterLib; using XenOvf; using XenAdmin.Controls; +using XenModel; namespace XenAdmin.Wizards.ExportWizard { - /// - /// Class representing the page of the ExportAppliance wizard where the user specifies - /// whether to create a manifest, sign the appliance or encrypt files and whether to - /// create an OVA package or compress the OVF files - /// - internal partial class ExportOptionsPage : XenTabPage + /// + /// Class representing the page of the ExportAppliance wizard where the user specifies + /// whether to create a manifest, sign the appliance or encrypt files and whether to + /// create an OVA package or compress the OVF files + /// + internal partial class ExportOptionsPage : XenTabPage { private const int MIN_PASSWORD_STRENGTH = 1; private int m_passwordStrength; @@ -285,9 +285,9 @@ namespace XenAdmin.Wizards.ExportWizard { error = string.Empty; - if (!PathValidator.IsPathValid(m_textBoxCertificate.Text))//includes null check + if (!PathValidator.IsPathValid(m_textBoxCertificate.Text, out string invalidPathMsg))//includes null check { - error = Messages.EXPORT_SECURITY_PAGE_ERROR_INVALID_CERT; + error = string.Join(" ", new[] { Messages.EXPORT_SECURITY_PAGE_ERROR_INVALID_CERT, invalidPathMsg }); return false; } diff --git a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs index 3bf250a90..9da082816 100644 --- a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs @@ -32,7 +32,7 @@ using System; using XenAdmin.Controls; using XenCenterLib; - +using XenModel; namespace XenAdmin.Wizards.ImportWizard { @@ -118,9 +118,10 @@ namespace XenAdmin.Wizards.ImportWizard if (String.IsNullOrEmpty(name)) return false; - if (!PathValidator.IsFileNameValid(name)) + + if (!PathValidator.IsFileNameValid(name, out string invalidNameMsg)) { - error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_INVALID_PATH; + error = invalidNameMsg; return false; } return true; diff --git a/XenAdmin/Wizards/ImportWizard/ImportSourcePage.cs b/XenAdmin/Wizards/ImportWizard/ImportSourcePage.cs index 3816258b0..2b3c484d3 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSourcePage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSourcePage.cs @@ -50,7 +50,7 @@ using XenCenterLib.Archive; using XenOvf; using XenOvf.Definitions.VMC; using XenOvf.Utilities; - +using XenModel; namespace XenAdmin.Wizards.ImportWizard { @@ -370,21 +370,20 @@ namespace XenAdmin.Wizards.ImportWizard /// private bool CheckPathValid(out string error) { - error = string.Empty; - + error = string.Empty; if (String.IsNullOrEmpty(FilePath)) return false; if (IsUri()) return CheckDownloadFromUri(out error); - if (!PathValidator.IsPathValid(FilePath)) + if (!PathValidator.IsPathValid(FilePath, out string invalidNameMsg)) { - error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_INVALID_PATH; - return false; + error = invalidNameMsg; + return false; } - - return true; + + return true; } /// diff --git a/XenCenterLib/PathValidator.cs b/XenCenterLib/PathValidator.cs deleted file mode 100644 index b2e233d0a..000000000 --- a/XenCenterLib/PathValidator.cs +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright (c) Citrix Systems, Inc. - * All rights reserved. - * - * 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; - -namespace XenCenterLib -{ - public class PathValidator - { - private static readonly char[] m_invalidFileCharList = Path.GetInvalidFileNameChars(); - private static readonly string[] m_deviceNames = { - "CON", "PRN", "AUX", "NUL", - "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", - "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" - }; - - public static bool IsFileNameValid(string filename) - { - if (filename.IndexOfAny(m_invalidFileCharList) > -1) - return false; - - foreach (var name in m_deviceNames) - { - if (name == filename.ToUpper()) - return false; - } - - return true; - } - - public static bool IsPathValid(string path) - { - if (string.IsNullOrEmpty(path)) - return false; - - try - { - if (Path.IsPathRooted(path)) - { - path = path[0] == '\\' && path.Length == 1 - ? path.Substring(1) - : path.Substring(2); - } - } - catch(ArgumentException) - { - //path contains a character from Path.GetInvalidPathChars() - return false; - } - - string[] parts = path.Split(new[] {'\\'}); - - if (parts.Length > 0) - { - foreach (var part in parts) - { - if (part.IndexOfAny(m_invalidFileCharList) > -1) - return false; - - foreach (var name in m_deviceNames) - { - if (name == part.ToUpper()) - return false; - } - } - } - - return true; - } - } -} diff --git a/XenCenterLib/XenCenterLib.csproj b/XenCenterLib/XenCenterLib.csproj index 8664d927f..962af0444 100644 --- a/XenCenterLib/XenCenterLib.csproj +++ b/XenCenterLib/XenCenterLib.csproj @@ -79,7 +79,6 @@ - diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index b1d372572..c156d8b13 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -16978,6 +16978,24 @@ namespace XenAdmin { } } + /// + /// Looks up a localized string similar to A file name cannot be a device name.. + /// + public static string FILE_NAME_IS_DEVICE_NAME_ERROR_MESSAGE { + get { + return ResourceManager.GetString("FILE_NAME_IS_DEVICE_NAME_ERROR_MESSAGE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path section {0} matches a device name.. + /// + public static string FILE_PATH_DEVICE_NAME_ERROR_MESSAGE { + get { + return ResourceManager.GetString("FILE_PATH_DEVICE_NAME_ERROR_MESSAGE", resourceCulture); + } + } + /// /// Looks up a localized string similar to Acrobat (PDF) file. /// @@ -20224,6 +20242,15 @@ namespace XenAdmin { } } + /// + /// Looks up a localized string similar to The following characters are invalid: {0}. + /// + public static string ILLEGAL_CHARACTER_ERROR_MESSAGE { + get { + return ResourceManager.GetString("ILLEGAL_CHARACTER_ERROR_MESSAGE", resourceCulture); + } + } + /// /// Looks up a localized string similar to It is not possible to connect to the iLO service. Please review your configuration.. /// @@ -30178,6 +30205,15 @@ namespace XenAdmin { } } + /// + /// Looks up a localized string similar to Path cannot be null or empty.. + /// + public static string PATH_CAN_NOT_BE_NULL_ERROR_MESSAGE { + get { + return ResourceManager.GetString("PATH_CAN_NOT_BE_NULL_ERROR_MESSAGE", resourceCulture); + } + } + /// /// Looks up a localized string similar to Path does not exist.. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index f045c9f44..66bedeef7 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -1596,6 +1596,9 @@ The user you are currently logged into '{1}' with is a member of '{0}'. Proceedi Do you want to continue? + + Please wait while {0} establishes your current external authentication configuration. + Subject could not be resolved in your AD @@ -1663,9 +1666,6 @@ Do you want to continue? Do you want to continue? - - Please wait while {0} establishes your current external authentication configuration. - AD is not currently configured for pool '{0}'. To enable AD authentication, click Join Domain. @@ -1850,19 +1850,19 @@ Note that if RBAC is enabled, only alerts which you have privileges to dismiss w You have applied filters to the list of alerts. Do you want to export all alerts from every connected server, or only the alerts you have chosen to view? - + All {0} attempts originated from unknown sources. - + The most common attempts originated from the following sources: - + There has been a total of {0} failed login attempts. - + {0} attempts originated from unknown sources. - - + + Last attempt on: {0} @@ -1916,12 +1916,12 @@ Note that if RBAC is enabled, only alerts which you have privileges to dismiss w Allowed MTU value: {0} - - Would you like {0} to periodically check the internet for new versions of {0} and {1}? - &Show internet proxy settings + + Would you like {0} to periodically check the internet for new versions of {0} and {1}? + &Allow to continue @@ -2664,15 +2664,15 @@ This will cancel compilation of the status report. Valid from {0} to {1} - - Certificate Verification - Enabled on the pool, but disabled on: Disabled, but enabled on the pool + + Certificate Verification + Ability to download updates @@ -2780,12 +2780,6 @@ Do you want to assign it to the schedule '{2}' instead? Checking security protocol - - vSwitch Controller check - - - Checking vSwitch Controller configuration - Checking reboots required @@ -2807,6 +2801,12 @@ Do you want to assign it to the schedule '{2}' instead? Checking upgrade hotfix status + + vSwitch Controller check + + + Checking vSwitch Controller configuration + Checking {0} version @@ -3673,6 +3673,9 @@ This action cannot be undone. Are you sure you want to continue? Convert VM to Template + + Coordinator + Copy @@ -5646,15 +5649,15 @@ Would you like to eject these ISOs before continuing? EULAs + + You cannot nominate a new coordinator while the pool is in the process of creating a cluster. + Enter Maintenance Mode - {0} {0} Eject the CD - - You cannot nominate a new coordinator while the pool is in the process of creating a cluster. - You cannot nominate a new coordinator while HA is being disabled on the pool. @@ -5935,6 +5938,12 @@ Would you like to eject these ISOs before continuing? All files + + A file name cannot be a device name. + + + Path section {0} matches a device name. + Acrobat (PDF) file @@ -7043,6 +7052,9 @@ This might result in failure to migrate VMs to this server during the RPU or to &Ignore + + The following characters are invalid: {0} + It is not possible to connect to the iLO service. Please review your configuration. @@ -8297,9 +8309,6 @@ This will permanently delete and reinitialize all local storage on the servers. Subscription Advantage required - - Coordinator - Max @@ -8448,12 +8457,12 @@ Are you sure you want to detach this storage repository? Certificate verification is not enabled on '{0}'. Would you like to enable it now? - - Before enabling certificate verification ensure that there are no operations running in the pool, otherwise they will be interrupted. - &Yes, Enable certificate verification + + Before enabling certificate verification ensure that there are no operations running in the pool, otherwise they will be interrupted. + Unable to connect to server '{0}'. {1} @@ -8516,11 +8525,14 @@ This action is final and unrecoverable. Writing password information failed: {0} + + You cannot remove the coordinator from the pool. + The pool Coordinator will become a standalone server, are you sure you want to continue? - - You cannot remove the coordinator from the pool. + + You must eject all other pool members from the pool before you can delete the pool. [{0}] There has been an unexpected error. Technical details about this error have been saved to the following file. Please send this to your support representative. @@ -8564,9 +8576,6 @@ Do you want to continue? Do you want to continue? - - You must eject all other pool members from the pool before you can delete the pool. - This will delete the selected network interface permanently. Continue? @@ -8881,8 +8890,14 @@ You should only proceed if you have verified that these settings are correct. New Private Network - - Clustering is enabled on this server. + + The coordinator is still connecting + + + The coordinator is disconnected + + + Your current role on the coordinator is not authorized to add hosts to the coordinator's pool This server has different updates from the coordinator @@ -8926,15 +8941,6 @@ You should only proceed if you have verified that these settings are correct. This server's Linux pack installation state differs from that of the coordinator - - The coordinator is still connecting - - - The coordinator is disconnected - - - Your current role on the coordinator is not authorized to add hosts to the coordinator's pool - The pool has already reached the maximum number of servers allowed by your license @@ -9402,12 +9408,6 @@ Review these settings, then click Previous if you need to change anything. Other Locate the operating system installation media - - Disk '{0}' - - - Created by template provisioner - The default SR '{0}' cannot be seen from the VM's home server. @@ -9417,9 +9417,21 @@ Review these settings, then click Previous if you need to change anything. Other The default SR '{0}' does not have enough free space for the new VM's disks. + + Disk '{0}' + + + Created by template provisioner + Storage + + <no suitable storage> + + + The SR '{0}' is overcommitted. There is only {1} of free space and the new VM requires {2}. + The SR suggested by the template ('{0}') cannot be seen from the VM's home server. @@ -9429,12 +9441,6 @@ Review these settings, then click Previous if you need to change anything. Other The SR suggested by the template ('{0}') does not have enough free space for the new VM's disks. - - <no suitable storage> - - - The SR '{0}' is overcommitted. There is only {1} of free space and the new VM requires {2}. - Configure storage for the new VM @@ -9456,9 +9462,6 @@ Review these settings, then click Previous if you need to change anything. Other Gooroom - - Rocky - Linx @@ -9477,6 +9480,9 @@ Review these settings, then click Previous if you need to change anything. Other Red Hat + + Rocky + Scientific Linux @@ -9580,6 +9586,9 @@ Do you want to enable AD authentication on your server and join it to the same d All pool members must use the same authentication method. Do you want to enable AD authentication on these servers and join them to the same domain as the pool? + + Clustering is enabled on this server. + You are attempting to add the server '{0}' to a pool with a coordinator that is using an older CPU. @@ -9716,12 +9725,12 @@ It is strongly recommended that you Cancel and apply the latest version of the p SR-IOV is already enabled on all the SR-IOV capable NICs. - - {0} (Hidden) - {0} (Bonded member) + + {0} (Hidden) + Network Interface Cards @@ -9761,14 +9770,14 @@ It is strongly recommended that you Cancel and apply the latest version of the p Events: {0} - - {0} in progress + + 1 error {0} errors - - 1 error + + {0} in progress Events ({0} errors) @@ -10465,6 +10474,9 @@ File not found Update uploaded to server '{0}' + + Path cannot be null or empty. + Path does not exist. @@ -10555,12 +10567,12 @@ File not found error. - - Server '{0}' could not be evacuated because there were no servers available to accommodate all the VMs being migrated from this server. Please reboot the other servers that are pending a reboot following the update installation, and then press Retry to resume the process. - Server '{0}' could not be evacuated because there was not enough free memory on the other servers to migrate all the VMs from this server. Please suspend or shut down some VMs and then press Retry to resume the process. + + Server '{0}' could not be evacuated because there were no servers available to accommodate all the VMs being migrated from this server. Please reboot the other servers that are pending a reboot following the update installation, and then press Retry to resume the process. + Installing {0} on '{1}'... @@ -10674,6 +10686,12 @@ Please reconnect the host and try again Pool: + + Pool coordinator + + + Could not find the pool coordinator in {0}'s cache. + Pool '{0}' has HA enabled. You must disable HA before making the pool into a standalone server. @@ -10740,12 +10758,6 @@ Please reconnect the host and try again Pool License - - Pool coordinator - - - Could not find the pool coordinator in {0}'s cache. - Pool name cannot be empty @@ -10799,12 +10811,24 @@ If this value does not correspond to a server within the selected resource pool Probing for LUNs on {0} - - {0}: Health Check has been removed in {1} {2}. + + {0}: The coordinator needs to be rebooted first + + + {0}: This update requires the coordinator to be rebooted first + + + {0}: Toolstack on coordinator needs to be restarted first + + + {0}: This update requires the toolstack on coordinator to be restarted first Disable Health Check + + {0}: Health Check has been removed in {1} {2}. + Server '{0}' @@ -10820,15 +10844,6 @@ If this value does not correspond to a server within the selected resource pool If you are upgrading to {0} and above, you will not be able to use security protocols earlier than TLS 1.2 for communication with the server and you may lose permanently access to it. - - {0}: Support for the vSwitch Controller has been removed in {1}. - - - Support for the vSwitch Controller has been removed in {0}. You must deconfigure the controller because any features that require it will no longer work. Please click the link below for more information. - - - If you are upgrading to {0} and above, you must deconfigure the vSwitch Controller because support for it has been removed in this release and any features that require it will no longer work. Please click the link below for more information. - The MAC address entered has already been assigned to the VM: {1} @@ -10838,18 +10853,6 @@ Are you sure you want to continue? Duplicate MAC address - - {0}: The coordinator needs to be rebooted first - - - {0}: This update requires the coordinator to be rebooted first - - - {0}: Toolstack on coordinator needs to be restarted first - - - {0}: This update requires the toolstack on coordinator to be restarted first - Pool '{0}' @@ -10876,6 +10879,15 @@ Click Previous if you need to go back and specify a different network location o VM '{0}' + + {0}: Support for the vSwitch Controller has been removed in {1}. + + + Support for the vSwitch Controller has been removed in {0}. You must deconfigure the controller because any features that require it will no longer work. Please click the link below for more information. + + + If you are upgrading to {0} and above, you must deconfigure the vSwitch Controller because support for it has been removed in this release and any features that require it will no longer work. Please click the link below for more information. + {0} version @@ -11530,6 +11542,9 @@ The coordinator must be upgraded first, so if you skip the coordinator, the roll You cannot rotate the pool secret when HA is on. + + Rotate &Pool Secret + You cannot enable clustering while a pool secret rotation is in progress. @@ -11539,9 +11554,6 @@ The coordinator must be upgraded first, so if you skip the coordinator, the roll You cannot nominate a new coordinator while a pool secret rotation is in progress. - - Rotate &Pool Secret - A {0} user does not have sufficient permissions to rotate the pool secret. Please login using an account with one of the following roles: @@ -11619,12 +11631,12 @@ The coordinator must be upgraded first, so if you skip the coordinator, the roll Saving search '{0}'... - - Saving VM properties - Saving configuration... + + Saving VM properties + Saving Workload Balancing configuration. @@ -11937,16 +11949,6 @@ The coordinator must be upgraded first, so if you skip the coordinator, the roll Slack: - - Server '{0}' is a member of pool '{1}' and is already connected. - - - Server '{0}' is in a pool. To connect to a pool, you must connect to the pool coordinator. -Do you want to connect to the pool coordinator '{1}'? - - - This pool contains servers earlier than {0} {1}. Please use an earlier version of {2} to manage this pool. - smaller than @@ -12143,13 +12145,13 @@ You may need to reboot your server(s) to enable SR-IOV network. The SR is currently detached. + + You cannot create a disk greater than {0} on this SR. + Initial allocation: {0} Incremental allocation: {1} - - You cannot create a disk greater than {0} on this SR. - This SR does not need to be upgraded. @@ -12168,12 +12170,12 @@ Incremental allocation: {1} VMs without a home server cannot have disks on local storage - - Disk size ({0}) exceeds SR size ({1}) - SR '{0}' does not have {1} of free space to import virtual disk {2}. + + Disk size ({0}) exceeds SR size ({1}) + {0} required when only {1} available @@ -12401,6 +12403,16 @@ The upper limit: SR size / {2} Sun + + Server '{0}' is a member of pool '{1}' and is already connected. + + + Server '{0}' is in a pool. To connect to a pool, you must connect to the pool coordinator. +Do you want to connect to the pool coordinator '{1}'? + + + This pool contains servers earlier than {0} {1}. Please use an earlier version of {2} to manage this pool. + {0} (version {1}) @@ -13120,12 +13132,12 @@ Note that if RBAC is enabled, only updates which you have privileges to dismiss {0}: Check skipped because hosts in pool '{1}' have incompatible CPUs - - Upgrade host {0} - Upgrade coordinator {0} + + Upgrade host {0} + Apply Upgrade @@ -13386,14 +13398,14 @@ To start a {0} trial, click the button below. {0} - currently in use by '{1}' - - The vCPUs can only be changed when the VM is shut down. - The number of VCPUs is greater than the number of physical CPUs on the host server. This will significantly reduce VM performance. To optimize VM performance, you should reduce the number of VCPUs to less than or equal to the number of physical CPUs. + + The vCPUs can only be changed when the VM is shut down. + VDI @@ -14725,4 +14737,4 @@ Any disk in your VM's DVD drive will be ejected when installing {1}. You are here - + \ No newline at end of file diff --git a/XenModel/PathValidator.cs b/XenModel/PathValidator.cs new file mode 100644 index 000000000..10e933847 --- /dev/null +++ b/XenModel/PathValidator.cs @@ -0,0 +1,135 @@ +/* Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * 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.Linq; +using XenAdmin; + +namespace XenModel +{ + public class PathValidator + { + private static readonly char[] m_invalidFileCharList = Path.GetInvalidFileNameChars(); + private static readonly string[] m_deviceNames = { + "CON", "PRN", "AUX", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" + }; + + private static string IllegalFileCharMsg { + get { + return string.Format(Messages.ILLEGAL_CHARACTER_ERROR_MESSAGE, string.Join(" ", m_invalidFileCharList.Where(c => !char.IsControl(c)))); + } + } + + private static string IllegalPathCharMsg + { + get + { + return string.Format(Messages.ILLEGAL_CHARACTER_ERROR_MESSAGE, string.Join(" ", m_invalidFileCharList.Where(c => !char.IsControl(c) && c != '\\'))); + + } + } + + public static bool IsFileNameValid(string filename, out string invalidNameMsg) + { + invalidNameMsg = string.Empty; + if (filename.IndexOfAny(m_invalidFileCharList) > -1) + { + invalidNameMsg = IllegalFileCharMsg; + return false; + } + + foreach (var name in m_deviceNames) + { + if (name == filename.ToUpper()) + { + invalidNameMsg = Messages.FILE_NAME_IS_DEVICE_NAME_ERROR_MESSAGE; + return false; + } + } + + return true; + } + + public static bool IsPathValid(string path, out string invalidPathMsg) + { + invalidPathMsg = string.Empty; + if (string.IsNullOrEmpty(path)) + { + invalidPathMsg = Messages.PATH_CAN_NOT_BE_NULL_ERROR_MESSAGE; + return false; + } + + try + { + if (Path.IsPathRooted(path)) + { + path = path[0] == '\\' && path.Length == 1 + ? path.Substring(1) + : path.Substring(2); + } + } + catch (ArgumentException) + { + //path contains some of the characters from Path.GetInvalidPathChars() + invalidPathMsg = IllegalPathCharMsg; + return false; + } + + var parts = path.Split('\\'); + + if (parts.Length > 0) + { + foreach (var part in parts) + { + if (part.IndexOfAny(m_invalidFileCharList) > -1) + { + invalidPathMsg = IllegalPathCharMsg; + return false; + } + + foreach (var name in m_deviceNames) + { + if (name == part.ToUpper()) + { + invalidPathMsg = string.Format(Messages.FILE_PATH_DEVICE_NAME_ERROR_MESSAGE, name); + return false; + } + } + } + } + + return true; + } + } +} diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 423381b95..78e009645 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -168,6 +168,7 @@ + True True From 355321faeab93cf6768d0377a976a4702cc319d3 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Fri, 5 Nov 2021 21:44:14 +0000 Subject: [PATCH 59/62] Made ovfModeOnly an optional parameter. Signed-off-by: Konstantina Chremmou --- XenAdmin/Commands/ImPortCommand.cs | 8 ++++---- XenAdmin/MainWindow.cs | 2 +- XenAdmin/Wizards/ImportWizard/ImportWizard.cs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/XenAdmin/Commands/ImPortCommand.cs b/XenAdmin/Commands/ImPortCommand.cs index 9ef720f97..178c997ff 100644 --- a/XenAdmin/Commands/ImPortCommand.cs +++ b/XenAdmin/Commands/ImPortCommand.cs @@ -49,14 +49,14 @@ namespace XenAdmin.Commands : base(mainWindow, pool) { } - public override string MenuText { get { return Messages.HOST_MENU_IMPORT_VM_TEXT; } } - - public override string ContextMenuText{get{return Messages.HOST_MENU_IMPORT_VM_TEXT;}} + public override string MenuText => Messages.HOST_MENU_IMPORT_VM_TEXT; + + public override string ContextMenuText => Messages.HOST_MENU_IMPORT_VM_TEXT; protected override void RunCore(SelectedItemCollection selection) { var con = selection.GetConnectionOfFirstItem(); - MainWindowCommandInterface.ShowPerConnectionWizard(con, new ImportWizard(con, selection.FirstAsXenObject, null, false)); + MainWindowCommandInterface.ShowPerConnectionWizard(con, new ImportWizard(con, selection.FirstAsXenObject, null)); } } } diff --git a/XenAdmin/MainWindow.cs b/XenAdmin/MainWindow.cs index ad918e5a7..11ff50d22 100755 --- a/XenAdmin/MainWindow.cs +++ b/XenAdmin/MainWindow.cs @@ -2706,7 +2706,7 @@ namespace XenAdmin { HelpersGUI.BringFormToFront(this); Host hostAncestor = SelectionManager.Selection.Count == 1 ? SelectionManager.Selection[0].HostAncestor : null; - new ImportWizard(SelectionManager.Selection.GetConnectionOfFirstItem(), hostAncestor, param, false).Show(); + new ImportWizard(SelectionManager.Selection.GetConnectionOfFirstItem(), hostAncestor, param).Show(); } #region XenSearch diff --git a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs index ab06d95a1..e35c6ac97 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs @@ -81,7 +81,7 @@ namespace XenAdmin.Wizards.ImportWizard private IXenConnection TargetConnection { get; set; } #endregion - public ImportWizard(IXenConnection con, IXenObject xenObject, string filename, bool ovfModeOnly) + public ImportWizard(IXenConnection con, IXenObject xenObject, string filename, bool ovfModeOnly = false) : base(con) { InitializeComponent(); From 051c205899dd2c7f8123e3ea1c446b7da18bbcf6 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Fri, 5 Nov 2021 21:46:07 +0000 Subject: [PATCH 60/62] CA-350411 part 2: Add conditional page control refresh in Import Wizard Signed-off-by: Konstantina Chremmou --- .../Wizards/ImportWizard/ImageVMConfigPage.cs | 16 +- .../Wizards/ImportWizard/ImportEulaPage.cs | 2 +- .../ImportWizard/ImportSecurityPage.cs | 2 +- .../ImportWizard/ImportSelectHostPage.cs | 2 +- .../ImportWizard/ImportSelectNetworkPage.cs | 2 +- .../ImportWizard/ImportSelectStoragePage.cs | 2 +- XenAdmin/Wizards/ImportWizard/ImportWizard.cs | 271 ++++++++++-------- .../ImportWizard/LunPerVdiImportPage.cs | 2 +- .../Wizards/ImportWizard/NetworkPickerPage.cs | 50 ++-- .../Wizards/ImportWizard/StoragePickerPage.cs | 25 +- XenModel/Mappings/VmMapping.cs | 28 +- XenOvfApi/OVF.cs | 45 ++- 12 files changed, 269 insertions(+), 178 deletions(-) diff --git a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs index 70bb08e0b..bfcc9c977 100644 --- a/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImageVMConfigPage.cs @@ -55,17 +55,17 @@ namespace XenAdmin.Wizards.ImportWizard /// /// Gets the page's title (headline) /// - public override string PageTitle { get { return Messages.IMAGE_DEFINITION_PAGE_TITLE; } } + public override string PageTitle => Messages.IMAGE_DEFINITION_PAGE_TITLE; /// /// Gets the page's label in the (left hand side) wizard progress panel /// - public override string Text { get { return Messages.IMAGE_DEFINITION_PAGE_TEXT; } } + public override string Text => Messages.IMAGE_DEFINITION_PAGE_TEXT; /// /// Gets the value by which the help files section for this page is identified /// - public override string HelpID { get { return "VMConfig"; } } + public override string HelpID => "VMConfig"; protected override bool ImplementsIsDirty() { @@ -99,14 +99,14 @@ namespace XenAdmin.Wizards.ImportWizard public bool IsWim { internal get; set; } - public string VmName { get { return m_textBoxVMName.Text; } } + public string VmName => m_textBoxVMName.Text; - public ulong CpuCount { get { return (ulong)m_upDownCpuCount.Value; } } + public ulong CpuCount => (ulong)m_upDownCpuCount.Value; - public ulong Memory { get { return (ulong)m_upDownMemory.Value; } } + public ulong Memory => (ulong)m_upDownMemory.Value; + + public ulong AdditionalSpace => m_groupBoxAddSpace.Visible && m_groupBoxAddSpace.Enabled ? (ulong)m_upDownAddSpace.Value * GB : 0; - public ulong AdditionalSpace { get { return m_groupBoxAddSpace.Enabled ? (ulong)m_upDownAddSpace.Value * GB : 0; } } - #endregion #region Private Methods diff --git a/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs b/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs index 7cf5d7da1..eb576a959 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportEulaPage.cs @@ -141,7 +141,7 @@ namespace XenAdmin.Wizards.ImportWizard #region Accessors - public EnvelopeType SelectedOvfEnvelope { internal get; set; } + public EnvelopeType SelectedOvfEnvelope { private get; set; } #endregion diff --git a/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs index ffaabb95f..9d8695ff9 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSecurityPage.cs @@ -137,7 +137,7 @@ namespace XenAdmin.Wizards.ImportWizard /// /// Package containing the selected OVF appliance. /// - public Package SelectedOvfPackage { internal get; set; } + public Package SelectedOvfPackage { private get; set; } #endregion diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs index 21612b073..e7b8f55d2 100755 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectHostPage.cs @@ -80,7 +80,7 @@ namespace XenAdmin.Wizards.ImportWizard public EnvelopeType SelectedOvfEnvelope { - internal get + private get { return _selectedOvfEnvelope; } diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs index 807903505..724463242 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectNetworkPage.cs @@ -85,7 +85,7 @@ namespace XenAdmin.Wizards.ImportWizard return false; } - public EnvelopeType SelectedOvfEnvelope { get; set; } + public EnvelopeType SelectedOvfEnvelope { private get; set; } protected override string IntroductionText => Messages.IMPORT_WIZARD_NETWORKING_INTRO; diff --git a/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs b/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs index cbd6732f5..b58f8f434 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportSelectStoragePage.cs @@ -56,7 +56,7 @@ namespace XenAdmin.Wizards.ImportWizard return true; } - public EnvelopeType SelectedOvfEnvelope { get; set; } + public EnvelopeType SelectedOvfEnvelope { private get; set; } public override StorageResourceContainer ResourceData(string sysId) { diff --git a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs index e35c6ac97..293cecef0 100644 --- a/XenAdmin/Wizards/ImportWizard/ImportWizard.cs +++ b/XenAdmin/Wizards/ImportWizard/ImportWizard.cs @@ -32,18 +32,18 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using XenAdmin.Actions; using XenAdmin.Actions.OvfActions; +using XenAdmin.Actions.VMActions; +using XenAdmin.Commands; using XenAdmin.Controls; using XenAdmin.Core; using XenAdmin.Mappings; using XenAdmin.Network; using XenAdmin.Wizards.GenericPages; using XenAPI; -using System.Linq; -using XenAdmin.Actions.VMActions; -using XenAdmin.Commands; using XenOvf; using XenOvf.Definitions; using XenOvf.Utilities; @@ -78,7 +78,10 @@ namespace XenAdmin.Wizards.ImportWizard private ImportType? m_typeOfImport; private bool m_ignoreAffinitySet; private EnvelopeType m_envelopeFromVhd; - private IXenConnection TargetConnection { get; set; } + private Package _selectedOvfPackage; + private string _selectedImagePath; + private Host _selectedAffinity; + private IXenConnection _targetConnection; #endregion public ImportWizard(IXenConnection con, IXenObject xenObject, string filename, bool ovfModeOnly = false) @@ -128,7 +131,7 @@ namespace XenAdmin.Wizards.ImportWizard m_pageXvaStorage.ImportXvaAction.EndWizard(m_pageFinish.StartVmsAutomatically, m_pageXvaNetwork.VIFs); break; case ImportType.Ovf: - new ImportApplianceAction(TargetConnection, + new ImportApplianceAction(_targetConnection, m_pageImportSource.SelectedOvfPackage, m_vmMappings, m_pageSecurity.VerifyManifest, @@ -139,7 +142,7 @@ namespace XenAdmin.Wizards.ImportWizard m_pageFinish.StartVmsAutomatically).RunAsync(); break; case ImportType.Vhd: - new ImportImageAction(TargetConnection, + new ImportImageAction(_targetConnection, m_envelopeFromVhd, Path.GetDirectoryName(m_pageImportSource.FilePath), m_vmMappings, @@ -171,17 +174,15 @@ namespace XenAdmin.Wizards.ImportWizard protected override void UpdateWizardContent(XenTabPage page) { var type = page.GetType(); - var oldTypeOfImport = m_typeOfImport; //store previous type if (type == typeof(ImportSourcePage)) { - #region ImportSourcePage - + var oldTypeOfImport = m_typeOfImport; //store previous type m_typeOfImport = m_pageImportSource.TypeOfImport; + var appliancePages = new XenTabPage[] { m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions }; var imagePages = new XenTabPage[] { m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions }; var xvaPages = new XenTabPage[] { m_pageXvaHost, m_pageXvaStorage, m_pageXvaNetwork }; - var newVmMappings = m_vmMappings; switch (m_typeOfImport) { @@ -195,29 +196,27 @@ namespace XenAdmin.Wizards.ImportWizard RemovePages(xvaPages); AddAfterPage(m_pageImportSource, appliancePages); } - var newSelectedOvfPackage = m_pageImportSource.SelectedOvfPackage; - var newSelectedOvfEnvelope = newSelectedOvfPackage.OvfEnvelope; - if (oldTypeOfImport != ImportType.Ovf - || m_pageSecurity.SelectedOvfPackage != newSelectedOvfPackage - || m_pageEula.SelectedOvfEnvelope != newSelectedOvfEnvelope - || m_pageHost.SelectedOvfEnvelope != newSelectedOvfEnvelope - || m_pageHost.VmMappings != newVmMappings - || m_pageStorage.SelectedOvfEnvelope != newSelectedOvfEnvelope - || lunPerVdiMappingPage.SelectedOvfEnvelope != newSelectedOvfEnvelope - || m_pageHost.SelectedOvfEnvelope != newSelectedOvfEnvelope) + var oldSelectedOvfPackage = _selectedOvfPackage; + _selectedOvfPackage = m_pageImportSource.SelectedOvfPackage; + + if (oldTypeOfImport != ImportType.Ovf || oldSelectedOvfPackage != _selectedOvfPackage) { - m_pageEula.SelectedOvfEnvelope = newSelectedOvfEnvelope; - m_pageSecurity.SelectedOvfPackage = newSelectedOvfPackage; - + m_pageEula.SelectedOvfEnvelope = _selectedOvfPackage.OvfEnvelope; + m_pageSecurity.SelectedOvfPackage = _selectedOvfPackage; CheckDisabledPages(m_pageEula, m_pageSecurity); //decide whether to disable these progress steps - ResetVmMappings(newSelectedOvfEnvelope); - m_pageHost.SelectedOvfEnvelope = newSelectedOvfEnvelope; + + m_vmMappings.Clear(); + string[] sysIds = OVF.FindSystemIds(_selectedOvfPackage.OvfEnvelope); + foreach (string sysId in sysIds) + m_vmMappings.Add(sysId, new VmMapping {VmNameLabel = FindVMName(_selectedOvfPackage.OvfEnvelope, sysId)}); + + m_pageHost.SelectedOvfEnvelope = _selectedOvfPackage.OvfEnvelope; m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); - m_pageHost.VmMappings = newVmMappings; - m_pageStorage.SelectedOvfEnvelope = newSelectedOvfEnvelope; - lunPerVdiMappingPage.SelectedOvfEnvelope = newSelectedOvfEnvelope; - m_pageNetwork.SelectedOvfEnvelope = newSelectedOvfEnvelope; + m_pageHost.VmMappings = m_vmMappings; + m_pageStorage.SelectedOvfEnvelope = _selectedOvfPackage.OvfEnvelope; + lunPerVdiMappingPage.SelectedOvfEnvelope = _selectedOvfPackage.OvfEnvelope; + m_pageNetwork.SelectedOvfEnvelope = _selectedOvfPackage.OvfEnvelope; NotifyNextPagesOfChange(m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions); } @@ -230,19 +229,19 @@ namespace XenAdmin.Wizards.ImportWizard RemovePages(appliancePages); RemovePages(xvaPages); AddAfterPage(m_pageImportSource, imagePages); + + //if _targetConnection=null, i.e. we haven't selected a connection yet, do not add the page + if (_targetConnection != null && BootModesControl.ShowBootModeOptions(_targetConnection)) + AddAfterPage(m_pageNetwork, m_pageBootOptions); } - var newIsWim = m_pageImportSource.IsWIM; + var oldSelectedImagePath = _selectedImagePath; + _selectedImagePath = m_pageImportSource.FilePath; - if (oldTypeOfImport != ImportType.Vhd - || m_pageVMconfig.IsWim != newIsWim - || m_pageHost.VmMappings != newVmMappings - || m_pageHost.SelectedOvfEnvelope != null) + if (oldTypeOfImport != ImportType.Vhd || oldSelectedImagePath != _selectedImagePath) { - m_pageVMconfig.IsWim = newIsWim; - m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); - m_pageHost.SelectedOvfEnvelope = null; - m_pageHost.VmMappings = newVmMappings; + m_vmMappings.Clear(); + m_pageVMconfig.IsWim = m_pageImportSource.IsWIM; NotifyNextPagesOfChange(m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions); } break; @@ -260,60 +259,107 @@ namespace XenAdmin.Wizards.ImportWizard m_pageXvaStorage.FilePath = m_pageImportSource.FilePath; break; } - - #endregion } else if (type == typeof(ImageVMConfigPage)) { - //then use it to create an ovf for the import - - var newEnvelope = OVF.CreateOvfEnvelope(m_pageVMconfig.VmName, - m_pageVMconfig.CpuCount, m_pageVMconfig.Memory, - m_pageBootOptions.BootParams, m_pageBootOptions.PlatformSettings, - m_pageImportSource.DiskCapacity, m_pageImportSource.IsWIM, m_pageVMconfig.AdditionalSpace, - m_pageImportSource.FilePath, m_pageImportSource.ImageLength, BrandManager.ProductBrand); - - if (newEnvelope != m_envelopeFromVhd) + var newMapping = new VmMapping { - ResetVmMappings(m_envelopeFromVhd); - NotifyNextPagesOfChange(m_pageHost, m_pageStorage, m_pageNetwork); + VmNameLabel = m_pageVMconfig.VmName, + CpuCount = m_pageVMconfig.CpuCount, + Capacity = m_pageImportSource.DiskCapacity + m_pageVMconfig.AdditionalSpace, + Memory = m_pageVMconfig.Memory, + BootParams = m_pageBootOptions.BootParams, + PlatformSettings = m_pageBootOptions.PlatformSettings + }; + + var oldMapping = m_vmMappings.Values.FirstOrDefault(); + if (oldMapping != null) + { + newMapping.XenRef = oldMapping.XenRef; + newMapping.TargetName = oldMapping.TargetName; + newMapping.Storage = oldMapping.Storage; + newMapping.StorageToAttach = oldMapping.StorageToAttach; + newMapping.Networks = oldMapping.Networks; } - m_envelopeFromVhd = newEnvelope; - m_pageStorage.SelectedOvfEnvelope = m_envelopeFromVhd; - lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd; - m_pageNetwork.SelectedOvfEnvelope = m_envelopeFromVhd; + if (!newMapping.Equals(oldMapping)) + { + m_envelopeFromVhd = OVF.CreateOvfEnvelope(newMapping.VmNameLabel, + newMapping.CpuCount, newMapping.Memory, + newMapping.BootParams, newMapping.PlatformSettings, + newMapping.Capacity, + m_pageImportSource.FilePath, m_pageImportSource.ImageLength, BrandManager.ProductBrand); + + m_vmMappings.Clear(); + var sysId = OVF.FindSystemIds(m_envelopeFromVhd).First(); + m_vmMappings.Add(sysId, newMapping); + + m_pageHost.VmMappings = m_vmMappings; + m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject); + + m_pageHost.SelectedOvfEnvelope = m_envelopeFromVhd; + m_pageStorage.SelectedOvfEnvelope = m_envelopeFromVhd; + lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd; + m_pageNetwork.SelectedOvfEnvelope = m_envelopeFromVhd; + + NotifyNextPagesOfChange(m_pageHost, lunPerVdiMappingPage, m_pageStorage, m_pageNetwork); + } } else if (type == typeof(ImportSelectHostPage)) { - var newConnection = m_pageHost.ChosenItem?.Connection; - var newMappings = m_pageHost.VmMappings; + var oldTargetConnection = _targetConnection; + _targetConnection = m_pageHost.ChosenItem?.Connection; + var oldVmMappings = m_vmMappings; + m_vmMappings = m_pageHost.VmMappings; - RemovePage(m_pageRbac); - ConfigureRbacPage(TargetConnection); + if (oldTargetConnection != _targetConnection) + { + RemovePage(m_pageRbac); + ConfigureRbacPage(_targetConnection); - if (m_pageStorage.VmMappings != newMappings - || m_pageNetwork.Connection != newConnection - || m_pageOptions.Connection != newConnection) + RemovePage(m_pageBootOptions); + if (m_typeOfImport == ImportType.Vhd && BootModesControl.ShowBootModeOptions(_targetConnection)) + AddAfterPage(m_pageNetwork, m_pageBootOptions); + } + + m_pageStorage.VmMappings = m_vmMappings; + m_pageStorage.Connection = _targetConnection; + m_pageNetwork.Connection = _targetConnection; + m_pageOptions.Connection = _targetConnection; + m_pageBootOptions.Connection = _targetConnection; + + if (oldTargetConnection != _targetConnection || oldVmMappings != m_vmMappings) NotifyNextPagesOfChange(m_pageStorage, m_pageNetwork, m_pageOptions); + } + else if (type == typeof(ImportBootOptionPage)) + { + var oldMapping = m_vmMappings.Values.First(); - if (m_pageBootOptions.Connection != newConnection && m_typeOfImport != oldTypeOfImport) + if (oldMapping.BootParams != m_pageBootOptions.BootParams || + oldMapping.PlatformSettings != m_pageBootOptions.PlatformSettings) { - RemovePage(m_pageBootOptions); - if (m_typeOfImport == ImportType.Vhd && BootModesControl.ShowBootModeOptions(TargetConnection)) - { - AddAfterPage(m_pageNetwork, m_pageBootOptions); - } + string systemId = null; + if (m_envelopeFromVhd.Item is VirtualSystem_Type vs) + systemId = vs.id; + else if (m_envelopeFromVhd.Item is VirtualSystemCollection_Type vsc) + systemId = vsc.Content.FirstOrDefault()?.id; + + if (oldMapping.BootParams != m_pageBootOptions.BootParams) + { + m_envelopeFromVhd = OVF.UpdateBootParams(m_envelopeFromVhd, systemId, m_pageBootOptions.BootParams); + m_vmMappings.Values.First().BootParams = m_pageBootOptions.BootParams; + } + + if (oldMapping.PlatformSettings != m_pageBootOptions.PlatformSettings) + { + m_envelopeFromVhd = OVF.UpdatePlatform(m_envelopeFromVhd, systemId, m_pageBootOptions.PlatformSettings); + m_vmMappings.Values.First().PlatformSettings = m_pageBootOptions.PlatformSettings; + } } - m_vmMappings = newMappings; - TargetConnection = newConnection; - - m_pageStorage.VmMappings = m_vmMappings; - m_pageStorage.Connection = TargetConnection; - m_pageNetwork.Connection = TargetConnection; - m_pageOptions.Connection = TargetConnection; - m_pageBootOptions.Connection = TargetConnection; + m_pageStorage.SelectedOvfEnvelope = m_envelopeFromVhd; + lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd; + m_pageNetwork.SelectedOvfEnvelope = m_envelopeFromVhd; } else if (type == typeof(ImportSelectStoragePage)) { @@ -339,31 +385,31 @@ namespace XenAdmin.Wizards.ImportWizard } else if (type == typeof(GlobalSelectHost)) { - var newConnection = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection; - var newStorageTargetHost = m_ignoreAffinitySet ? null : m_pageXvaHost.SelectedHost; - var newNetworkSelectedHost = m_pageXvaHost.SelectedHost; + var oldSelectedAffinity = _selectedAffinity; + _selectedAffinity = m_pageXvaHost.SelectedHost; + var oldTargetConnection = _targetConnection; + _targetConnection = _selectedAffinity == null ? m_pageXvaHost.SelectedConnection : _selectedAffinity.Connection; - RemovePage(m_pageRbac); - ConfigureRbacPage(newConnection); + if (oldTargetConnection != _targetConnection) + { + RemovePage(m_pageRbac); + ConfigureRbacPage(_targetConnection); + } - if (m_pageXvaStorage.MTargetConnection != newConnection - || m_pageXvaNetwork.MSelectedConnection != newConnection - || !m_pageXvaNetwork.MSelectedAffinity.Equals(newNetworkSelectedHost) - || !m_pageXvaStorage.MTargetHost.Equals(newStorageTargetHost) - ) + m_pageXvaStorage.TargetConnection = _targetConnection; + m_pageXvaStorage.TargetHost = m_ignoreAffinitySet ? null : _selectedAffinity; + + m_pageXvaNetwork.SelectedConnection = _targetConnection; + m_pageXvaNetwork.SelectedAffinity = _selectedAffinity; + + if (oldTargetConnection != _targetConnection || + oldSelectedAffinity != null && _selectedAffinity != null && oldSelectedAffinity.opaque_ref != _selectedAffinity.opaque_ref) NotifyNextPagesOfChange(m_pageXvaStorage, m_pageXvaNetwork); - - m_pageXvaStorage.MTargetConnection = newConnection; - m_pageXvaStorage.MTargetHost = newStorageTargetHost; - - m_pageXvaNetwork.MSelectedConnection = newConnection; - m_pageXvaNetwork.MSelectedAffinity = m_pageXvaHost.SelectedHost; - } else if (type == typeof(StoragePickerPage)) { m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; - m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); + m_pageXvaNetwork.VM = m_pageXvaStorage.ImportedVm; NotifyNextPagesOfChange(m_pageXvaNetwork); } @@ -567,7 +613,7 @@ namespace XenAdmin.Wizards.ImportWizard temp.Add(new Tuple(Messages.FINISH_PAGE_VMNAME, m_pageVMconfig.VmName)); temp.Add(new Tuple(Messages.FINISH_PAGE_CPUCOUNT, m_pageVMconfig.CpuCount.ToString())); temp.Add(new Tuple(Messages.FINISH_PAGE_MEMORY, string.Format(Messages.VAL_MB, m_pageVMconfig.Memory))); - if (Helpers.NaplesOrGreater(TargetConnection)) + if (Helpers.NaplesOrGreater(_targetConnection)) temp.Add(new Tuple(Messages.BOOT_MODE, m_pageBootOptions.SelectedBootMode.StringOf())); if (m_pageImportSource.IsWIM) @@ -609,23 +655,6 @@ namespace XenAdmin.Wizards.ImportWizard return temp; } - private void ResetVmMappings(EnvelopeType ovfEnvelope) - { - string[] sysIds = OVF.FindSystemIds(ovfEnvelope); - m_vmMappings.Clear(); - - foreach (string sysId in sysIds) - { - var vmMap = new VmMapping - { - VmNameLabel = (m_typeOfImport == ImportType.Ovf) - ? FindVMName(ovfEnvelope, sysId) - : m_pageVMconfig.VmName //it should only iterate once - }; - m_vmMappings.Add(sysId, vmMap); - } - } - private bool IsGUID(string expression) { if (expression != null) @@ -709,15 +738,15 @@ namespace XenAdmin.Wizards.ImportWizard private void m_pageXvaStorage_ImportVmCompleted() { Program.Invoke(this, () => - { - if (CurrentStepTabPage.GetType() == typeof(StoragePickerPage)) - { - m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; - m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm); - NotifyNextPagesOfChange(m_pageXvaNetwork); - NextStep(); - } - }); + { + if (CurrentStepTabPage.GetType() == typeof(StoragePickerPage)) + { + m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template; + m_pageXvaNetwork.VM = m_pageXvaStorage.ImportedVm; + NotifyNextPagesOfChange(m_pageXvaNetwork); + NextStep(); + } + }); } private void ShowXenAppXenDesktopWarning(IXenConnection connection) diff --git a/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs b/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs index f8c570d74..db036272f 100644 --- a/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs +++ b/XenAdmin/Wizards/ImportWizard/LunPerVdiImportPage.cs @@ -99,7 +99,7 @@ namespace XenAdmin.Wizards.ImportWizard } } - public EnvelopeType SelectedOvfEnvelope { get; set; } + public EnvelopeType SelectedOvfEnvelope { private get; set; } private StorageResourceContainer ResourceData(string sysId) { diff --git a/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs b/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs index 6b36caeba..c3a90ed3a 100644 --- a/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs +++ b/XenAdmin/Wizards/ImportWizard/NetworkPickerPage.cs @@ -49,9 +49,6 @@ namespace XenAdmin.Wizards.ImportWizard #region Private fields private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - internal IXenConnection MSelectedConnection { get; set; } - internal Host MSelectedAffinity { get; set; } - private VM m_vm; private bool m_buttonNextEnabled; #endregion @@ -108,6 +105,15 @@ namespace XenAdmin.Wizards.ImportWizard #region Accessors + /// + /// Should be set before the Affinity is set. + /// + internal IXenConnection SelectedConnection { get; set; } + + internal Host SelectedAffinity { get; set; } + + internal VM VM { get; set; } + public List VIFs { get @@ -136,12 +142,6 @@ namespace XenAdmin.Wizards.ImportWizard #endregion - - public void SetVm(VM vm) - { - m_vm = vm; - } - #region Private methods private void UpdateControlsEnabledState(bool enabled) @@ -155,7 +155,7 @@ namespace XenAdmin.Wizards.ImportWizard { NetworkNetworkColumn.Items.Clear(); - var networks = MSelectedConnection.Cache.Networks.Where(ShowNetwork); + var networks = SelectedConnection.Cache.Networks.Where(ShowNetwork); foreach (XenAPI.Network network in networks) { @@ -174,18 +174,18 @@ namespace XenAdmin.Wizards.ImportWizard m_networkGridView.SuspendLayout(); m_networkGridView.Rows.Clear(); - if (m_vm.is_a_template && m_vm.VIFs.Count < 1) + if (VM.is_a_template && VM.VIFs.Count < 1) { // We need to automatically generate VIFs for Networks marked AutoPlug=true - var networks = MSelectedConnection.Cache.Networks; + var networks = SelectedConnection.Cache.Networks; foreach (XenAPI.Network network in networks) { - if (m_networkGridView.Rows.Count < m_vm.MaxVIFsAllowed() && ShowNetwork(network) && network.GetAutoPlug()) + if (m_networkGridView.Rows.Count < VM.MaxVIFsAllowed() && ShowNetwork(network) && network.GetAutoPlug()) { AddVIFRow(new VIF { - Connection = MSelectedConnection, + Connection = SelectedConnection, device = m_networkGridView.Rows.Count.ToString(), network = new XenRef(network.opaque_ref), MAC = Messages.MAC_AUTOGENERATE @@ -193,16 +193,16 @@ namespace XenAdmin.Wizards.ImportWizard } } } - else if (m_vm.is_a_template) + else if (VM.is_a_template) { // We need to create off the _vmTemplate - var vifs = MSelectedConnection.ResolveAll(m_vm.VIFs); + var vifs = SelectedConnection.ResolveAll(VM.VIFs); foreach (VIF vif in vifs) { AddVIFRow(new VIF { - Connection = MSelectedConnection, + Connection = SelectedConnection, device = vif.device, network = vif.network, MAC = Messages.MAC_AUTOGENERATE @@ -212,7 +212,7 @@ namespace XenAdmin.Wizards.ImportWizard else { //We need to recreate off vm - var vifs = MSelectedConnection.ResolveAll(m_vm.VIFs); + var vifs = SelectedConnection.ResolveAll(VM.VIFs); foreach (VIF vif in vifs) AddVIFRow(vif); } @@ -228,7 +228,7 @@ namespace XenAdmin.Wizards.ImportWizard private XenAPI.Network GetDefaultNetwork() { - foreach (XenAPI.Network network in MSelectedConnection.Cache.Networks) + foreach (XenAPI.Network network in SelectedConnection.Cache.Networks) if (ShowNetwork(network)) return network; @@ -249,13 +249,13 @@ namespace XenAdmin.Wizards.ImportWizard if (network.IsMember()) return false; - if (MSelectedAffinity != null && !MSelectedAffinity.CanSeeNetwork(network)) + if (SelectedAffinity != null && !SelectedAffinity.CanSeeNetwork(network)) return false; - if (MSelectedAffinity == null && !network.AllHostsCanSeeNetwork()) + if (SelectedAffinity == null && !network.AllHostsCanSeeNetwork()) return false; - if (network.IsSriov() && !m_vm.HasSriovRecommendation()) + if (network.IsSriov() && !VM.HasSriovRecommendation()) return false; return true; @@ -264,7 +264,7 @@ namespace XenAdmin.Wizards.ImportWizard private void AddVIFRow(VIF vif) { var row = new VifRow(vif); - XenAPI.Network network = MSelectedConnection.Resolve(vif.network); + XenAPI.Network network = SelectedConnection.Resolve(vif.network); bool isGuestInstallerNetwork = network != null && network.IsGuestInstallerNetwork(); ToStringWrapper comboBoxEntry = FindComboBoxEntryForNetwork(network); @@ -332,7 +332,7 @@ namespace XenAdmin.Wizards.ImportWizard private void m_buttonAddNetwork_Click(object sender, EventArgs e) { - if (m_networkGridView.Rows.Count >= m_vm.MaxVIFsAllowed()) + if (m_networkGridView.Rows.Count >= VM.MaxVIFsAllowed()) { using (var dlg = new ErrorDialog(FriendlyErrorNames.VIFS_MAX_ALLOWED) {WindowTitle = FriendlyErrorNames.VIFS_MAX_ALLOWED_TITLE}) @@ -342,7 +342,7 @@ namespace XenAdmin.Wizards.ImportWizard return; } - VIF vif = new VIF {Connection = MSelectedConnection}; + VIF vif = new VIF {Connection = SelectedConnection}; int i = 0; while (true) diff --git a/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs b/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs index ae57f26c6..615036d25 100644 --- a/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs +++ b/XenAdmin/Wizards/ImportWizard/StoragePickerPage.cs @@ -45,9 +45,6 @@ namespace XenAdmin.Wizards.ImportWizard public partial class StoragePickerPage : XenTabPage { #region Private fields - - internal Host MTargetHost { set; get; } - internal IXenConnection MTargetConnection { get; set; } private volatile Task m_importTask; private bool m_alreadyFoundVM; private ActionProgressDialog m_actionDialog; @@ -99,8 +96,8 @@ namespace XenAdmin.Wizards.ImportWizard SetButtonNextEnabled(false); m_buttonPreviousEnabled = false; OnPageUpdated(); - ImportXvaAction = new ImportVmAction(MTargetHost == null ? MTargetConnection : MTargetHost.Connection, - MTargetHost, FilePath, SR, + ImportXvaAction = new ImportVmAction(TargetHost == null ? TargetConnection : TargetHost.Connection, + TargetHost, FilePath, SR, VMOperationCommand.WarningDialogHAInvalidConfig, VMOperationCommand.StartDiagnosisForm); ImportXvaAction.Completed += m_importXvaAction_Completed; @@ -120,7 +117,7 @@ namespace XenAdmin.Wizards.ImportWizard public override void PopulatePage() { SetButtonNextEnabled(false); - m_srPicker.PopulateAsync(SrPicker.SRPickerType.VM, MTargetConnection, MTargetHost, null, null); + m_srPicker.PopulateAsync(SrPicker.SRPickerType.VM, TargetConnection, TargetHost, null, null); IsDirty = true; } @@ -138,6 +135,10 @@ namespace XenAdmin.Wizards.ImportWizard #region Accessors + internal IXenConnection TargetConnection { get; set; } + + internal Host TargetHost { get; set; } + public ImportVmAction ImportXvaAction { get; private set; } public string FilePath { private get; set; } @@ -184,12 +185,12 @@ namespace XenAdmin.Wizards.ImportWizard while (ImportXvaAction.RelatedTask == null) Thread.Sleep(100); - while ((m_importTask = MTargetConnection.Resolve(ImportXvaAction.RelatedTask)) == null) + while ((m_importTask = TargetConnection.Resolve(ImportXvaAction.RelatedTask)) == null) Thread.Sleep(100); // We register a XenObjectsUpdated event handler where we check that the import task has the object creation phase marked as "complete"; // Once the object creation is complete, we look for the vm; When we found the vm we unregister this event handler; - MTargetConnection.XenObjectsUpdated += targetConnection_XenObjectsUpdated; + TargetConnection.XenObjectsUpdated += targetConnection_XenObjectsUpdated; Program.Invoke(this, CheckTask); } @@ -221,11 +222,11 @@ namespace XenAdmin.Wizards.ImportWizard { // Should never get here (as we unregister XenObjectsUpdated event handler after we find the vm) but just in case, // unregister XenObjectsUpdated event handler - MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + TargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; return; } - foreach (VM vm in MTargetConnection.Cache.VMs) + foreach (VM vm in TargetConnection.Cache.VMs) { if (!vm.other_config.ContainsKey(ImportVmAction.IMPORT_TASK)) continue; @@ -238,7 +239,7 @@ namespace XenAdmin.Wizards.ImportWizard ImportedVm = vm; // We found the VM, unregister XenObjectsUpdated event handler - MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + TargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; // And close the dialog, flick to next page. m_actionDialog.Close(); @@ -267,7 +268,7 @@ namespace XenAdmin.Wizards.ImportWizard if (!(ImportXvaAction.Succeeded) || ImportXvaAction.Cancelled) { // task failed or has been cancelled, unregister XenObjectsUpdated event handler - MTargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; + TargetConnection.XenObjectsUpdated -= targetConnection_XenObjectsUpdated; // Give the user a chance to correct any errors m_actionDialog = null; diff --git a/XenModel/Mappings/VmMapping.cs b/XenModel/Mappings/VmMapping.cs index a7c85a665..0696f002e 100644 --- a/XenModel/Mappings/VmMapping.cs +++ b/XenModel/Mappings/VmMapping.cs @@ -44,6 +44,11 @@ namespace XenAdmin.Mappings } public string VmNameLabel { get; set; } + public ulong Capacity { get; set; } + public ulong CpuCount { get; set; } + public ulong Memory { get; set; } + public string BootParams { get; set; } + public string PlatformSettings { get; set; } /// /// OpaqueRef of the target pool or host @@ -66,5 +71,26 @@ namespace XenAdmin.Mappings /// Keyed on the id in the ovf file /// public Dictionary Networks { get; set; } - } + + public override bool Equals(object obj) + { + return obj is VmMapping other && + VmNameLabel == other.VmNameLabel && + Capacity == other.Capacity && + CpuCount == other.CpuCount && + Memory == other.Memory && + BootParams == other.BootParams && + PlatformSettings == other.PlatformSettings && + XenRef == other.XenRef && + TargetName == other.TargetName && + Storage == other.Storage && + StorageToAttach == other.StorageToAttach && + Networks == other.Networks; + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + } } diff --git a/XenOvfApi/OVF.cs b/XenOvfApi/OVF.cs index 3cd2c657b..310dd4fbf 100644 --- a/XenOvfApi/OVF.cs +++ b/XenOvfApi/OVF.cs @@ -1388,7 +1388,7 @@ namespace XenOvf #region CREATEs public static EnvelopeType CreateOvfEnvelope(string vmName, ulong cpuCount, ulong memory, - string bootParams, string platformSettings, ulong diskCapacity, bool isWim, ulong additionalSpace, + string bootParams, string platformSettings, ulong capacity, string diskPath, ulong imageLength, string productBrand) { EnvelopeType env = CreateEnvelope(vmName); @@ -1415,10 +1415,6 @@ namespace XenOvf AddNetwork(env, systemID, netId, string.Format(Messages.NETWORK_NAME, 0), Messages.OVF_NET_DESCRIPTION, null); string diskId = Guid.NewGuid().ToString(); - ulong capacity = diskCapacity; - - if (isWim) - capacity += additionalSpace; AddDisk(env, systemID, diskId, diskPath, true, Messages.OVF_DISK_CAPTION, Messages.OVF_CREATED, imageLength, capacity); @@ -1426,6 +1422,45 @@ namespace XenOvf return env; } + public static EnvelopeType UpdateBootParams(EnvelopeType env, string systemID, string bootParams) + { + return UpdateOtherSystemSettingsData(env, systemID, "HVM_boot_params", "order=dc;" + bootParams); + } + + public static EnvelopeType UpdatePlatform(EnvelopeType env, string systemID, string platformSettings) + { + return UpdateOtherSystemSettingsData(env, systemID, "platform", "nx=true;acpi=true;apic=true;pae=true;stdvga=0;" + platformSettings); + } + + private static EnvelopeType UpdateOtherSystemSettingsData(EnvelopeType env, string systemID, string setting, string value) + { + VirtualHardwareSection_Type[] vhsArray = FindVirtualHardwareSection(env, systemID); + VirtualHardwareSection_Type foundVhs = null; + + foreach (VirtualHardwareSection_Type vhs in vhsArray) + { + if (vhs.System?.VirtualSystemType == null) + continue; + + var vst = vhs.System.VirtualSystemType.Value; + if (string.IsNullOrEmpty(vst) || !vst.ToLower().StartsWith("xen") && !vst.ToLower().StartsWith("hvm")) + continue; + + foundVhs = vhs; + break; + } + + if (foundVhs == null) + return env; + + var config = foundVhs.VirtualSystemOtherConfigurationData.FirstOrDefault(d => d.Name == setting); + if (config == null) + return env; + + config.Value = new cimString(value); + return env; + } + public EnvelopeType Create(DiskInfo[] vhdExports, string pathToOvf, string ovfName) { return Create(vhdExports, pathToOvf, ovfName, LANGUAGE); From eef4e5f9951875feec2dae02521bda048cdad85f Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 25 Nov 2021 20:48:54 +0000 Subject: [PATCH 61/62] CP-38427 issue 1: Do not allow enabling TLS verification during RPU. Signed-off-by: Konstantina Chremmou --- XenAdmin/Commands/EnableTlsVerificationCommand.cs | 6 +++++- XenModel/Messages.Designer.cs | 9 +++++++++ XenModel/Messages.resx | 3 +++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/XenAdmin/Commands/EnableTlsVerificationCommand.cs b/XenAdmin/Commands/EnableTlsVerificationCommand.cs index 895d3d4da..31999d7ef 100644 --- a/XenAdmin/Commands/EnableTlsVerificationCommand.cs +++ b/XenAdmin/Commands/EnableTlsVerificationCommand.cs @@ -111,7 +111,8 @@ namespace XenAdmin.Commands !pool.current_operations.Values.Contains(pool_allowed_operations.ha_enable) && !pool.current_operations.Values.Contains(pool_allowed_operations.ha_disable) && !pool.current_operations.Values.Contains(pool_allowed_operations.cluster_create) && - !pool.current_operations.Values.Contains(pool_allowed_operations.designate_new_master); + !pool.current_operations.Values.Contains(pool_allowed_operations.designate_new_master) && + !pool.RollingUpgrade(); } protected override string GetCantRunReasonCore(IXenObject item) @@ -134,6 +135,9 @@ namespace XenAdmin.Commands if (pool.current_operations.Values.Contains(pool_allowed_operations.designate_new_master)) return Messages.ENABLE_TLS_VERIFICATION_NEW_COORDINATOR; + + if (pool.RollingUpgrade()) + return Messages.ENABLE_TLS_VERIFICATION_RPU; } return base.GetCantRunReasonCore(item); diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index c156d8b13..6ff4ed3c9 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -15294,6 +15294,15 @@ namespace XenAdmin { } } + /// + /// Looks up a localized string similar to You cannot enable certificate verification while a rolling pool upgrade is in progress.. + /// + public static string ENABLE_TLS_VERIFICATION_RPU { + get { + return ResourceManager.GetString("ENABLE_TLS_VERIFICATION_RPU", resourceCulture); + } + } + /// /// Looks up a localized string similar to Res&ume. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 66bedeef7..a6b64de83 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -5382,6 +5382,9 @@ Would you like to eject these ISOs before continuing? {1} + + You cannot enable certificate verification while a rolling pool upgrade is in progress. + Res&ume From e9fa5674c379dc5b3c2316ed0b4f32e2ebee6fa2 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 1 Dec 2021 15:07:11 +0000 Subject: [PATCH 62/62] CA-339273: Some corrections and minor refactoring. Signed-off-by: Konstantina Chremmou --- XenAdmin/Core/ActionBaseExtensions.cs | 5 +++- .../Actions/VDI/MigrateVirtualDiskAction.cs | 1 - XenModel/Actions/VDI/MoveVirtualDiskAction.cs | 1 - XenModel/Actions/VM/ImportVmAction.cs | 8 ++--- XenModel/Actions/VM/VMCloneAction.cs | 17 +++++------ XenModel/Actions/VM/VMCopyAction.cs | 1 - .../Actions/VM/VMCrossPoolMigrateAction.cs | 1 - XenModel/Actions/VM/VMMigrateAction.cs | 16 ++++------ XenModel/Actions/VM/VMMoveAction.cs | 14 ++++++--- XenModel/Messages.Designer.cs | 29 ++++++++++++------- XenModel/Messages.resx | 11 ++++--- 11 files changed, 55 insertions(+), 49 deletions(-) diff --git a/XenAdmin/Core/ActionBaseExtensions.cs b/XenAdmin/Core/ActionBaseExtensions.cs index c76ae8d86..1a1a263c0 100644 --- a/XenAdmin/Core/ActionBaseExtensions.cs +++ b/XenAdmin/Core/ActionBaseExtensions.cs @@ -59,7 +59,10 @@ namespace XenAdmin.Core internal static string GetDetails(this ActionBase action) { var sb = new StringBuilder(GetTitle(action)); - sb.Append("\n").Append(GetDescription(action)); + + var description = GetDescription(action); + if (!string.IsNullOrEmpty(description)) + sb.Append("\n").Append(description); string timeString = GetTimeElapsed(action); if (!string.IsNullOrEmpty(timeString)) diff --git a/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs b/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs index 7f410afce..3ef3d27ca 100644 --- a/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs +++ b/XenModel/Actions/VDI/MigrateVirtualDiskAction.cs @@ -52,7 +52,6 @@ namespace XenAdmin.Actions protected override void Run() { - Description = Messages.MOVING; RelatedTask = VDI.async_pool_migrate(Session, vdi.opaque_ref, SR.opaque_ref, new Dictionary()); PollToCompletion(); Description = Messages.MOVED; diff --git a/XenModel/Actions/VDI/MoveVirtualDiskAction.cs b/XenModel/Actions/VDI/MoveVirtualDiskAction.cs index 2659b43e1..0de606612 100644 --- a/XenModel/Actions/VDI/MoveVirtualDiskAction.cs +++ b/XenModel/Actions/VDI/MoveVirtualDiskAction.cs @@ -61,7 +61,6 @@ namespace XenAdmin.Actions protected override void Run() { - Description = Messages.MOVING; PercentComplete = 10; log.DebugFormat("Moving VDI '{0}'", Helpers.GetName(vdi)); RelatedTask = VDI.async_copy(Session, vdi.opaque_ref, SR.opaque_ref); diff --git a/XenModel/Actions/VM/ImportVmAction.cs b/XenModel/Actions/VM/ImportVmAction.cs index d5f728af1..d626efe1e 100644 --- a/XenModel/Actions/VM/ImportVmAction.cs +++ b/XenModel/Actions/VM/ImportVmAction.cs @@ -72,7 +72,7 @@ namespace XenAdmin.Actions public ImportVmAction(IXenConnection connection, Host affinity, string filename, SR sr, Action warningDelegate, Action failureDiagnosisDelegate) - : base(connection, GetTitle(filename, connection, affinity)) + : base(connection, "") { Description = Messages.IMPORTVM_PREP; Pool = Helpers.GetPoolOfOne(connection); @@ -95,12 +95,8 @@ namespace XenAdmin.Actions ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList); #endregion - } - private static string GetTitle(string filename, IXenConnection connection, Host affinity) - { - var toHost = affinity ?? connection.Resolve(Helpers.GetPoolOfOne(connection).master); - return string.Format(Messages.IMPORTVM_TITLE, filename, toHost.NameWithLocation()); + Title = string.Format(Messages.IMPORTVM_TITLE, filename, Host.NameWithLocation()); } protected override void Run() diff --git a/XenModel/Actions/VM/VMCloneAction.cs b/XenModel/Actions/VM/VMCloneAction.cs index 10693eb42..b10ef5b5e 100644 --- a/XenModel/Actions/VM/VMCloneAction.cs +++ b/XenModel/Actions/VM/VMCloneAction.cs @@ -37,9 +37,9 @@ namespace XenAdmin.Actions.VMActions { public class VMCloneAction : AsyncAction { + private readonly string _cloneName; + private readonly string _cloneDescription; - protected string _cloneName; - protected string _cloneDescription; public VMCloneAction(VM vm, string name, string description) : base(vm.Connection, string.Format(Messages.CREATEVM_CLONE, name, vm.NameWithLocation())) { @@ -58,17 +58,14 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - Description = Messages.ACTION_TEMPLATE_CLONING; RelatedTask = VM.async_clone(Session, VM.opaque_ref, _cloneName); PollToCompletion(); - { - VM created = Connection.WaitForCache(new XenRef(Result)); - VM.set_name_description(Session, created.opaque_ref, _cloneDescription); - Result = created.opaque_ref; - } + + VM created = Connection.WaitForCache(new XenRef(Result)); + VM.set_name_description(Session, created.opaque_ref, _cloneDescription); + Result = created.opaque_ref; + Description = Messages.ACTION_TEMPLATE_CLONED; } } - - } diff --git a/XenModel/Actions/VM/VMCopyAction.cs b/XenModel/Actions/VM/VMCopyAction.cs index 6d1d210c1..f966a6f66 100644 --- a/XenModel/Actions/VM/VMCopyAction.cs +++ b/XenModel/Actions/VM/VMCopyAction.cs @@ -65,7 +65,6 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - Description = Messages.ACTION_VM_COPYING; RelatedTask = VM.async_copy(Session, VM.opaque_ref, _nameLabel, SR.opaque_ref); try { diff --git a/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs b/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs index ed57a6fb8..a8cdeea40 100644 --- a/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs +++ b/XenModel/Actions/VM/VMCrossPoolMigrateAction.cs @@ -93,7 +93,6 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - Description = copy ? Messages.ACTION_VM_COPYING: Messages.ACTION_VM_MIGRATING; try { PercentComplete = 0; diff --git a/XenModel/Actions/VM/VMMigrateAction.cs b/XenModel/Actions/VM/VMMigrateAction.cs index f39d29181..47209992e 100644 --- a/XenModel/Actions/VM/VMMigrateAction.cs +++ b/XenModel/Actions/VM/VMMigrateAction.cs @@ -40,25 +40,21 @@ namespace XenAdmin.Actions.VMActions { public VMMigrateAction(VM vm, Host destinationHost) - : base(vm.Connection, GetTitle(vm, destinationHost)) + : base(vm.Connection, "") { VM = vm; Host = destinationHost; Pool = Helpers.GetPool(vm.Connection); - } - private static string GetTitle(VM vm, Host toHost) - { - Host residentOn = vm.Connection.Resolve(vm.resident_on); - - return residentOn == null - ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.NameWithLocation(), toHost.NameWithLocation()) - : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), residentOn.NameWithLocation(), toHost.NameWithLocation()); + var residentOn = vm.Connection.Resolve(vm.resident_on); + + Title = residentOn == null + ? string.Format(Messages.ACTION_VM_MIGRATING_NON_RESIDENT, vm.NameWithLocation(), Host.NameWithLocation()) + : string.Format(Messages.ACTION_VM_MIGRATING_RESIDENT, vm.Name(), residentOn.NameWithLocation(), Host.NameWithLocation()); } protected override void Run() { - Description = Messages.ACTION_VM_MIGRATING; RelatedTask = VM.async_live_migrate(Session, VM.opaque_ref, Host.opaque_ref); try { diff --git a/XenModel/Actions/VM/VMMoveAction.cs b/XenModel/Actions/VM/VMMoveAction.cs index 8598c520b..7f77775e0 100644 --- a/XenModel/Actions/VM/VMMoveAction.cs +++ b/XenModel/Actions/VM/VMMoveAction.cs @@ -45,7 +45,7 @@ namespace XenAdmin.Actions.VMActions private Dictionary _storageMapping; public VMMoveAction(VM vm, Dictionary storageMapping, Host host) - : base(vm.Connection, string.Format(Messages.ACTION_VM_MOVING, vm.Name(), vm.Connection.Name, host.Name())) + : base(vm.Connection, "") { VM = vm; Host = host; @@ -57,6 +57,14 @@ namespace XenAdmin.Actions.VMActions SR = _storageMapping.Values.FirstOrDefault(); PopulateApiMethodsToRoleCheck(); + + var sourceHost = vm.Home(); + if (sourceHost != null && !sourceHost.Equals(host)) + Title = string.Format(Messages.ACTION_VM_MOVING_HOST, vm.Name(), sourceHost, host.Name()); + else if (storageMapping.Count == 1) + Title = string.Format(Messages.ACTION_VM_MOVING_SR, vm.Name(), storageMapping.Values.ElementAt(0).Name()); + else + Title = string.Format(Messages.ACTION_VM_MOVING, vm.Name()); } public VMMoveAction(VM vm, SR sr, Host host) @@ -92,8 +100,6 @@ namespace XenAdmin.Actions.VMActions protected override void Run() { - Description = Messages.MOVING; - // move the progress bar above 0, it's more reassuring to see than a blank bar as we copy the first disk PercentComplete += 10; int halfstep = 90 / (VM.VBDs.Count * 2); @@ -156,7 +162,7 @@ namespace XenAdmin.Actions.VMActions PercentComplete += halfstep; } - Description = Messages.MOVING; + Description = string.Empty; if (SR != null) VM.set_suspend_SR(Session, VM.opaque_ref, SR.opaque_ref); diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 31e99b5db..01e47ce25 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -2616,15 +2616,6 @@ namespace XenAdmin { } } - /// - /// Looks up a localized string similar to Duplicating. - /// - public static string ACTION_TEMPLATE_CLONING { - get { - return ResourceManager.GetString("ACTION_TEMPLATE_CLONING", resourceCulture); - } - } - /// /// Looks up a localized string similar to Restart toolstack on '{0}'. /// @@ -3175,7 +3166,7 @@ namespace XenAdmin { } /// - /// Looks up a localized string similar to Moving VM '{0}' from Host '{1}' to Host '{2}'. + /// Looks up a localized string similar to Moving VM '{0}' to new storage. /// public static string ACTION_VM_MOVING { get { @@ -3183,6 +3174,24 @@ namespace XenAdmin { } } + /// + /// Looks up a localized string similar to Moving VM '{0}' from server '{1}' to server '{2}'. + /// + public static string ACTION_VM_MOVING_HOST { + get { + return ResourceManager.GetString("ACTION_VM_MOVING_HOST", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Moving VM '{0}' to SR '{1}'. + /// + public static string ACTION_VM_MOVING_SR { + get { + return ResourceManager.GetString("ACTION_VM_MOVING_SR", resourceCulture); + } + } + /// /// Looks up a localized string similar to Failed to finalize moving VM '{0}' to new storage. Please see logs for details.. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 95ae0b5dd..ea2ffc5bd 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -969,9 +969,6 @@ Copy of {0} - - Duplicating - Toolstack restarted. @@ -1177,7 +1174,13 @@ Migrating VM '{0}' - Moving VM '{0}' from Host '{1}' to Host '{2}' + Moving VM '{0}' to new storage + + + Moving VM '{0}' from server '{1}' to server '{2}' + + + Moving VM '{0}' to SR '{1}' Failed to finalize moving VM '{0}' to new storage. Please see logs for details.