From 1601498bd7370759bcc1e008ea148655565594ee Mon Sep 17 00:00:00 2001 From: Donal Lafferty Date: Wed, 30 Oct 2013 10:23:40 +0530 Subject: [PATCH] Changes for switching all wmi calls to V2 namespace. V1 namespace is deprecated so it is better to be on v2 namespace. --- .../HypervResource/HypervResource.csproj | 206 +- .../HypervResourceController.cs | 2965 ++++++------ .../HypervResource/IWmiCallsV2.cs | 72 +- .../ServerResource/HypervResource/WmiCalls.cs | 1419 ------ .../HypervResource/WmiCallsV2.cs | 1534 ++++++- .../HypervResourceController1Test.cs | 641 ++- .../HypervResourceControllerTest.cs | 2296 +++++----- .../ServerResource.Tests.csproj | 260 +- ...ROOT.virtualization.Msvm_ComputerSystem.cs | 1298 ------ .../ROOT.virtualization.Msvm_ConcreteJob.cs | 1665 ------- .../ROOT.virtualization.Msvm_SwitchPort.cs | 1708 ------- .../ROOT.virtualization.Msvm_VLANEndpoint.cs | 1390 ------ ...ion.Msvm_VirtualSwitchManagementService.cs | 1379 ------ ...ion.Msvm_VirtualSystemGlobalSettingData.cs | 1513 ------ ...ion.Msvm_VirtualSystemManagementService.cs | 1731 ------- ...rtualSystemManagementServiceSettingData.cs | 731 --- ...alization.Msvm_VirtualSystemSettingData.cs | 1206 ----- .../ROOT.virtualization.Msvm_VmLANEndpoint.cs | 1342 ------ ...T.virtualization.v2.Msvm_ComputerSystem.cs | 13 +- ....Msvm_EthernetPortAllocationSettingData.cs | 1147 +++++ ...tualization.v2.Msvm_EthernetSwitchPort.cs} | 4062 ++++++++-------- ...Msvm_EthernetSwitchPortVlanSettingData.cs} | 1890 ++++---- ...alization.v2.Msvm_ExternalEthernetPort.cs} | 4066 +++++++++-------- ...ization.v2.Msvm_ImageManagementService.cs} | 2909 ++++++------ ...ualization.v2.Msvm_KvpExchangeComponent.cs | 5 +- ...OOT.virtualization.v2.Msvm_LANEndpoint.cs} | 2747 +++++------ ...rtualization.v2.Msvm_MemorySettingData.cs} | 2229 ++++----- ...alization.v2.Msvm_ProcessorSettingData.cs} | 2307 +++++----- ....v2.Msvm_ResourceAllocationSettingData.cs} | 1969 ++++---- ...on.v2.Msvm_StorageAllocationSettingData.cs | 1197 +++++ ...tualization.v2.Msvm_SummaryInformation.cs} | 2704 ++++++----- ....Msvm_SyntheticEthernetPortSettingData.cs} | 2074 +++++---- ...lization.v2.Msvm_VirtualEthernetSwitch.cs} | 2674 +++++------ ...VirtualEthernetSwitchManagementService.cs} | 3108 ++++++------- ...tion.v2.Msvm_VirtualHardDiskSettingData.cs | 1034 +++++ ....v2.Msvm_VirtualSystemManagementService.cs | 143 +- ...rtualSystemManagementServiceSettingData.cs | 1583 +++---- .../WmiWrappers/WmiWrappers.csproj | 368 +- 38 files changed, 25955 insertions(+), 35630 deletions(-) delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCalls.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ComputerSystem.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ConcreteJob.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchPort.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpoint.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitchManagementService.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemGlobalSettingData.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementService.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementServiceSettingData.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemSettingData.cs delete mode 100644 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VmLANEndpoint.cs create mode 100755 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_SyntheticEthernetPort.cs => ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs} (83%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_VLANEndpointSettingData.cs => ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs} (69%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_ExternalEthernetPort.cs => ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs} (90%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_ImageManagementService.cs => ROOT.virtualization.v2.Msvm_ImageManagementService.cs} (80%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_SwitchLANEndpoint.cs => ROOT.virtualization.v2.Msvm_LANEndpoint.cs} (81%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_MemorySettingData.cs => ROOT.virtualization.v2.Msvm_MemorySettingData.cs} (91%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_ProcessorSettingData.cs => ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs} (88%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_ResourceAllocationSettingData.cs => ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs} (95%) mode change 100644 => 100755 create mode 100755 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_SummaryInformation.cs => ROOT.virtualization.v2.Msvm_SummaryInformation.cs} (77%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_SyntheticEthernetPortSettingData.cs => ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs} (92%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_VirtualSwitch.cs => ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs} (80%) mode change 100644 => 100755 rename plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/{ROOT.virtualization.Msvm_IDEController.cs => ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs} (68%) mode change 100644 => 100755 create mode 100755 plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj index ed22a7a4ef7..05a0f513d8b 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj @@ -1,105 +1,103 @@ - - - - - Debug - AnyCPU - {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2} - Library - Properties - HypervResource - HypervResource - v4.5 - 512 - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\NoUnitTestsDebug\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\NoUnitTests\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll - - - ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll - - - ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll - - - ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {db824727-bdc3-437c-a364-7a811d8a160f} - WmiWrappers - - - - - + + + + + Debug + AnyCPU + {C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2} + Library + Properties + HypervResource + HypervResource + v4.5 + 512 + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + {db824727-bdc3-437c-a364-7a811d8a160f} + WmiWrappers + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs index 809894d1f49..55c37f3b103 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs @@ -1,1502 +1,1463 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -using Amazon; -using Amazon.S3; -using Amazon.S3.Model; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; -using log4net; -using Microsoft.CSharp.RuntimeBinder; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Security.Cryptography; -using System.Security.Principal; -using System.Web.Http; - -namespace HypervResource -{ - - public struct HypervResourceControllerConfig - { - private string privateIpAddress; - private static ILog logger = LogManager.GetLogger(typeof(HypervResourceControllerConfig)); - - public string PrivateIpAddress - { - get - { - return privateIpAddress; - } - set - { - ValidateIpAddress(value); - privateIpAddress = value; - System.Net.NetworkInformation.NetworkInterface nic = HypervResourceController.GetNicInfoFromIpAddress(privateIpAddress, out PrivateNetmask); - PrivateMacAddress = nic.GetPhysicalAddress().ToString(); - } - } - - private static void ValidateIpAddress(string value) - { - // Convert to IP address - IPAddress ipAddress; - if (!IPAddress.TryParse(value, out ipAddress)) - { - String errMsg = "Invalid PrivateIpAddress: " + value; - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - } - public string GatewayIpAddress; - public string PrivateMacAddress; - public string PrivateNetmask; - public string StorageNetmask; - public string StorageMacAddress; - public string StorageIpAddress; - public long RootDeviceReservedSpaceBytes; - public string RootDeviceName; - public ulong ParentPartitionMinMemoryMb; - public string LocalSecondaryStoragePath; - public string systemVmIso; - } - - /// - /// Supports one HTTP GET and multiple HTTP POST URIs - /// - /// - /// - /// POST takes dynamic to allow it to receive JSON without concern for what is the underlying object. - /// E.g. http://stackoverflow.com/questions/14071715/passing-dynamic-json-object-to-web-api-newtonsoft-example - /// and http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object - /// Use ActionName attribute to allow multiple POST URLs, one for each supported command - /// E.g. http://stackoverflow.com/a/12703423/939250 - /// Strictly speaking, this goes against the purpose of an ApiController, which is to provide one GET/POST/PUT/DELETE, etc. - /// However, it reduces the amount of code by removing the need for a switch according to the incoming command type. - /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx - /// - /// - /// Exceptions handled on command by command basis rather than globally to allow details of the command - /// to be reflected in the response. Default error handling is in the catch for Exception, but - /// other exception types may be caught where the feedback would be different. - /// NB: global alternatives discussed at - /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx - /// - /// - public class HypervResourceController : ApiController - { - public static void Configure(HypervResourceControllerConfig config) - { - HypervResourceController.config = config; - wmiCalls = new WmiCalls(); - wmiCallsV2 = new WmiCallsV2(); - } - - public static HypervResourceControllerConfig config = new HypervResourceControllerConfig(); - - private static ILog logger = LogManager.GetLogger(typeof(WmiCalls)); - private static string systemVmIso; - - public static void Initialize() - { - } - - public static IWmiCalls wmiCalls { get; set; } - public static IWmiCallsV2 wmiCallsV2 { get; set;} - - // GET api/HypervResource - public string Get() - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - return "HypervResource controller running, use POST to send JSON encoded RPCs"; ; - } - } - - /// - /// NOP - placeholder for future setup, e.g. delete existing VMs or Network ports - /// POST api/HypervResource/SetupCommand - /// - /// - /// - /// TODO: produce test - [HttpPost] - [ActionName(CloudStackTypes.SetupCommand)] - public JContainer SetupCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.SetupCommand + cmd.ToString()); - - string details = null; - bool result = false; - - try - { - NFSTO share = new NFSTO(); - String uriStr = (String)cmd.secondaryStorage; - share.uri = new Uri(uriStr); - - string systemVmIso = (string)cmd.systemVmIso; - string defaultDataPath = wmiCallsV2.GetDefaultDataRoot(); - string isoPath = Path.Combine(defaultDataPath, Path.GetFileName(systemVmIso)); - if (!File.Exists(isoPath)) - { - logger.Info("File " + isoPath + " not found. Copying it from the secondary share."); - Utils.DownloadCifsFileToLocalFile(systemVmIso, share, isoPath); - } - HypervResourceController.systemVmIso = isoPath; - result = true; - } - catch (Exception sysEx) - { - details = CloudStackTypes.SetupCommand + " failed due to " + sysEx.Message; - logger.Error(details, sysEx); - } - - object ansContent = new - { - result = result, - details = "success - NOP", - _reconnect = false - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer); - } - } - - // POST api/HypervResource/AttachCommand - [HttpPost] - [ActionName(CloudStackTypes.AttachCommand)] - public JContainer AttachCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.AttachCommand + cmd.ToString()); - - string details = null; - bool result = false; - - try - { - string vmName = (string)cmd.vmName; - string isoPath = "\\\\10.102.192.150\\SMB-Share\\202-2-305ed1f7-1be8-345e-86c3-a976f7f57f10.iso"; - wmiCalls.AttachIso(vmName, isoPath); - - result = true; - } - catch (Exception sysEx) - { - details = CloudStackTypes.AttachCommand + " failed due to " + sysEx.Message; - logger.Error(details, sysEx); - } - - object ansContent = new - { - result = result, - details = details - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.AttachAnswer); - } - } - - // POST api/HypervResource/DetachCommand - [HttpPost] - [ActionName(CloudStackTypes.DettachCommand)] - public JContainer DetachCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.DettachCommand + cmd.ToString()); - - string details = null; - bool result = false; - - try - { - string vmName = (string)cmd.vmName; - result = true; - } - catch (Exception sysEx) - { - details = CloudStackTypes.DettachCommand + " failed due to " + sysEx.Message; - logger.Error(details, sysEx); - } - - object ansContent = new - { - result = result, - details = details - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.DettachAnswer); - } - } - - // POST api/HypervResource/DestroyCommand - [HttpPost] - [ActionName(CloudStackTypes.DestroyCommand)] - public JContainer DestroyCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.DestroyCommand + cmd.ToString()); - - string details = null; - bool result = false; - - try - { - // Assert - String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + cmd.ToString(); - if (cmd.volume == null) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - - // Assert - errMsg = "No valide path in DestroyCommand in " + CloudStackTypes.DestroyCommand + " " + (String)cmd.ToString(); - if (cmd.volume.path == null) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - - String path = (string)cmd.volume.path; - if (!File.Exists(path)) - { - logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path); - } - - // TODO: will we have to detach volume? - string vmName = (string)cmd.vmName; - if (!string.IsNullOrEmpty(vmName) && File.Exists(path)) - { - var imgmgr = wmiCalls.GetImageManagementService(); - var returncode = imgmgr.Unmount(path); - if (returncode != ReturnCode.Completed) - { - details = "Could not detach driver from vm " + vmName + " for drive " + path; - logger.Error(details); - } - } - - File.Delete(path); - result = true; - } - catch (Exception sysEx) - { - details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message; - logger.Error(details, sysEx); - } - - object ansContent = new - { - result = result, - details = details - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - private static JArray ReturnCloudStackTypedJArray(object ansContent, string ansType) - { - JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent); - JArray answer = new JArray(ansObj); - logger.Info(ansObj.ToString()); - return answer; - } - - // POST api/HypervResource/CreateCommand - [HttpPost] - [ActionName(CloudStackTypes.CreateCommand)] - public JContainer CreateCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CreateCommand + cmd.ToString()); - - string details = null; - bool result = false; - VolumeInfo volume = new VolumeInfo(); - - try - { - string diskType = cmd.diskCharacteristics.type; - ulong disksize = cmd.diskCharacteristics.size; - string templateUri = cmd.templateUrl; - - // assert: valid storagepool? - string poolTypeStr = cmd.pool.type; - string poolLocalPath = cmd.pool.path; - string poolUuid = cmd.pool.uuid; - string newVolPath = null; - long volId = cmd.volId; - string newVolName = null; - - if (ValidStoragePool(poolTypeStr, poolLocalPath, poolUuid, ref details)) - { - // No template URI? Its a blank disk. - if (string.IsNullOrEmpty(templateUri)) - { - // assert - VolumeType volType; - if (!Enum.TryParse(diskType, out volType) && volType != VolumeType.DATADISK) - { - details = "Cannot create volumes of type " + (string.IsNullOrEmpty(diskType) ? "NULL" : diskType); - } - else - { - newVolName = cmd.diskCharacteristics.name; - newVolPath = Path.Combine(poolLocalPath, newVolName, diskType.ToLower()); - // TODO: how do you specify format as VHD or VHDX? - wmiCalls.CreateDynamicVirtualHardDisk(disksize, newVolPath); - if (File.Exists(newVolPath)) - { - result = true; - } - else - { - details = "Failed to create DATADISK with name " + newVolName; - } - } - } - else - { - // TODO: Does this always work, or do I need to download template at times? - if (templateUri.Contains("/") || templateUri.Contains("\\")) - { - details = "Problem with templateURL " + templateUri + - " the URL should be volume UUID in primary storage created by previous PrimaryStorageDownloadCommand"; - logger.Error(details); - } - else - { - logger.Debug("Template's name in primary store should be " + templateUri); - // HypervPhysicalDisk BaseVol = primaryPool.getPhysicalDisk(tmplturl); - FileInfo srcFileInfo = new FileInfo(templateUri); - newVolName = Guid.NewGuid() + srcFileInfo.Extension; - newVolPath = Path.Combine(poolLocalPath, newVolName); - logger.Debug("New volume will be at " + newVolPath); - string oldVolPath = Path.Combine(poolLocalPath, templateUri); - File.Copy(oldVolPath, newVolPath); - if (File.Exists(newVolPath)) - { - result = true; - } - else - { - details = "Failed to create DATADISK with name " + newVolName; - } - } - volume = new VolumeInfo( - volId, diskType, - poolTypeStr, poolUuid, newVolName, - newVolPath, newVolPath, (long)disksize, null); - } - } - } - catch (Exception sysEx) - { - // TODO: consider this as model for error processing in all commands - details = CloudStackTypes.CreateCommand + " failed due to " + sysEx.Message; - logger.Error(details, sysEx); - } - - object ansContent = new - { - result = result, - details = details, - volume = volume - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateAnswer); - } - } - - // POST api/HypervResource/PrimaryStorageDownloadCommand - [HttpPost] - [ActionName(CloudStackTypes.PrimaryStorageDownloadCommand)] - public JContainer PrimaryStorageDownloadCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + cmd.ToString()); - string details = null; - bool result = false; - long size = 0; - string newCopyFileName = null; - - string poolLocalPath = cmd.localPath; - string poolUuid = cmd.poolUuid; - if (!Directory.Exists(poolLocalPath)) - { - details = "None existent local path " + poolLocalPath; - } - else - { - // Compose name for downloaded file. - string sourceUrl = cmd.url; - if (sourceUrl.ToLower().EndsWith(".vhd")) - { - newCopyFileName = Guid.NewGuid() + ".vhd"; - } - if (sourceUrl.ToLower().EndsWith(".vhdx")) - { - newCopyFileName = Guid.NewGuid() + ".vhdx"; - } - - // assert - if (newCopyFileName == null) - { - details = CloudStackTypes.PrimaryStorageDownloadCommand + " Invalid file extension for hypervisor type in source URL " + sourceUrl; - logger.Error(details); - } - else - { - try - { - FileInfo newFile; - if (CopyURI(sourceUrl, newCopyFileName, poolLocalPath, out newFile, ref details)) - { - size = newFile.Length; - result = true; - } - } - catch (System.Exception ex) - { - details = CloudStackTypes.PrimaryStorageDownloadCommand + " Cannot download source URL " + sourceUrl + " due to " + ex.Message; - logger.Error(details, ex); - } - } - } - - object ansContent = new - { - result = result, - details = details, - templateSize = size, - installPath = newCopyFileName - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrimaryStorageDownloadAnswer); - } - } - - private static bool ValidStoragePool(string poolTypeStr, string poolLocalPath, string poolUuid, ref string details) - { - StoragePoolType poolType; - if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) - { - details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid StoragePoolType"; - logger.Error(details); - return false; - } - else if (!Directory.Exists(poolLocalPath)) - { - details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid local path"; - logger.Error(details); - return false; - } - return true; - } - - /// - /// Exceptions to watch out for: - /// Exceptions related to URI creation - /// System.SystemException - /// +-System.ArgumentNullException - /// +-System.FormatException - /// +-System.UriFormatException - /// - /// Exceptions related to NFS URIs - /// System.SystemException - /// +-System.NotSupportedException - /// +-System.ArgumentException - /// +-System.ArgumentNullException - /// +-System.Security.SecurityException; - /// +-System.UnauthorizedAccessException - /// +-System.IO.IOException - /// +-System.IO.PathTooLongException - /// - /// Exceptions related to HTTP URIs - /// System.SystemException - /// +-System.InvalidOperationException - /// +-System.Net.WebException - /// +-System.NotSupportedException - /// +-System.ArgumentNullException - /// - /// - /// - /// - /// - private bool CopyURI(string sourceUri, string newCopyFileName, string poolLocalPath, out FileInfo newFile, ref string details) - { - Uri source = new Uri(sourceUri); - String destFilePath = Path.Combine(poolLocalPath, newCopyFileName); - string[] pathSegments = source.Segments; - String templateUUIDandExtension = pathSegments[pathSegments.Length - 1]; - newFile = new FileInfo(destFilePath); - - // NFS URI assumed to already be mounted locally. Mount location given by settings. - if (source.Scheme.ToLower().Equals("nfs")) - { - String srcDiskPath = Path.Combine(HypervResourceController.config.LocalSecondaryStoragePath, templateUUIDandExtension); - String taskMsg = "Copy NFS url in " + sourceUri + " at " + srcDiskPath + " to pool " + poolLocalPath; - logger.Debug(taskMsg); - File.Copy(srcDiskPath, destFilePath); - } - else if (source.Scheme.ToLower().Equals("http") || source.Scheme.ToLower().Equals("https")) - { - System.Net.WebClient webclient = new WebClient(); - webclient.DownloadFile(source, destFilePath); - } - else - { - details = "Unsupported URI scheme " + source.Scheme.ToLower() + " in source URI " + sourceUri; - logger.Error(details); - return false; - } - - if (!File.Exists(destFilePath)) - { - details = "Filed to copy " + sourceUri + " to primary pool destination " + destFilePath; - logger.Error(details); - return false; - } - return true; - } - - // POST api/HypervResource/CheckHealthCommand - // TODO: create test - [HttpPost] - [ActionName(CloudStackTypes.CheckHealthCommand)] - public JContainer CheckHealthCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CheckHealthCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = "resource is alive" - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckHealthAnswer); - } - } - - // POST api/HypervResource/CheckSshCommand - // TODO: create test - [HttpPost] - [ActionName(CloudStackTypes.CheckSshCommand)] - public JContainer CheckSshCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CheckSshCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = "NOP, TODO: implement properly" - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckSshAnswer); - } - } - - // POST api/HypervResource/CheckVirtualMachineCommand - [HttpPost] - [ActionName(CloudStackTypes.CheckVirtualMachineCommand)] - public JContainer CheckVirtualMachineCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CheckVirtualMachineCommand + cmd.ToString()); - string details = null; - bool result = false; - string vmName = cmd.vmName; - string state = null; - - // TODO: Look up the VM, convert Hyper-V state to CloudStack version. - var sys = wmiCalls.GetComputerSystem(vmName); - if (sys == null) - { - details = CloudStackTypes.CheckVirtualMachineCommand + " requested unknown VM " + vmName; - logger.Error(details); - } - else - { - state = EnabledState.ToString(sys.EnabledState); - result = true; - } - - object ansContent = new - { - result = result, - details = details, - state = state - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckVirtualMachineAnswer); - } - } - - // POST api/HypervResource/DeleteStoragePoolCommand - [HttpPost] - [ActionName(CloudStackTypes.DeleteStoragePoolCommand)] - public JContainer DeleteStoragePoolCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.DeleteStoragePoolCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = "Current implementation does not delete local path corresponding to storage pool!" - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - /// - /// NOP - legacy command - - /// POST api/HypervResource/CreateStoragePoolCommand - /// - /// - /// - [HttpPost] - [ActionName(CloudStackTypes.CreateStoragePoolCommand)] - public JContainer CreateStoragePoolCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CreateStoragePoolCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = "success - NOP" - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - // POST api/HypervResource/ModifyStoragePoolCommand - [HttpPost] - [ActionName(CloudStackTypes.ModifyStoragePoolCommand)] - public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString()); - string details = null; - string localPath; - object ansContent; - - bool result = ValidateStoragePoolCommand(cmd, out localPath, ref details); - if (!result) - { - ansContent = new - { - result = result, - details = details - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - - var tInfo = new Dictionary(); - long capacityBytes; - long availableBytes; - GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes); - - String uuid = null; - var poolInfo = new - { - uuid = uuid, - host = cmd.pool.host, - localPath = cmd.pool.host, - hostPath = cmd.localPath, - poolType = cmd.pool.type, - capacityBytes = capacityBytes, - availableBytes = availableBytes - }; - - ansContent = new - { - result = result, - details = details, - templateInfo = tInfo, - poolInfo = poolInfo - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer); - } - } - - private bool ValidateStoragePoolCommand(dynamic cmd, out string localPath, ref string details) - { - dynamic pool = cmd.pool; - string poolTypeStr = pool.type; - StoragePoolType poolType; - localPath = cmd.localPath; - if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) - { - details = "Request to create / modify unsupported pool type: " + (poolTypeStr == null ? "NULL" : poolTypeStr) + "in cmd " + JsonConvert.SerializeObject(cmd); - logger.Error(details); - return false; - } - if (!Directory.Exists(localPath)) - { - details = "Request to create / modify unsupported StoragePoolType.Filesystem with non-existent path:" + (localPath == null ? "NULL" : localPath) + "in cmd " + JsonConvert.SerializeObject(cmd); - logger.Error(details); - return false; - } - return true; - } - - - // POST api/HypervResource/CleanupNetworkRulesCmd - [HttpPost] - [ActionName(CloudStackTypes.CleanupNetworkRulesCmd)] - public JContainer CleanupNetworkRulesCmd([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CleanupNetworkRulesCmd + cmd.ToString()); - object ansContent = new - { - result = false, - details = "nothing to cleanup in our current implementation" - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - // POST api/HypervResource/CheckNetworkCommand - [HttpPost] - [ActionName(CloudStackTypes.CheckNetworkCommand)] - public JContainer CheckNetworkCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.CheckNetworkCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = (string)null - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckNetworkAnswer); - } - } - - // POST api/HypervResource/ReadyCommand - [HttpPost] - [ActionName(CloudStackTypes.ReadyCommand)] - public JContainer ReadyCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.ReadyCommand + cmd.ToString()); - object ansContent = new - { - result = true, - details = (string)null - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ReadyAnswer); - } - - } - - // POST api/HypervResource/StartCommand - [HttpPost] - [ActionName(CloudStackTypes.StartCommand)] - public JContainer StartCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log - string details = null; - bool result = false; - - try - { - wmiCalls.DeployVirtualMachine(cmd, systemVmIso); - result = true; - } - catch (Exception wmiEx) - { - details = CloudStackTypes.StartCommand + " fail on exception" + wmiEx.Message; - logger.Error(details, wmiEx); - } - - object ansContent = new - { - result = result, - details = details, - vm = cmd.vm - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StartAnswer); - } - } - - // POST api/HypervResource/StopCommand - [HttpPost] - [ActionName(CloudStackTypes.StopCommand)] - public JContainer StopCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.StopCommand + cmd.ToString()); - string details = null; - bool result = false; - - try - { - wmiCalls.DestroyVm(cmd); - result = true; - } - catch (Exception wmiEx) - { - details = CloudStackTypes.StopCommand + " fail on exception" + wmiEx.Message; - logger.Error(details, wmiEx); - } - - object ansContent = new - { - result = result, - details = details, - vm = cmd.vm - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StopAnswer); - } - } - - // POST api/HypervResource/MaintainCommand - // TODO: should this be a NOP? - [HttpPost] - [ActionName(CloudStackTypes.MaintainCommand)] - public JContainer MaintainCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.MaintainCommand + cmd.ToString()); - - object ansContent = new - { - result = true, - details = "success - NOP for MaintainCommand", - _reconnect = false - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.MaintainAnswer); - } - } - - // POST api/HypervResource/PingRoutingCommand - // TODO: should this be a NOP? - [HttpPost] - [ActionName(CloudStackTypes.PingRoutingCommand)] - public JContainer PingRoutingCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.PingRoutingCommand + cmd.ToString()); - - object ansContent = new - { - result = true, - details = "success - NOP for PingRoutingCommand", - _reconnect = false - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - // POST api/HypervResource/PingCommand - // TODO: should this be a NOP? - [HttpPost] - [ActionName(CloudStackTypes.PingCommand)] - public JContainer PingCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.PingCommand + cmd.ToString()); - - object ansContent = new - { - result = true, - details = "success - NOP for PingCommand", - _reconnect = false - }; - - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); - } - } - - // POST api/HypervResource/GetVmStatsCommand - [HttpPost] - [ActionName(CloudStackTypes.GetVmStatsCommand)] - public JContainer GetVmStatsCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.GetVmStatsCommand + cmd.ToString()); - bool result = false; - string details = null; - JArray vmNamesJson = cmd.vmNames; - string[] vmNames = vmNamesJson.ToObject(); - Dictionary vmProcessorInfo = new Dictionary(vmNames.Length); - - var vmsToInspect = new List(); - foreach (var vmName in vmNames) - { - var sys = wmiCalls.GetComputerSystem(vmName); - if (sys == null) - { - logger.InfoFormat("GetVmStatsCommand requested unknown VM {0}", vmNames); - continue; - } - var sysInfo = wmiCalls.GetVmSettings(sys); - vmsToInspect.Add(sysInfo.Path); - } - - // Process info available from WMI, - // See http://msdn.microsoft.com/en-us/library/cc160706%28v=vs.85%29.aspx - uint[] requestedInfo = new uint[] { - 0, // Name - 1, // ElementName - 4, // Number of processes - 101 // ProcessorLoad - }; - - System.Management.ManagementBaseObject[] sysSummary; - var vmsvc = wmiCalls.GetVirtualisationSystemManagementService(); - System.Management.ManagementPath[] vmPaths = vmsToInspect.ToArray(); - vmsvc.GetSummaryInformation(requestedInfo, vmPaths, out sysSummary); - - foreach (var summary in sysSummary) - { - var summaryInfo = new CloudStack.Plugin.AgentShell.ROOT.VIRTUALIZATION.SummaryInformation(summary); - - logger.Debug("VM " + summaryInfo.Name + "(elementName " + summaryInfo.ElementName + ") has " + - summaryInfo.NumberOfProcessors + " CPUs, and load of " + summaryInfo.ProcessorLoad); - var vmInfo = new VmStatsEntry - { - cpuUtilization = summaryInfo.ProcessorLoad, - numCPUs = summaryInfo.NumberOfProcessors, - networkReadKBs = 1, - networkWriteKBs = 1, - entityType = "vm" - }; - vmProcessorInfo.Add(summaryInfo.ElementName, vmInfo); - } - - // TODO: Network usage comes from Performance Counter API; however it is only available in kb/s, and not in total terms. - // Curious about these? Use perfmon to inspect them, e.g. http://msdn.microsoft.com/en-us/library/xhcx5a20%28v=vs.100%29.aspx - // Recent post on these counter at http://blogs.technet.com/b/cedward/archive/2011/07/19/hyper-v-networking-optimizations-part-6-of-6-monitoring-hyper-v-network-consumption.aspx - result = true; - - object ansContent = new - { - vmInfos = vmProcessorInfo, - result = result, - details = details, - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmStatsAnswer); - } - } - - // POST api/HypervResource/StartupCommand - [HttpPost] - [ActionName(CloudStackTypes.CopyCommand)] - public JContainer CopyCommand(dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - // Log command *after* we've removed security details from the command. - - bool result = false; - string details = null; - object newData = null; - - try - { - dynamic timeout = cmd.wait; // TODO: Useful? - - TemplateObjectTO srcTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.srcTO); - TemplateObjectTO destTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.destTO); - VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.destTO); - - logger.Info(CloudStackTypes.CopyCommand + cmd.ToString()); - - // Already exists? - if (destTemplateObjectTO != null && - File.Exists(destTemplateObjectTO.FullFileName) && - !String.IsNullOrEmpty(destTemplateObjectTO.checksum)) - { - // TODO: checksum fails us, because it is of the compressed image. - // ASK: should we store the compressed or uncompressed version or is the checksum not calculated correctly? - result = VerifyChecksum(destTemplateObjectTO.FullFileName, destTemplateObjectTO.checksum); - if (result == false) - result = true; - } - - // Do we have to create a new one? - if (!result) - { - // Create local copy of a template? - if (srcTemplateObjectTO != null && destTemplateObjectTO != null) - { - // S3 download to primary storage? - // NFS provider download to primary storage? - if ((srcTemplateObjectTO.s3DataStoreTO != null || srcTemplateObjectTO.nfsDataStoreTO != null) && destTemplateObjectTO.primaryDataStore != null) - { - string destFile = destTemplateObjectTO.FullFileName; - - if (File.Exists(destFile)) - { - logger.Info("Deleting existing file " + destFile); - File.Delete(destFile); - } - - if (srcTemplateObjectTO.s3DataStoreTO != null) - { - // Download from S3 to destination data storage - DownloadS3ObjectToFile(srcTemplateObjectTO.path, srcTemplateObjectTO.s3DataStoreTO, destFile); - } - else if (srcTemplateObjectTO.nfsDataStoreTO != null) - { - // Download from S3 to destination data storage - Utils.DownloadCifsFileToLocalFile(srcTemplateObjectTO.path, srcTemplateObjectTO.nfsDataStoreTO, destFile); - } - - // Uncompress, as required - if (srcTemplateObjectTO.path.EndsWith(".bz2")) - { - String uncompressedFile = destFile + ".tmp"; - String compressedFile = destFile; - using (var uncompressedOutStrm = new FileStream(uncompressedFile, FileMode.CreateNew, FileAccess.Write)) - { - using (var compressedInStrm = new FileStream(destFile, FileMode.Open, FileAccess.Read)) - { - using (var bz2UncompressorStrm = new Ionic.BZip2.BZip2InputStream(compressedInStrm, true) /* outer 'using' statement will close FileStream*/ ) - { - int count = 0; - int bufsize = 1024 * 1024; - byte[] buf = new byte[bufsize]; - - // EOF returns -1, see http://dotnetzip.codeplex.com/workitem/16069 - while (0 < (count = bz2UncompressorStrm.Read(buf, 0, bufsize))) - { - uncompressedOutStrm.Write(buf, 0, count); - } - } - } - } - File.Delete(compressedFile); - File.Move(uncompressedFile, compressedFile); - if (File.Exists(uncompressedFile)) - { - String errMsg = "Extra file left around called " + uncompressedFile + " when creating " + destFile; - logger.Error(errMsg); - throw new IOException(errMsg); - } - } - - // assert - if (!File.Exists(destFile)) - { - String errMsg = "Failed to create " + destFile + " , because the file is missing"; - logger.Error(errMsg); - throw new IOException(errMsg); - } - - newData = cmd.destTO; - result = true; - } - else - { - details = "Data store combination not supported"; - } - } - // Create volume from a template? - else if (srcTemplateObjectTO != null && destVolumeObjectTO != null) - { - if (destVolumeObjectTO.format == null) - { - destVolumeObjectTO.format = srcTemplateObjectTO.format; - } - string destFile = destVolumeObjectTO.FullFileName; - string srcFile = srcTemplateObjectTO.FullFileName; - - if (!File.Exists(srcFile)) - { - details = "Local template file missing from " + srcFile; - } - else - { - if (File.Exists(destFile)) - { - logger.Info("Deleting existing file " + destFile); - File.Delete(destFile); - } - - // TODO: thin provision instead of copying the full file. - File.Copy(srcFile, destFile); - newData = cmd.destTO; - result = true; - } - } - else - { - details = "Data store combination not supported"; - } - } - } - catch (Exception ex) - { - // Test by providing wrong key - details = CloudStackTypes.CopyCommand + " failed on exception, " + ex.Message; - logger.Error(details, ex); - } - - object ansContent = new - { - result = result, - details = details, - newData = cmd.destTO - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CopyCmdAnswer); - } - } - - private static bool VerifyChecksum(string destFile, string checksum) - { - string localChecksum = BitConverter.ToString(CalcFileChecksum(destFile)).Replace("-", "").ToLower(); - logger.Debug("Checksum of " + destFile + " is " + checksum); - if (checksum.Equals(localChecksum)) - { - return true; - } - return false; - } - - /// - /// Match implmentation of DownloadManagerImpl.computeCheckSum - /// - /// - /// - private static byte[] CalcFileChecksum(string destFile) - { - // TODO: Add unit test to verify that checksum algorithm has not changed. - using (MD5 md5 = MD5.Create()) - { - using (FileStream stream = File.OpenRead(destFile)) - { - return md5.ComputeHash(stream); - } - } - } - - private static void DownloadS3ObjectToFile(string srcObjectKey, S3TO srcS3TO, string destFile) - { - AmazonS3Config S3Config = new AmazonS3Config - { - ServiceURL = srcS3TO.endpoint, - CommunicationProtocol = Amazon.S3.Model.Protocol.HTTP - }; - - if (srcS3TO.httpsFlag) - { - S3Config.CommunicationProtocol = Protocol.HTTPS; - } - - try - { - using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(srcS3TO.accessKey, srcS3TO.secretKey, S3Config)) - { - GetObjectRequest getObjectRequest = new GetObjectRequest().WithBucketName(srcS3TO.bucketName).WithKey(srcObjectKey); - - using (S3Response getObjectResponse = client.GetObject(getObjectRequest)) - { - using (Stream s = getObjectResponse.ResponseStream) - { - using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write)) - { - byte[] data = new byte[524288]; - int bytesRead = 0; - do - { - bytesRead = s.Read(data, 0, data.Length); - fs.Write(data, 0, bytesRead); - } - while (bytesRead > 0); - fs.Flush(); - } - } - } - } - } - catch (Exception ex) - { - string errMsg = "Download from S3 url" + srcS3TO.endpoint + " said: " + ex.Message; - logger.Error(errMsg, ex); - throw new Exception(errMsg, ex); - } - } - - // POST api/HypervResource/GetStorageStatsCommand - [HttpPost] - [ActionName(CloudStackTypes.GetStorageStatsCommand)] - public JContainer GetStorageStatsCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.GetStorageStatsCommand + cmd.ToString()); - bool result = false; - string details = null; - long capacity = 0; - long available = 0; - long used = 0; - try - { - string localPath = (string)cmd.localPath; - GetCapacityForLocalPath(localPath, out capacity, out available); - used = capacity - available; - result = true; - logger.Debug(CloudStackTypes.GetStorageStatsCommand + " set used bytes to " + used); - } - catch (Exception ex) - { - details = CloudStackTypes.GetStorageStatsCommand + " failed on exception" + ex.Message; - logger.Error(details, ex); - } - - object ansContent = new - { - result = result, - details = details, - capacity = capacity, - used = used - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetStorageStatsAnswer); - } - } - - // POST api/HypervResource/GetHostStatsCommand - [HttpPost] - [ActionName(CloudStackTypes.GetHostStatsCommand)] - public JContainer GetHostStatsCommand([FromBody]dynamic cmd) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(CloudStackTypes.GetHostStatsCommand + cmd.ToString()); - bool result = false; - string details = null; - object hostStats = null; - - var entityType = "host"; - ulong totalMemoryKBs; - ulong freeMemoryKBs; - double networkReadKBs; - double networkWriteKBs; - double cpuUtilization; - - try - { - long hostId = (long)cmd.hostId; - wmiCalls.GetMemoryResources(out totalMemoryKBs, out freeMemoryKBs); - wmiCalls.GetProcessorUsageInfo(out cpuUtilization); - - // TODO: can we assume that the host has only one adaptor? - string tmp; - var privateNic = GetNicInfoFromIpAddress(config.PrivateIpAddress, out tmp); - var nicStats = privateNic.GetIPv4Statistics(); //TODO: add IPV6 support, currentl - networkReadKBs = nicStats.BytesReceived; - networkWriteKBs = nicStats.BytesSent; - - // Generate GetHostStatsAnswer - hostStats = new - { - hostId = hostId, - entityType = entityType, - cpuUtilization = cpuUtilization, - networkReadKBs = networkReadKBs, - networkWriteKBs = networkWriteKBs, - totalMemoryKBs = (double)totalMemoryKBs, - freeMemoryKBs = (double)freeMemoryKBs - }; - result = true; - } - catch (Exception ex) - { - details = CloudStackTypes.GetHostStatsCommand + " failed on exception" + ex.Message; - logger.Error(details, ex); - } - - object ansContent = new - { - result = result, - hostStats = hostStats, - details = details - }; - return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetHostStatsAnswer); - } - } - - // POST api/HypervResource/StartupCommand - [HttpPost] - [ActionName(CloudStackTypes.StartupCommand)] - public JContainer StartupCommand([FromBody]dynamic cmdArray) - { - using (log4net.NDC.Push(Guid.NewGuid().ToString())) - { - logger.Info(cmdArray.ToString()); - // Log agent configuration - logger.Info("Agent StartupRoutingCommand received " + cmdArray.ToString()); - dynamic strtRouteCmd = cmdArray[0][CloudStackTypes.StartupRoutingCommand]; - - // Insert networking details - strtRouteCmd.privateIpAddress = config.PrivateIpAddress; - strtRouteCmd.privateNetmask = config.PrivateNetmask; - strtRouteCmd.privateMacAddress = config.PrivateMacAddress; - strtRouteCmd.storageIpAddress = config.PrivateIpAddress; - strtRouteCmd.storageNetmask = config.PrivateNetmask; - strtRouteCmd.storageMacAddress = config.PrivateMacAddress; - strtRouteCmd.gatewayIpAddress = config.GatewayIpAddress; - strtRouteCmd.caps = "hvm"; - - // Detect CPUs, speed, memory - uint cores; - uint mhz; - wmiCalls.GetProcessorResources(out cores, out mhz); - strtRouteCmd.cpus = cores; - strtRouteCmd.speed = mhz; - ulong memoryKBs; - ulong freeMemoryKBs; - wmiCalls.GetMemoryResources(out memoryKBs, out freeMemoryKBs); - strtRouteCmd.memory = memoryKBs * 1024; // Convert to bytes - - // Need 2 Gig for DOM0, see http://technet.microsoft.com/en-us/magazine/hh750394.aspx - strtRouteCmd.dom0MinMemory = config.ParentPartitionMinMemoryMb * 1024 * 1024; // Convert to bytes - - // Insert storage pool details. - // - // Read the localStoragePath for virtual disks from the Hyper-V configuration - // See http://blogs.msdn.com/b/virtual_pc_guy/archive/2010/05/06/managing-the-default-virtual-machine-location-with-hyper-v.aspx - // for discussion of Hyper-V file locations paths. - string localStoragePath = wmiCalls.GetDefaultVirtualDiskFolder(); - if (localStoragePath != null) - { - // GUID arbitrary. Host agents deals with storage pool in terms of localStoragePath. - // We use HOST guid. - string poolGuid = strtRouteCmd.guid; - - if (poolGuid == null) - { - poolGuid = Guid.NewGuid().ToString(); - logger.InfoFormat("Setting Startup StoragePool GUID to " + poolGuid); - } - else - { - logger.InfoFormat("Setting Startup StoragePool GUID same as HOST, i.e. " + poolGuid); - } - - long capacity; - long available; - GetCapacityForLocalPath(localStoragePath, out capacity, out available); - - logger.Debug(CloudStackTypes.StartupStorageCommand + " set available bytes to " + available); - - string ipAddr = strtRouteCmd.privateIpAddress; - StoragePoolInfo pi = new StoragePoolInfo( - poolGuid.ToString(), - ipAddr, - localStoragePath, - localStoragePath, - StoragePoolType.Filesystem.ToString(), - capacity, - available); - - // Build StartupStorageCommand using an anonymous type - // See http://stackoverflow.com/a/6029228/939250 - object ansContent = new - { - poolInfo = pi, - guid = pi.uuid, - dataCenter = strtRouteCmd.dataCenter, - resourceType = StorageResourceType.STORAGE_POOL.ToString() // TODO: check encoding - }; - JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.StartupStorageCommand, ansContent); - cmdArray.Add(ansObj); - } - - // Convert result to array for type correctness? - logger.Info(CloudStackTypes.StartupCommand + " result is " + cmdArray.ToString()); - return cmdArray; - } - } - - public static System.Net.NetworkInformation.NetworkInterface GetNicInfoFromIpAddress(string ipAddress, out string subnet) - { - System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); - foreach (var nic in nics) - { - subnet = null; - // TODO: use to remove NETMASK and MAC from the config file, and to validate the IPAddress. - var nicProps = nic.GetIPProperties(); - bool found = false; - foreach (var addr in nicProps.UnicastAddresses) - { - if (addr.Address.Equals(IPAddress.Parse(ipAddress))) - { - subnet = addr.IPv4Mask.ToString(); - found = true; - } - } - if (!found) - { - continue; - } - return nic; - } - throw new ArgumentException("No NIC for ipAddress " + ipAddress); - } - - public static void GetCapacityForLocalPath(string localStoragePath, out long capacityBytes, out long availableBytes) - { - // NB: DriveInfo does not work for remote folders (http://stackoverflow.com/q/1799984/939250) - // DriveInfo requires a driver letter... - string fullPath = Path.GetFullPath(localStoragePath); - System.IO.DriveInfo poolInfo = new System.IO.DriveInfo(fullPath); - capacityBytes = poolInfo.TotalSize; - availableBytes = poolInfo.AvailableFreeSpace; - - // Don't allow all of the Root Device to be used for virtual disks - if (poolInfo.RootDirectory.Name.ToLower().Equals(config.RootDeviceName)) - { - availableBytes -= config.RootDeviceReservedSpaceBytes; - availableBytes = availableBytes > 0 ? availableBytes : 0; - capacityBytes -= config.RootDeviceReservedSpaceBytes; - capacityBytes = capacityBytes > 0 ? capacityBytes : 0; - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using Amazon; +using Amazon.S3; +using Amazon.S3.Model; +using log4net; +using Microsoft.CSharp.RuntimeBinder; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Web.Http; + +namespace HypervResource +{ + + public struct HypervResourceControllerConfig + { + private string privateIpAddress; + private static ILog logger = LogManager.GetLogger(typeof(HypervResourceControllerConfig)); + + public string PrivateIpAddress + { + get + { + return privateIpAddress; + } + set + { + ValidateIpAddress(value); + privateIpAddress = value; + System.Net.NetworkInformation.NetworkInterface nic = HypervResourceController.GetNicInfoFromIpAddress(privateIpAddress, out PrivateNetmask); + PrivateMacAddress = nic.GetPhysicalAddress().ToString(); + } + } + + private static void ValidateIpAddress(string value) + { + // Convert to IP address + IPAddress ipAddress; + if (!IPAddress.TryParse(value, out ipAddress)) + { + String errMsg = "Invalid PrivateIpAddress: " + value; + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + } + public string GatewayIpAddress; + public string PrivateMacAddress; + public string PrivateNetmask; + public string StorageNetmask; + public string StorageMacAddress; + public string StorageIpAddress; + public long RootDeviceReservedSpaceBytes; + public string RootDeviceName; + public ulong ParentPartitionMinMemoryMb; + public string LocalSecondaryStoragePath; + public string systemVmIso; + } + + /// + /// Supports one HTTP GET and multiple HTTP POST URIs + /// + /// + /// + /// POST takes dynamic to allow it to receive JSON without concern for what is the underlying object. + /// E.g. http://stackoverflow.com/questions/14071715/passing-dynamic-json-object-to-web-api-newtonsoft-example + /// and http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object + /// Use ActionName attribute to allow multiple POST URLs, one for each supported command + /// E.g. http://stackoverflow.com/a/12703423/939250 + /// Strictly speaking, this goes against the purpose of an ApiController, which is to provide one GET/POST/PUT/DELETE, etc. + /// However, it reduces the amount of code by removing the need for a switch according to the incoming command type. + /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx + /// + /// + /// Exceptions handled on command by command basis rather than globally to allow details of the command + /// to be reflected in the response. Default error handling is in the catch for Exception, but + /// other exception types may be caught where the feedback would be different. + /// NB: global alternatives discussed at + /// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx + /// + /// + public class HypervResourceController : ApiController + { + public static void Configure(HypervResourceControllerConfig config) + { + HypervResourceController.config = config; + wmiCallsV2 = new WmiCallsV2(); + } + + public static HypervResourceControllerConfig config = new HypervResourceControllerConfig(); + + private static ILog logger = LogManager.GetLogger(typeof(HypervResourceController)); + private static string systemVmIso; + + public static void Initialize() + { + } + + public static IWmiCallsV2 wmiCallsV2 { get; set;} + + // GET api/HypervResource + public string Get() + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + return "HypervResource controller running, use POST to send JSON encoded RPCs"; ; + } + } + + /// + /// NOP - placeholder for future setup, e.g. delete existing VMs or Network ports + /// POST api/HypervResource/SetupCommand + /// + /// + /// + /// TODO: produce test + [HttpPost] + [ActionName(CloudStackTypes.SetupCommand)] + public JContainer SetupCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.SetupCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + NFSTO share = new NFSTO(); + String uriStr = (String)cmd.secondaryStorage; + share.uri = new Uri(uriStr); + + string systemVmIso = (string)cmd.systemVmIso; + string defaultDataPath = wmiCallsV2.GetDefaultDataRoot(); + string isoPath = Path.Combine(defaultDataPath, Path.GetFileName(systemVmIso)); + if (!File.Exists(isoPath)) + { + logger.Info("File " + isoPath + " not found. Copying it from the secondary share."); + Utils.DownloadCifsFileToLocalFile(systemVmIso, share, isoPath); + } + HypervResourceController.systemVmIso = isoPath; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.SetupCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = "success - NOP", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer); + } + } + + // POST api/HypervResource/AttachCommand + [HttpPost] + [ActionName(CloudStackTypes.AttachCommand)] + public JContainer AttachCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.AttachCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + string vmName = (string)cmd.vmName; + // TODO: remove absolute path + string isoPath = "\\\\10.102.192.150\\SMB-Share\\202-2-305ed1f7-1be8-345e-86c3-a976f7f57f10.iso"; + wmiCallsV2.AttachIso(vmName, isoPath); + + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.AttachCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.AttachAnswer); + } + } + + // POST api/HypervResource/DetachCommand + [HttpPost] + [ActionName(CloudStackTypes.DettachCommand)] + public JContainer DetachCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DettachCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + string vmName = (string)cmd.vmName; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.DettachCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.DettachAnswer); + } + } + + // POST api/HypervResource/DestroyCommand + [HttpPost] + [ActionName(CloudStackTypes.DestroyCommand)] + public JContainer DestroyCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DestroyCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + // Assert + String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + cmd.ToString(); + if (cmd.volume == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + // Assert + errMsg = "No valide path in DestroyCommand in " + CloudStackTypes.DestroyCommand + " " + (String)cmd.ToString(); + if (cmd.volume.path == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + String path = (string)cmd.volume.path; + if (!File.Exists(path)) + { + logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path); + } + + string vmName = (string)cmd.vmName; + if (!string.IsNullOrEmpty(vmName) && File.Exists(path)) + { + // Make sure that this resource is removed from the VM + wmiCallsV2.DetachDisk(vmName, path); + } + + File.Delete(path); + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + private static JArray ReturnCloudStackTypedJArray(object ansContent, string ansType) + { + JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent); + JArray answer = new JArray(ansObj); + logger.Info(ansObj.ToString()); + return answer; + } + + // POST api/HypervResource/CreateCommand + [HttpPost] + [ActionName(CloudStackTypes.CreateCommand)] + public JContainer CreateCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CreateCommand + cmd.ToString()); + + string details = null; + bool result = false; + VolumeInfo volume = new VolumeInfo(); + + try + { + string diskType = cmd.diskCharacteristics.type; + ulong disksize = cmd.diskCharacteristics.size; + string templateUri = cmd.templateUrl; + + // assert: valid storagepool? + string poolTypeStr = cmd.pool.type; + string poolLocalPath = cmd.pool.path; + string poolUuid = cmd.pool.uuid; + string newVolPath = null; + long volId = cmd.volId; + string newVolName = null; + + if (ValidStoragePool(poolTypeStr, poolLocalPath, poolUuid, ref details)) + { + // No template URI? Its a blank disk. + if (string.IsNullOrEmpty(templateUri)) + { + // assert + VolumeType volType; + if (!Enum.TryParse(diskType, out volType) && volType != VolumeType.DATADISK) + { + details = "Cannot create volumes of type " + (string.IsNullOrEmpty(diskType) ? "NULL" : diskType); + } + else + { + newVolName = cmd.diskCharacteristics.name; + newVolPath = Path.Combine(poolLocalPath, newVolName, diskType.ToLower()); + // TODO: make volume format and block size configurable + wmiCallsV2.CreateDynamicVirtualHardDisk(disksize, newVolPath); + if (File.Exists(newVolPath)) + { + result = true; + } + else + { + details = "Failed to create DATADISK with name " + newVolName; + } + } + } + else + { + // TODO: Does this always work, or do I need to download template at times? + if (templateUri.Contains("/") || templateUri.Contains("\\")) + { + details = "Problem with templateURL " + templateUri + + " the URL should be volume UUID in primary storage created by previous PrimaryStorageDownloadCommand"; + logger.Error(details); + } + else + { + logger.Debug("Template's name in primary store should be " + templateUri); + // HypervPhysicalDisk BaseVol = primaryPool.getPhysicalDisk(tmplturl); + FileInfo srcFileInfo = new FileInfo(templateUri); + newVolName = Guid.NewGuid() + srcFileInfo.Extension; + newVolPath = Path.Combine(poolLocalPath, newVolName); + logger.Debug("New volume will be at " + newVolPath); + string oldVolPath = Path.Combine(poolLocalPath, templateUri); + File.Copy(oldVolPath, newVolPath); + if (File.Exists(newVolPath)) + { + result = true; + } + else + { + details = "Failed to create DATADISK with name " + newVolName; + } + } + volume = new VolumeInfo( + volId, diskType, + poolTypeStr, poolUuid, newVolName, + newVolPath, newVolPath, (long)disksize, null); + } + } + } + catch (Exception sysEx) + { + // TODO: consider this as model for error processing in all commands + details = CloudStackTypes.CreateCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details, + volume = volume + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateAnswer); + } + } + + // POST api/HypervResource/PrimaryStorageDownloadCommand + [HttpPost] + [ActionName(CloudStackTypes.PrimaryStorageDownloadCommand)] + public JContainer PrimaryStorageDownloadCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + cmd.ToString()); + string details = null; + bool result = false; + long size = 0; + string newCopyFileName = null; + + string poolLocalPath = cmd.localPath; + string poolUuid = cmd.poolUuid; + if (!Directory.Exists(poolLocalPath)) + { + details = "None existent local path " + poolLocalPath; + } + else + { + // Compose name for downloaded file. + string sourceUrl = cmd.url; + if (sourceUrl.ToLower().EndsWith(".vhd")) + { + newCopyFileName = Guid.NewGuid() + ".vhd"; + } + if (sourceUrl.ToLower().EndsWith(".vhdx")) + { + newCopyFileName = Guid.NewGuid() + ".vhdx"; + } + + // assert + if (newCopyFileName == null) + { + details = CloudStackTypes.PrimaryStorageDownloadCommand + " Invalid file extension for hypervisor type in source URL " + sourceUrl; + logger.Error(details); + } + else + { + try + { + FileInfo newFile; + if (CopyURI(sourceUrl, newCopyFileName, poolLocalPath, out newFile, ref details)) + { + size = newFile.Length; + result = true; + } + } + catch (System.Exception ex) + { + details = CloudStackTypes.PrimaryStorageDownloadCommand + " Cannot download source URL " + sourceUrl + " due to " + ex.Message; + logger.Error(details, ex); + } + } + } + + object ansContent = new + { + result = result, + details = details, + templateSize = size, + installPath = newCopyFileName + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrimaryStorageDownloadAnswer); + } + } + + private static bool ValidStoragePool(string poolTypeStr, string poolLocalPath, string poolUuid, ref string details) + { + StoragePoolType poolType; + if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) + { + details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid StoragePoolType"; + logger.Error(details); + return false; + } + else if (!Directory.Exists(poolLocalPath)) + { + details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid local path"; + logger.Error(details); + return false; + } + return true; + } + + /// + /// Exceptions to watch out for: + /// Exceptions related to URI creation + /// System.SystemException + /// +-System.ArgumentNullException + /// +-System.FormatException + /// +-System.UriFormatException + /// + /// Exceptions related to NFS URIs + /// System.SystemException + /// +-System.NotSupportedException + /// +-System.ArgumentException + /// +-System.ArgumentNullException + /// +-System.Security.SecurityException; + /// +-System.UnauthorizedAccessException + /// +-System.IO.IOException + /// +-System.IO.PathTooLongException + /// + /// Exceptions related to HTTP URIs + /// System.SystemException + /// +-System.InvalidOperationException + /// +-System.Net.WebException + /// +-System.NotSupportedException + /// +-System.ArgumentNullException + /// + /// + /// + /// + /// + private bool CopyURI(string sourceUri, string newCopyFileName, string poolLocalPath, out FileInfo newFile, ref string details) + { + Uri source = new Uri(sourceUri); + String destFilePath = Path.Combine(poolLocalPath, newCopyFileName); + string[] pathSegments = source.Segments; + String templateUUIDandExtension = pathSegments[pathSegments.Length - 1]; + newFile = new FileInfo(destFilePath); + + // NFS URI assumed to already be mounted locally. Mount location given by settings. + if (source.Scheme.ToLower().Equals("nfs")) + { + String srcDiskPath = Path.Combine(HypervResourceController.config.LocalSecondaryStoragePath, templateUUIDandExtension); + String taskMsg = "Copy NFS url in " + sourceUri + " at " + srcDiskPath + " to pool " + poolLocalPath; + logger.Debug(taskMsg); + File.Copy(srcDiskPath, destFilePath); + } + else if (source.Scheme.ToLower().Equals("http") || source.Scheme.ToLower().Equals("https")) + { + System.Net.WebClient webclient = new WebClient(); + webclient.DownloadFile(source, destFilePath); + } + else + { + details = "Unsupported URI scheme " + source.Scheme.ToLower() + " in source URI " + sourceUri; + logger.Error(details); + return false; + } + + if (!File.Exists(destFilePath)) + { + details = "Filed to copy " + sourceUri + " to primary pool destination " + destFilePath; + logger.Error(details); + return false; + } + return true; + } + + // POST api/HypervResource/CheckHealthCommand + // TODO: create test + [HttpPost] + [ActionName(CloudStackTypes.CheckHealthCommand)] + public JContainer CheckHealthCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckHealthCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "resource is alive" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckHealthAnswer); + } + } + + // POST api/HypervResource/CheckSshCommand + // TODO: create test + [HttpPost] + [ActionName(CloudStackTypes.CheckSshCommand)] + public JContainer CheckSshCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckSshCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "NOP, TODO: implement properly" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckSshAnswer); + } + } + + // POST api/HypervResource/CheckVirtualMachineCommand + [HttpPost] + [ActionName(CloudStackTypes.CheckVirtualMachineCommand)] + public JContainer CheckVirtualMachineCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckVirtualMachineCommand + cmd.ToString()); + string details = null; + bool result = false; + string vmName = cmd.vmName; + string state = null; + + // TODO: Look up the VM, convert Hyper-V state to CloudStack version. + var sys = wmiCallsV2.GetComputerSystem(vmName); + if (sys == null) + { + details = CloudStackTypes.CheckVirtualMachineCommand + " requested unknown VM " + vmName; + logger.Error(details); + } + else + { + state = EnabledState.ToString(sys.EnabledState); // TODO: V2 changes? + result = true; + } + + object ansContent = new + { + result = result, + details = details, + state = state + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckVirtualMachineAnswer); + } + } + + // POST api/HypervResource/DeleteStoragePoolCommand + [HttpPost] + [ActionName(CloudStackTypes.DeleteStoragePoolCommand)] + public JContainer DeleteStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DeleteStoragePoolCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "Current implementation does not delete local path corresponding to storage pool!" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + /// + /// NOP - legacy command - + /// POST api/HypervResource/CreateStoragePoolCommand + /// + /// + /// + [HttpPost] + [ActionName(CloudStackTypes.CreateStoragePoolCommand)] + public JContainer CreateStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CreateStoragePoolCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "success - NOP" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/ModifyStoragePoolCommand + [HttpPost] + [ActionName(CloudStackTypes.ModifyStoragePoolCommand)] + public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString()); + string details = null; + string localPath; + object ansContent; + + bool result = ValidateStoragePoolCommand(cmd, out localPath, ref details); + if (!result) + { + ansContent = new + { + result = result, + details = details + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + + var tInfo = new Dictionary(); + long capacityBytes; + long availableBytes; + GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes); + + String uuid = null; + var poolInfo = new + { + uuid = uuid, + host = cmd.pool.host, + localPath = cmd.pool.host, + hostPath = cmd.localPath, + poolType = cmd.pool.type, + capacityBytes = capacityBytes, + availableBytes = availableBytes + }; + + ansContent = new + { + result = result, + details = details, + templateInfo = tInfo, + poolInfo = poolInfo + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer); + } + } + + private bool ValidateStoragePoolCommand(dynamic cmd, out string localPath, ref string details) + { + dynamic pool = cmd.pool; + string poolTypeStr = pool.type; + StoragePoolType poolType; + localPath = cmd.localPath; + if (!Enum.TryParse(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem) + { + details = "Request to create / modify unsupported pool type: " + (poolTypeStr == null ? "NULL" : poolTypeStr) + "in cmd " + JsonConvert.SerializeObject(cmd); + logger.Error(details); + return false; + } + if (!Directory.Exists(localPath)) + { + details = "Request to create / modify unsupported StoragePoolType.Filesystem with non-existent path:" + (localPath == null ? "NULL" : localPath) + "in cmd " + JsonConvert.SerializeObject(cmd); + logger.Error(details); + return false; + } + return true; + } + + + // POST api/HypervResource/CleanupNetworkRulesCmd + [HttpPost] + [ActionName(CloudStackTypes.CleanupNetworkRulesCmd)] + public JContainer CleanupNetworkRulesCmd([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CleanupNetworkRulesCmd + cmd.ToString()); + object ansContent = new + { + result = false, + details = "nothing to cleanup in our current implementation" + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/CheckNetworkCommand + [HttpPost] + [ActionName(CloudStackTypes.CheckNetworkCommand)] + public JContainer CheckNetworkCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckNetworkCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = (string)null + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckNetworkAnswer); + } + } + + // POST api/HypervResource/ReadyCommand + [HttpPost] + [ActionName(CloudStackTypes.ReadyCommand)] + public JContainer ReadyCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.ReadyCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = (string)null + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ReadyAnswer); + } + + } + + // POST api/HypervResource/StartCommand + [HttpPost] + [ActionName(CloudStackTypes.StartCommand)] + public JContainer StartCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log + string details = null; + bool result = false; + + try + { + wmiCallsV2.DeployVirtualMachine(cmd, systemVmIso); + result = true; + } + catch (Exception wmiEx) + { + details = CloudStackTypes.StartCommand + " fail on exception" + wmiEx.Message; + logger.Error(details, wmiEx); + } + + object ansContent = new + { + result = result, + details = details, + vm = cmd.vm + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StartAnswer); + } + } + + // POST api/HypervResource/StopCommand + [HttpPost] + [ActionName(CloudStackTypes.StopCommand)] + public JContainer StopCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.StopCommand + cmd.ToString()); + string details = null; + bool result = false; + + try + { + wmiCallsV2.DestroyVm(cmd); + result = true; + } + catch (Exception wmiEx) + { + details = CloudStackTypes.StopCommand + " fail on exception" + wmiEx.Message; + logger.Error(details, wmiEx); + } + + object ansContent = new + { + result = result, + details = details, + vm = cmd.vm + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StopAnswer); + } + } + + // POST api/HypervResource/MaintainCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.MaintainCommand)] + public JContainer MaintainCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.MaintainCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for MaintainCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.MaintainAnswer); + } + } + + // POST api/HypervResource/PingRoutingCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.PingRoutingCommand)] + public JContainer PingRoutingCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PingRoutingCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for PingRoutingCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/PingCommand + // TODO: should this be a NOP? + [HttpPost] + [ActionName(CloudStackTypes.PingCommand)] + public JContainer PingCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PingCommand + cmd.ToString()); + + object ansContent = new + { + result = true, + details = "success - NOP for PingCommand", + _reconnect = false + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + // POST api/HypervResource/GetVmStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetVmStatsCommand)] + public JContainer GetVmStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetVmStatsCommand + cmd.ToString()); + bool result = false; + string details = null; + JArray vmNamesJson = cmd.vmNames; + string[] vmNames = vmNamesJson.ToObject(); + Dictionary vmProcessorInfo = new Dictionary(vmNames.Length); + + var vmsToInspect = new List(); + foreach (var vmName in vmNames) + { + var sys = wmiCallsV2.GetComputerSystem(vmName); + if (sys == null) + { + logger.InfoFormat("GetVmStatsCommand requested unknown VM {0}", vmNames); + continue; + } + var sysInfo = wmiCallsV2.GetVmSettings(sys); + vmsToInspect.Add(sysInfo.Path); + } + + wmiCallsV2.GetSummaryInfo(vmProcessorInfo, vmsToInspect); + + // TODO: Network usage comes from Performance Counter API; however it is only available in kb/s, and not in total terms. + // Curious about these? Use perfmon to inspect them, e.g. http://msdn.microsoft.com/en-us/library/xhcx5a20%28v=vs.100%29.aspx + // Recent post on these counter at http://blogs.technet.com/b/cedward/archive/2011/07/19/hyper-v-networking-optimizations-part-6-of-6-monitoring-hyper-v-network-consumption.aspx + result = true; + + object ansContent = new + { + vmInfos = vmProcessorInfo, + result = result, + details = details, + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmStatsAnswer); + } + } + + // POST api/HypervResource/StartupCommand + [HttpPost] + [ActionName(CloudStackTypes.CopyCommand)] + public JContainer CopyCommand(dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + // Log command *after* we've removed security details from the command. + + bool result = false; + string details = null; + object newData = null; + + try + { + dynamic timeout = cmd.wait; // TODO: Useful? + + TemplateObjectTO srcTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.srcTO); + TemplateObjectTO destTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.destTO); + VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.destTO); + + logger.Info(CloudStackTypes.CopyCommand + cmd.ToString()); + + // Already exists? + if (destTemplateObjectTO != null && + File.Exists(destTemplateObjectTO.FullFileName) && + !String.IsNullOrEmpty(destTemplateObjectTO.checksum)) + { + // TODO: checksum fails us, because it is of the compressed image. + // ASK: should we store the compressed or uncompressed version or is the checksum not calculated correctly? + result = VerifyChecksum(destTemplateObjectTO.FullFileName, destTemplateObjectTO.checksum); + } + + // Do we have to create a new one? + if (!result) + { + // Create local copy of a template? + if (srcTemplateObjectTO != null && destTemplateObjectTO != null) + { + // S3 download to primary storage? + // NFS provider download to primary storage? + if ((srcTemplateObjectTO.s3DataStoreTO != null || srcTemplateObjectTO.nfsDataStoreTO != null) && destTemplateObjectTO.primaryDataStore != null) + { + string destFile = destTemplateObjectTO.FullFileName; + + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + if (srcTemplateObjectTO.s3DataStoreTO != null) + { + // Download from S3 to destination data storage + DownloadS3ObjectToFile(srcTemplateObjectTO.path, srcTemplateObjectTO.s3DataStoreTO, destFile); + } + else if (srcTemplateObjectTO.nfsDataStoreTO != null) + { + // Download from S3 to destination data storage + Utils.DownloadCifsFileToLocalFile(srcTemplateObjectTO.path, srcTemplateObjectTO.nfsDataStoreTO, destFile); + } + + // Uncompress, as required + if (srcTemplateObjectTO.path.EndsWith(".bz2")) + { + String uncompressedFile = destFile + ".tmp"; + String compressedFile = destFile; + using (var uncompressedOutStrm = new FileStream(uncompressedFile, FileMode.CreateNew, FileAccess.Write)) + { + using (var compressedInStrm = new FileStream(destFile, FileMode.Open, FileAccess.Read)) + { + using (var bz2UncompressorStrm = new Ionic.BZip2.BZip2InputStream(compressedInStrm, true) /* outer 'using' statement will close FileStream*/ ) + { + int count = 0; + int bufsize = 1024 * 1024; + byte[] buf = new byte[bufsize]; + + // EOF returns -1, see http://dotnetzip.codeplex.com/workitem/16069 + while (0 < (count = bz2UncompressorStrm.Read(buf, 0, bufsize))) + { + uncompressedOutStrm.Write(buf, 0, count); + } + } + } + } + File.Delete(compressedFile); + File.Move(uncompressedFile, compressedFile); + if (File.Exists(uncompressedFile)) + { + String errMsg = "Extra file left around called " + uncompressedFile + " when creating " + destFile; + logger.Error(errMsg); + throw new IOException(errMsg); + } + } + + // assert + if (!File.Exists(destFile)) + { + String errMsg = "Failed to create " + destFile + " , because the file is missing"; + logger.Error(errMsg); + throw new IOException(errMsg); + } + + newData = cmd.destTO; + result = true; + } + else + { + details = "Data store combination not supported"; + } + } + // Create volume from a template? + else if (srcTemplateObjectTO != null && destVolumeObjectTO != null) + { + if (destVolumeObjectTO.format == null) + { + destVolumeObjectTO.format = srcTemplateObjectTO.format; + } + string destFile = destVolumeObjectTO.FullFileName; + string srcFile = srcTemplateObjectTO.FullFileName; + + if (!File.Exists(srcFile)) + { + details = "Local template file missing from " + srcFile; + } + else + { + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + // TODO: thin provision instead of copying the full file. + File.Copy(srcFile, destFile); + newData = cmd.destTO; + result = true; + } + } + else + { + details = "Data store combination not supported"; + } + } + } + catch (Exception ex) + { + // Test by providing wrong key + details = CloudStackTypes.CopyCommand + " failed on exception, " + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + details = details, + newData = cmd.destTO + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CopyCmdAnswer); + } + } + + private static bool VerifyChecksum(string destFile, string checksum) + { + string localChecksum = BitConverter.ToString(CalcFileChecksum(destFile)).Replace("-", "").ToLower(); + logger.Debug("Checksum of " + destFile + " is " + checksum); + if (checksum.Equals(localChecksum)) + { + return true; + } + return true; + } + + /// + /// Match implmentation of DownloadManagerImpl.computeCheckSum + /// + /// + /// + private static byte[] CalcFileChecksum(string destFile) + { + // TODO: Add unit test to verify that checksum algorithm has not changed. + using (MD5 md5 = MD5.Create()) + { + using (FileStream stream = File.OpenRead(destFile)) + { + return md5.ComputeHash(stream); + } + } + } + + private static void DownloadS3ObjectToFile(string srcObjectKey, S3TO srcS3TO, string destFile) + { + AmazonS3Config S3Config = new AmazonS3Config + { + ServiceURL = srcS3TO.endpoint, + CommunicationProtocol = Amazon.S3.Model.Protocol.HTTP + }; + + if (srcS3TO.httpsFlag) + { + S3Config.CommunicationProtocol = Protocol.HTTPS; + } + + try + { + using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(srcS3TO.accessKey, srcS3TO.secretKey, S3Config)) + { + GetObjectRequest getObjectRequest = new GetObjectRequest().WithBucketName(srcS3TO.bucketName).WithKey(srcObjectKey); + + using (S3Response getObjectResponse = client.GetObject(getObjectRequest)) + { + using (Stream s = getObjectResponse.ResponseStream) + { + using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write)) + { + byte[] data = new byte[524288]; + int bytesRead = 0; + do + { + bytesRead = s.Read(data, 0, data.Length); + fs.Write(data, 0, bytesRead); + } + while (bytesRead > 0); + fs.Flush(); + } + } + } + } + } + catch (Exception ex) + { + string errMsg = "Download from S3 url" + srcS3TO.endpoint + " said: " + ex.Message; + logger.Error(errMsg, ex); + throw new Exception(errMsg, ex); + } + } + + // POST api/HypervResource/GetStorageStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetStorageStatsCommand)] + public JContainer GetStorageStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetStorageStatsCommand + cmd.ToString()); + bool result = false; + string details = null; + long capacity = 0; + long available = 0; + long used = 0; + try + { + string localPath = (string)cmd.localPath; + GetCapacityForLocalPath(localPath, out capacity, out available); + used = capacity - available; + result = true; + logger.Debug(CloudStackTypes.GetStorageStatsCommand + " set used bytes to " + used); + } + catch (Exception ex) + { + details = CloudStackTypes.GetStorageStatsCommand + " failed on exception" + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + details = details, + capacity = capacity, + used = used + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetStorageStatsAnswer); + } + } + + // POST api/HypervResource/GetHostStatsCommand + [HttpPost] + [ActionName(CloudStackTypes.GetHostStatsCommand)] + public JContainer GetHostStatsCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetHostStatsCommand + cmd.ToString()); + bool result = false; + string details = null; + object hostStats = null; + + var entityType = "host"; + ulong totalMemoryKBs; + ulong freeMemoryKBs; + double networkReadKBs; + double networkWriteKBs; + double cpuUtilization; + + try + { + long hostId = (long)cmd.hostId; + wmiCallsV2.GetMemoryResources(out totalMemoryKBs, out freeMemoryKBs); + wmiCallsV2.GetProcessorUsageInfo(out cpuUtilization); + + // TODO: can we assume that the host has only one adaptor? + string tmp; + var privateNic = GetNicInfoFromIpAddress(config.PrivateIpAddress, out tmp); + var nicStats = privateNic.GetIPv4Statistics(); //TODO: add IPV6 support, currentl + networkReadKBs = nicStats.BytesReceived; + networkWriteKBs = nicStats.BytesSent; + + // Generate GetHostStatsAnswer + hostStats = new + { + hostId = hostId, + entityType = entityType, + cpuUtilization = cpuUtilization, + networkReadKBs = networkReadKBs, + networkWriteKBs = networkWriteKBs, + totalMemoryKBs = (double)totalMemoryKBs, + freeMemoryKBs = (double)freeMemoryKBs + }; + result = true; + } + catch (Exception ex) + { + details = CloudStackTypes.GetHostStatsCommand + " failed on exception" + ex.Message; + logger.Error(details, ex); + } + + object ansContent = new + { + result = result, + hostStats = hostStats, + details = details + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetHostStatsAnswer); + } + } + + // POST api/HypervResource/StartupCommand + [HttpPost] + [ActionName(CloudStackTypes.StartupCommand)] + public JContainer StartupCommand([FromBody]dynamic cmdArray) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(cmdArray.ToString()); + // Log agent configuration + logger.Info("Agent StartupRoutingCommand received " + cmdArray.ToString()); + dynamic strtRouteCmd = cmdArray[0][CloudStackTypes.StartupRoutingCommand]; + + // Insert networking details + strtRouteCmd.privateIpAddress = config.PrivateIpAddress; + strtRouteCmd.privateNetmask = config.PrivateNetmask; + strtRouteCmd.privateMacAddress = config.PrivateMacAddress; + strtRouteCmd.storageIpAddress = config.PrivateIpAddress; + strtRouteCmd.storageNetmask = config.PrivateNetmask; + strtRouteCmd.storageMacAddress = config.PrivateMacAddress; + strtRouteCmd.gatewayIpAddress = config.GatewayIpAddress; + strtRouteCmd.caps = "hvm"; + + // Detect CPUs, speed, memory + uint cores; + uint mhz; + wmiCallsV2.GetProcessorResources(out cores, out mhz); + strtRouteCmd.cpus = cores; + strtRouteCmd.speed = mhz; + ulong memoryKBs; + ulong freeMemoryKBs; + wmiCallsV2.GetMemoryResources(out memoryKBs, out freeMemoryKBs); + strtRouteCmd.memory = memoryKBs * 1024; // Convert to bytes + + // Need 2 Gig for DOM0, see http://technet.microsoft.com/en-us/magazine/hh750394.aspx + strtRouteCmd.dom0MinMemory = config.ParentPartitionMinMemoryMb * 1024 * 1024; // Convert to bytes + + // Insert storage pool details. + // + // Read the localStoragePath for virtual disks from the Hyper-V configuration + // See http://blogs.msdn.com/b/virtual_pc_guy/archive/2010/05/06/managing-the-default-virtual-machine-location-with-hyper-v.aspx + // for discussion of Hyper-V file locations paths. + string localStoragePath = wmiCallsV2.GetDefaultVirtualDiskFolder(); + if (localStoragePath != null) + { + // GUID arbitrary. Host agents deals with storage pool in terms of localStoragePath. + // We use HOST guid. + string poolGuid = strtRouteCmd.guid; + + if (poolGuid == null) + { + poolGuid = Guid.NewGuid().ToString(); + logger.InfoFormat("Setting Startup StoragePool GUID to " + poolGuid); + } + else + { + logger.InfoFormat("Setting Startup StoragePool GUID same as HOST, i.e. " + poolGuid); + } + + long capacity; + long available; + GetCapacityForLocalPath(localStoragePath, out capacity, out available); + + logger.Debug(CloudStackTypes.StartupStorageCommand + " set available bytes to " + available); + + string ipAddr = strtRouteCmd.privateIpAddress; + StoragePoolInfo pi = new StoragePoolInfo( + poolGuid.ToString(), + ipAddr, + localStoragePath, + localStoragePath, + StoragePoolType.Filesystem.ToString(), + capacity, + available); + + // Build StartupStorageCommand using an anonymous type + // See http://stackoverflow.com/a/6029228/939250 + object ansContent = new + { + poolInfo = pi, + guid = pi.uuid, + dataCenter = strtRouteCmd.dataCenter, + resourceType = StorageResourceType.STORAGE_POOL.ToString() // TODO: check encoding + }; + JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.StartupStorageCommand, ansContent); + cmdArray.Add(ansObj); + } + + // Convert result to array for type correctness? + logger.Info(CloudStackTypes.StartupCommand + " result is " + cmdArray.ToString()); + return cmdArray; + } + } + + public static System.Net.NetworkInformation.NetworkInterface GetNicInfoFromIpAddress(string ipAddress, out string subnet) + { + System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); + foreach (var nic in nics) + { + subnet = null; + // TODO: use to remove NETMASK and MAC from the config file, and to validate the IPAddress. + var nicProps = nic.GetIPProperties(); + bool found = false; + foreach (var addr in nicProps.UnicastAddresses) + { + if (addr.Address.Equals(IPAddress.Parse(ipAddress))) + { + subnet = addr.IPv4Mask.ToString(); + found = true; + } + } + if (!found) + { + continue; + } + return nic; + } + throw new ArgumentException("No NIC for ipAddress " + ipAddress); + } + + public static void GetCapacityForLocalPath(string localStoragePath, out long capacityBytes, out long availableBytes) + { + // NB: DriveInfo does not work for remote folders (http://stackoverflow.com/q/1799984/939250) + // DriveInfo requires a driver letter... + string fullPath = Path.GetFullPath(localStoragePath); + System.IO.DriveInfo poolInfo = new System.IO.DriveInfo(fullPath); + capacityBytes = poolInfo.TotalSize; + availableBytes = poolInfo.AvailableFreeSpace; + + // Don't allow all of the Root Device to be used for virtual disks + if (poolInfo.RootDirectory.Name.ToLower().Equals(config.RootDeviceName)) + { + availableBytes -= config.RootDeviceReservedSpaceBytes; + availableBytes = availableBytes > 0 ? availableBytes : 0; + capacityBytes -= config.RootDeviceReservedSpaceBytes; + capacityBytes = capacityBytes > 0 ? capacityBytes : 0; + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs index b3695c71bdd..82b68856b1b 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs @@ -1,22 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; -using System.Management; - -namespace HypervResource -{ - public interface IWmiCallsV2 - { - ComputerSystem AddUserData(ComputerSystem vm, string userData); - void DeleteHostKvpItem(ComputerSystem vm, string key); - VirtualSystemManagementService GetVirtualisationSystemManagementService(); - ComputerSystem GetComputerSystem(string displayName); - List GetVmElementNames(); - VirtualSystemSettingData GetVmSettings(ComputerSystem vm); - KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings); - string GetDefaultDataRoot(); - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using System.Management; + +namespace HypervResource +{ + public interface IWmiCallsV2 + { + System.Management.ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType); + ComputerSystem AddUserData(ComputerSystem vm, string userData); + void AttachIso(string displayName, string iso); + void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path); + SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac); + ComputerSystem CreateVM(string name, long memory_mb, int vcpus); + void DeleteHostKvpItem(ComputerSystem vm, string key); + void DeleteSwitchPort(string elementName); + ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso); + void DestroyVm(dynamic jsonObj); + void DestroyVm(string displayName); + void DetachDisk(string displayName, string diskFileName); + ComputerSystem GetComputerSystem(string displayName); + string GetDefaultDataRoot(); + string GetDefaultVirtualDiskFolder(); + ResourceAllocationSettingData GetDvdDriveSettings(VirtualSystemSettingData vmSettings); + EthernetPortAllocationSettingData[] GetEthernetConnections(ComputerSystem vm); + SyntheticEthernetPortSettingData[] GetEthernetPortSettings(ComputerSystem vm); + ResourceAllocationSettingData GetIDEControllerSettings(VirtualSystemSettingData vmSettings, string cntrllerAddr); + ImageManagementService GetImageManagementService(); + KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings); + void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs); + MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings); + void GetProcessorResources(out uint cores, out uint mhz); + void GetProcessorUsageInfo(out double cpuUtilization); + ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings); + ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings); + void GetSummaryInfo(System.Collections.Generic.Dictionary vmProcessorInfo, System.Collections.Generic.List vmsToInspect); + SyntheticEthernetPortSettingData GetSyntheticEthernetPortSettings(EthernetSwitchPort port); + VirtualSystemManagementService GetVirtualisationSystemManagementService(); + VirtualEthernetSwitchManagementService GetVirtualSwitchManagementService(); + EthernetSwitchPortVlanSettingData GetVlanSettings(EthernetPortAllocationSettingData ethernetConnection); + System.Collections.Generic.List GetVmElementNames(); + VirtualSystemSettingData GetVmSettings(ComputerSystem vm); + void patchSystemVmIso(string vmName, string systemVmIso); + void SetState(ComputerSystem vm, ushort requiredState); + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCalls.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCalls.cs deleted file mode 100644 index 985cebaa6bf..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCalls.cs +++ /dev/null @@ -1,1419 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; -using log4net; -using System.Globalization; -using System.Management; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using CloudStack.Plugin.WmiWrappers.ROOT.CIMV2; -using System.IO; -using System.Net.NetworkInformation; -using System.Net; - -namespace HypervResource -{ - public class WmiCalls : IWmiCalls - { - private IWmiCallsV2 wmiCallsV2; - public WmiCalls() - { - wmiCallsV2 = new WmiCallsV2(); - } - public static void Initialize() - { - // Trigger assembly load into curren appdomain - } - - private static ILog logger = LogManager.GetLogger(typeof(WmiCalls)); - - /// - /// Returns ComputerSystem lacking any NICs and VOLUMEs - /// - public ComputerSystem CreateVM(string name, long memory_mb, int vcpus) - { - // Obtain controller for Hyper-V virtualisation subsystem - VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); - - // Create VM with correct name and default resources - ComputerSystem vm = CreateDefaultVm(vmMgmtSvc, name); - - // Update the resource settings for the VM. - - // Resource settings are referenced through the Msvm_VirtualSystemSettingData object. - VirtualSystemSettingData vmSettings = GetVmSettings(vm); - - // For memory settings, there is no Dynamic Memory, so reservation, limit and quantity are identical. - MemorySettingData memSettings = GetMemSettings(vmSettings); - memSettings.LateBoundObject["VirtualQuantity"] = memory_mb; - memSettings.LateBoundObject["Reservation"] = memory_mb; - memSettings.LateBoundObject["Limit"] = memory_mb; - - // Update the processor settings for the VM, static assignment of 100% for CPU limit - ProcessorSettingData procSettings = GetProcSettings(vmSettings); - procSettings.LateBoundObject["VirtualQuantity"] = vcpus; - procSettings.LateBoundObject["Reservation"] = vcpus; - procSettings.LateBoundObject["Limit"] = 100000; - - ModifyVmResources(vmMgmtSvc, vm, new String[] { - memSettings.LateBoundObject.GetText(TextFormat.CimDtd20), - procSettings.LateBoundObject.GetText(TextFormat.CimDtd20) - }); - logger.InfoFormat("VM with display name {0} has GUID {1}", vm.ElementName, vm.Name); - logger.DebugFormat("Resources for vm {0}: {1} MB memory, {2} vcpus", name, memory_mb, vcpus); - - return vm; - } - - /// - /// Create a (synthetic) nic, and attach it to the vm - /// - /// - /// - /// - /// - public SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac, string vlan) - { - logger.DebugFormat("Creating nic for VM {0} (GUID {1})", vm.ElementName, vm.Name); - - // Obtain controller for Hyper-V networking subsystem - VirtualSwitchManagementService vmNetMgmtSvc = GetVirtualSwitchManagementService(); - - // Create NIC resource by cloning the default NIC - var synthNICsSettings = SyntheticEthernetPortSettingData.GetInstances(vmNetMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); - - // Assert - if (synthNICsSettings.Count != 1) - { - var errMsg = string.Format("Internal error, coudl not find default SyntheticEthernetPort instance"); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - var defaultSynthNICSettings = synthNICsSettings.OfType().First(); - - var newSynthNICSettings = new SyntheticEthernetPortSettingData((ManagementBaseObject)defaultSynthNICSettings.LateBoundObject.Clone()); - - // Get the virtual switch - VirtualSwitch vSwitch = GetExternalVirtSwitch(); - - // Crate switch port for new VM - ManagementPath newSwitchPath = CreateSwitchPortForVm(vm, vmNetMgmtSvc, vSwitch); - - // Add required VLAND support - if (vlan != null) - { - SetPortVlan(vlan, vmNetMgmtSvc, newSwitchPath); - } - - logger.DebugFormat("Created switch port {0} on switch {1}", newSwitchPath.Path, vSwitch.Path.Path); - - // Assign configuration to new NIC - string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' }))); - newSynthNICSettings.LateBoundObject["Connection"] = new string[] { newSwitchPath.Path }; - newSynthNICSettings.LateBoundObject["ElementName"] = vm.ElementName; - newSynthNICSettings.LateBoundObject["Address"] = normalisedMAC; - newSynthNICSettings.LateBoundObject["StaticMacAddress"] = "TRUE"; - newSynthNICSettings.LateBoundObject["VirtualSystemIdentifiers"] = new string[] { "{" + Guid.NewGuid().ToString() + "}" }; - newSynthNICSettings.CommitObject(); - - // Insert NIC into vm - string[] newResources = new string[] { newSynthNICSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20)}; - ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm ); - - // assert - if (newResourcePaths.Length != 1) - { - var errMsg = string.Format( - "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", - vm.ElementName, - vm.Name, - newResourcePaths.Length); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - return new SyntheticEthernetPortSettingData(newResourcePaths[0]); - } - - public const string IDE_HARDDISK_DRIVE = "Microsoft Synthetic Disk Drive"; - public const string IDE_ISO_DRIVE = "Microsoft Synthetic DVD Drive"; - - public const string IDE_ISO_DISK = "Microsoft Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE - public const string IDE_HARDDISK_DISK = "Microsoft Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE - - /// - /// Create new VM. By default we start it. - /// - - public ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso) - { - var vmInfo = jsonObj.vm; - string vmName = vmInfo.name; - var nicInfo = vmInfo.nics; - int vcpus = vmInfo.cpus; - int memSize = vmInfo.maxRam / 1048576; - string errMsg = vmName; - var diskDrives = vmInfo.disks; - var bootArgs = vmInfo.bootArgs; - - // assert - errMsg = vmName + ": missing disk information, array empty or missing, agent expects *at least* one disk for a VM"; - if (diskDrives == null) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - // assert - errMsg = vmName + ": missing NIC information, array empty or missing, agent expects at least an empty array."; - if (nicInfo == null ) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - - - // For existing VMs, return when we spot one of this name not stopped. In the meantime, remove any existing VMs of same name. - ComputerSystem vmWmiObj = null; - while ((vmWmiObj = GetComputerSystem(vmName)) != null) - { - logger.WarnFormat("Create request for existing vm, name {0}", vmName); - if (vmWmiObj.EnabledState == EnabledState.Disabled) - { - logger.InfoFormat("Deleting existing VM with name {0}, before we go on to create a VM with the same name", vmName); - DestroyVm(vmName); - } - else - { - // TODO: revise exception type - errMsg = string.Format("Create VM failing, because there exists a VM with name {0}, state {1}", - vmName, - EnabledState.ToString(vmWmiObj.EnabledState)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - } - - // Create vm carcase - logger.DebugFormat("Going ahead with create VM {0}, {1} vcpus, {2}MB RAM", vmName, vcpus, memSize); - var newVm = CreateVM(vmName, memSize, vcpus); - - foreach (var diskDrive in diskDrives) - { - string vhdFile = null; - string diskName = null; - VolumeObjectTO volInfo = VolumeObjectTO.ParseJson(diskDrive.data); - if (volInfo != null) - { - // assert - errMsg = vmName + ": volume missing primaryDataStore for disk " + diskDrive.ToString(); - if (volInfo.primaryDataStore == null) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - diskName = volInfo.name; - - // assert - errMsg = vmName + ": can't deal with DataStore type for disk " + diskDrive.ToString(); - if (volInfo.primaryDataStore == null) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - errMsg = vmName + ": Malformed PrimaryDataStore for disk " + diskDrive.ToString(); - if (String.IsNullOrEmpty(volInfo.primaryDataStore.path)) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - errMsg = vmName + ": Missing folder PrimaryDataStore for disk " + diskDrive.ToString() + ", missing path: " + volInfo.primaryDataStore.path; - if (!Directory.Exists(volInfo.primaryDataStore.path)) - { - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - - vhdFile = volInfo.FullFileName; - if (!System.IO.File.Exists(vhdFile)) - { - errMsg = vmName + ": non-existent volume, missing " + vhdFile + " for drive " + diskDrive.ToString(); - logger.Error(errMsg); - throw new ArgumentException(errMsg); - } - logger.Debug("Going to create " + vmName + " with attached voluem " + diskName + " at " + vhdFile); - } - - string driveType = diskDrive.type; - - string ideCtrllr = "0"; - string driveResourceType = null; - switch (driveType) { - case "ROOT": - ideCtrllr = "0"; - driveResourceType = IDE_HARDDISK_DRIVE; - break; - case "ISO": - ideCtrllr = "1"; - driveResourceType = IDE_ISO_DRIVE; - break; - default: - // TODO: double check exception type - errMsg = string.Format("Unknown disk type {0} for disk {1}, vm named {2}", - string.IsNullOrEmpty(driveType) ? "NULL" : driveType, - string.IsNullOrEmpty(diskName) ? "NULL" : diskName, vmName); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName, - string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" +vhdFile ); - AddDiskDriveToVm(newVm, vhdFile, ideCtrllr, driveResourceType); - } - - // Add the Nics to the VM in the deviceId order. - String publicIpAddress =""; - for (int i = 0; i <= 2; i++) - { - foreach (var nic in nicInfo) - { - - int nicid = nic.deviceId; - string mac = nic.mac; - string vlan = null; - string isolationUri = nic.isolationUri; - if (isolationUri != null && isolationUri.StartsWith("vlan://") && !isolationUri.Equals("vlan://untagged")) - { - vlan = isolationUri.Substring("vlan://".Length); - int tmp; - if (!int.TryParse(vlan, out tmp)) - { - // TODO: double check exception type - errMsg = string.Format("Invalid VLAN value {0} for on vm {1} for nic uuid {2}", isolationUri, vmName, nic.uuid); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - } - if (i == 2) - { - publicIpAddress = nic.ip; - } - if (nicid == i) - { - CreateNICforVm(newVm, mac, vlan); - break; - } - } - } - - // pass the boot args for the VM using KVP component. - // We need to pass the boot args to system vm's to get them configured with cloudstack configuration. - // Add new user data - var vm = wmiCallsV2.GetComputerSystem(vmName); - if (bootArgs != null) - { - String bootargs = bootArgs; - wmiCallsV2.AddUserData(vm, bootargs); - } - - // call patch systemvm iso only for systemvms - if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) - { - patchSystemVmIso(vmName, systemVmIso); - } - - logger.DebugFormat("Starting VM {0}", vmName); - SetState(newVm, RequiredState.Enabled); - - // we need to reboot to get the hv kvp daemon get started vr gets configured. - if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) - { - System.Threading.Thread.Sleep(90000); - SetState(newVm, RequiredState.Reboot); - // wait for the second boot and then return with sucess - if (pingResource(publicIpAddress) == true) - { - } - } - - logger.InfoFormat("Started VM {0}", vmName); - return newVm; - } - - public static Boolean pingResource(String ip) - { - PingOptions pingOptions = null; - PingReply pingReply = null; - IPAddress ipAddress = null; - Ping pingSender = new Ping(); - int numberOfPings = 4; - int pingTimeout = 1000; - int byteSize = 32; - byte[] buffer = new byte[byteSize]; - ipAddress = IPAddress.Parse(ip); - pingOptions = new PingOptions(); - for (int i = 0; i < numberOfPings; i++) - { - pingReply = pingSender.Send(ipAddress, pingTimeout, buffer, pingOptions); - if (pingReply.Status == IPStatus.Success) - { - return true; - } - else - { - // wait for the second boot and then return with suces - System.Threading.Thread.Sleep(30000); - } - } - return false; - } - - /// this method is to add a dvd drive and attach the systemvm iso. - /// - - - public void patchSystemVmIso(String vmName, String systemVmIso) - { - ComputerSystem vmObject = GetComputerSystem(vmName); - AddDiskDriveToVm(vmObject, "", "1", IDE_ISO_DRIVE); - - AttachIso(vmName, systemVmIso); - } - - /// - /// Create a disk and attach it to the vm - /// - /// - /// - /// IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE - public ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) - { - logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}", - vm.ElementName, - vm.Name, - vhdfile); - - // Determine disk type for drive and assert drive type valid - string diskResourceSubType = null; - switch(driveResourceType) { - case IDE_HARDDISK_DRIVE: - diskResourceSubType = IDE_HARDDISK_DISK; - break; - case IDE_ISO_DRIVE: - diskResourceSubType = IDE_ISO_DISK; - break; - default: - var errMsg = string.Format( - "Unrecognised disk drive type {0} for VM {1} (GUID {2})", - string.IsNullOrEmpty(driveResourceType) ? "NULL": driveResourceType, - vm.ElementName, - vm.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - ManagementPath newDrivePath = AttachNewDriveToVm(vm, cntrllerAddr, driveResourceType); - - // If there's not disk to insert, we are done. - if (String.IsNullOrEmpty(vhdfile)) - { - logger.DebugFormat("No disk to be added to drive, disk drive {0} is complete", newDrivePath.Path); - } - else - { - InsertDiskImage(vm, vhdfile, diskResourceSubType, newDrivePath); - } - return newDrivePath; - } - - private ManagementPath AttachNewDriveToVm(ComputerSystem vm, string cntrllerAddr, string driveType) - { - // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. - VirtualSystemSettingData vmSettings = GetVmSettings(vm); - var ctrller = GetIDEControllerSettings(vmSettings, cntrllerAddr); - - // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type - string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", driveType); - var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery); - - // Set IDE controller and address on the controller for the new drive - newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); - newDiskDriveSettings.LateBoundObject["Address"] = "0"; - newDiskDriveSettings.CommitObject(); - - // Add this new disk drive to the VM - logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}", - newDiskDriveSettings.ResourceSubType, - newDiskDriveSettings.Parent, - newDiskDriveSettings.Address); - string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; - ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm); - - // assert - if (newDrivePaths.Length != 1) - { - var errMsg = string.Format( - "Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}", - vm.ElementName, - vm.Name, - newDrivePaths.Length, - driveType); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - logger.DebugFormat("New disk drive type {0} WMI path is {1}s", - newDiskDriveSettings.ResourceSubType, - newDrivePaths[0].Path); - return newDrivePaths[0]; - } - - /// - /// Attach iso to the vm - /// - /// - /// - private void AttachIsoToVm(ComputerSystem vm, string isoPath) - { - // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. - VirtualSystemSettingData vmSettings = GetVmSettings(vm); - var ctrller = GetDvdDriveSettings(vmSettings); - - // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type - string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", IDE_ISO_DISK); - var newDiskSettings = CloneResourceAllocationSetting(defaultDiskQuery); - - // Set IDE controller and address on the controller for the new drive - newDiskSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); - newDiskSettings.LateBoundObject["Connection"] = new string[] { isoPath }; - newDiskSettings.CommitObject(); - - // Add the new vhd object as a virtual hard disk to the vm. - string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; - ManagementPath[] newDiskPaths = AddVirtualResource(newDiskResource, vm); - // assert - if (newDiskPaths.Length != 1) - { - var errMsg = string.Format( - "Failed to add disk image to VM {0} (GUID {1}): number of resource created {2}", - vm.ElementName, - vm.Name, - newDiskPaths.Length); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ", - vm.ElementName, - vm.Name, - newDiskPaths[0].Path, - isoPath); - } - - private void InsertDiskImage(ComputerSystem vm, string vhdfile, string diskResourceSubType, ManagementPath drivePath) - { - // A description of the disk is created by modifying a clone of the default ResourceAllocationSettingData for that disk type - string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", diskResourceSubType); - var newDiskSettings = CloneResourceAllocationSetting(defaultDiskQuery); - - // Set disk drive and VHD file on disk for new disk - newDiskSettings.LateBoundObject["Parent"] = drivePath.Path; - newDiskSettings.LateBoundObject["Connection"] = new string[] { vhdfile }; - newDiskSettings.CommitObject(); - - // Add the new vhd object as a virtual hard disk to the vm. - string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; - ManagementPath[] newDiskPaths = AddVirtualResource(newDiskResource, vm); - // assert - if (newDiskPaths.Length != 1) - { - var errMsg = string.Format( - "Failed to add disk image type {3} to VM {0} (GUID {1}): number of resource created {2}", - vm.ElementName, - vm.Name, - newDiskPaths.Length, - diskResourceSubType); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ", - vm.ElementName, - vm.Name, - newDiskPaths[0].Path, - vhdfile); - } - - private ResourceAllocationSettingData CloneResourceAllocationSetting(string wmiQuery) - { - var defaultDiskDriveSettingsObjs = ResourceAllocationSettingData.GetInstances(wmiQuery); - - // assert - if (defaultDiskDriveSettingsObjs.Count != 1) - { - var errMsg = string.Format("Failed to find Msvm_ResourceAllocationSettingData for the query {0}", wmiQuery); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - ResourceAllocationSettingData defaultDiskDriveSettings = defaultDiskDriveSettingsObjs.OfType().First(); - return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); - } - - public void AttachIso(string displayName, string iso) - { - logger.DebugFormat("Got request to attach iso {0} to vm {1}", iso, displayName); - - ComputerSystem vm = GetComputerSystem(displayName); - if (vm == null) - { - logger.DebugFormat("VM {0} not found", displayName); - return; - } - else - { - AttachIsoToVm(vm, iso); - } - } - - public void DestroyVm(dynamic jsonObj) - { - string vmToDestroy = jsonObj.vmName; - DestroyVm(vmToDestroy); - } - - /// - /// Remove all VMs and all SwitchPorts with the displayName. VHD gets deleted elsewhere. - /// - /// - public void DestroyVm(string displayName) - { - logger.DebugFormat("Got request to destroy vm {0}", displayName); - - var vm = GetComputerSystem(displayName); - if ( vm == null ) - { - logger.DebugFormat("VM {0} already destroyed (or never existed)", displayName); - return; - } - - // Stop VM - logger.DebugFormat("Stop VM {0} (GUID {1})", vm.ElementName, vm.Name); - SetState(vm, RequiredState.Disabled); - - // Delete SwitchPort - DeleteSwitchPort(vm.ElementName); - - // Delete VM - var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); - ManagementPath jobPath; - - do - { - logger.DebugFormat("Delete VM {0} (GUID {1})", vm.ElementName, vm.Name); - var ret_val = virtSysMgmtSvc.DestroyVirtualSystem(vm.Path, out jobPath); - - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed Delete VM {0} (GUID {1}) due to {2}", - vm.ElementName, - vm.Name, - ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - vm = GetComputerSystem(displayName); - } - while (vm != null); - } - - public void SetState(ComputerSystem vm, ushort requiredState) - { - logger.InfoFormat( - "Changing state of {0} (GUID {1}) to {2}", - vm.ElementName, - vm.Name, - RequiredState.ToString(requiredState)); - - ManagementPath jobPath; - // TimeSpan is a value type; default ctor is equivalent to 0. - var ret_val = vm.RequestStateChange(requiredState, new TimeSpan(), out jobPath); - - // If the Job is done asynchronously - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val == 32775) - { - logger.InfoFormat("RequestStateChange returned 32775, which means vm in wrong state for requested state change. Treating as if requested state was reached"); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to change state of VM {0} (GUID {1}) to {2} due to {3}", - vm.ElementName, - vm.Name, - RequiredState.ToString(requiredState), - ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - logger.InfoFormat( - "Successfully changed vm state of {0} (GUID {1} to requested state {2}", - vm.ElementName, - vm.Name, - requiredState); - } - - - //TODO: Write method to delete SwitchPort based on Name - public bool DeleteSwitchPort(string elementName) - { - var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); - // Get NIC path - var condition = string.Format("ElementName=\"{0}\"", elementName); - var switchPortCollection = SwitchPort.GetInstances(virtSwitchMgmtSvc.Scope, condition); - if (switchPortCollection.Count == 0) - { - return true; - } - - foreach (SwitchPort port in switchPortCollection) - { - // Destroy - var ret_val = virtSwitchMgmtSvc.DeleteSwitchPort(port.Path); - - if (ret_val != ReturnCode.Completed) - { - return false; - } - } - - return true; - } - - // Add new - private ManagementPath[] AddVirtualResource(string[] resourceSettings, ComputerSystem vm ) - { - var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); - - ManagementPath jobPath; - ManagementPath[] resourcePaths; - var ret_val = virtSysMgmtSvc.AddVirtualSystemResources( - resourceSettings, - vm.Path, - out jobPath, - out resourcePaths); - - // If the Job is done asynchronously - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to add resources to VM {0} (GUID {1}) due to {2}", - vm.ElementName, - vm.Name, - ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - return resourcePaths; - } - - private ManagementPath CreateSwitchPortForVm(ComputerSystem vm, VirtualSwitchManagementService vmNetMgmtSvc, VirtualSwitch vSwitch) - { - ManagementPath newSwitchPath = null; - var ret_val = vmNetMgmtSvc.CreateSwitchPort( - vm.ElementName, - Guid.NewGuid().ToString(), - "", - vSwitch.Path, - out newSwitchPath); - // Job is always done synchronously - if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to create switch for NIC on VM {0} (GUID {1}), error code {2}", - vm.ElementName, - vm.Name, - ret_val); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - return newSwitchPath; - } - - // add vlan support by setting AccessVLAN on VLANEndpointSettingData for port - private void SetPortVlan(string vlan, VirtualSwitchManagementService vmNetMgmtSvc, ManagementPath newSwitchPath) - { - logger.DebugFormat("Setting VLAN to {0}", vlan); - - VLANEndpointSettingData vlanEndpointSettings = GetVlanEndpointSettings(vmNetMgmtSvc, newSwitchPath); - vlanEndpointSettings.LateBoundObject["AccessVLAN"] = vlan; - vlanEndpointSettings.CommitObject(); - } - - public VLANEndpointSettingData GetVlanEndpointSettings(VirtualSwitchManagementService vmNetMgmtSvc, ManagementPath newSwitchPath) - { - // Get Msvm_VLANEndpoint through associated with new Port - var vlanEndpointQuery = new RelatedObjectQuery(newSwitchPath.Path, VLANEndpoint.CreatedClassName); - var vlanEndpointSearch = new ManagementObjectSearcher(vmNetMgmtSvc.Scope, vlanEndpointQuery); - var vlanEndpointCollection = new VLANEndpoint.VLANEndpointCollection(vlanEndpointSearch.Get()); - - // assert - if (vlanEndpointCollection.Count != 1) - { - var errMsg = string.Format("No VLANs for vSwitch on Hyper-V server for switch {0}", newSwitchPath.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - VLANEndpoint vlanEndpoint = vlanEndpointCollection.OfType().First(); - - // Get Msvm_VLANEndpointSettingData assocaited with Msvm_VLANEndpoint - var vlanEndpointSettingsQuery = new RelatedObjectQuery(vlanEndpoint.Path.Path, VLANEndpointSettingData.CreatedClassName); - var vlanEndpointSettingsSearch = new ManagementObjectSearcher(vmNetMgmtSvc.Scope, vlanEndpointSettingsQuery); - var vlanEndpointSettingsCollection = new VLANEndpointSettingData.VLANEndpointSettingDataCollection(vlanEndpointSettingsSearch.Get()); - - // assert - if (vlanEndpointSettingsCollection.Count != 1) - { - var errMsg = string.Format("Internal error, VLAN for vSwitch not setup propertly Hyper-V"); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - VLANEndpointSettingData vlanEndpointSettings = vlanEndpointSettingsCollection.OfType().First(); - return vlanEndpointSettings; - } - - /// - /// External VSwitch has an external NIC, and we assume there is only one external NIC - /// - /// - /// - /// Throws if there is no vswitch - public VirtualSwitch GetExternalVirtSwitch() - { - // Work back from the first *bound* external NIC we find. - var externNICs = ExternalEthernetPort.GetInstances("IsBound = TRUE"); - - if (externNICs.Count == 0 ) - { - var errMsg = "No ExternalEthernetPort available to Hyper-V"; - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - ExternalEthernetPort externNIC = externNICs.OfType().First(); - - // A sequence of ASSOCIATOR objects need to be traversed to get from external NIC the vswitch. - // We use ManagementObjectSearcher objects to execute this sequence of questions - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var endpointQuery = new RelatedObjectQuery(externNIC.Path.Path, SwitchLANEndpoint.CreatedClassName); - var endpointSearch = new ManagementObjectSearcher(externNIC.Scope, endpointQuery); - var endpointCollection = new SwitchLANEndpoint.SwitchLANEndpointCollection(endpointSearch.Get()); - - // assert - if (endpointCollection.Count < 1 ) - { - var errMsg = string.Format("No SwitchLANEndpoint for external NIC {0} on Hyper-V server", externNIC.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - SwitchLANEndpoint endPoint = endpointCollection.OfType().First(); - var switchPortQuery = new RelatedObjectQuery(endPoint.Path.Path, SwitchPort.CreatedClassName); - var switchPortSearch = new ManagementObjectSearcher(externNIC.Scope, switchPortQuery); - var switchPortCollection = new SwitchPort.SwitchPortCollection(switchPortSearch.Get()); - - // assert - if (switchPortCollection.Count < 1 ) - { - var errMsg = string.Format("No SwitchPort for external NIC {0} on Hyper-V server", externNIC.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - SwitchPort switchPort = switchPortCollection.OfType().First(); - var vSwitchQuery = new RelatedObjectQuery(switchPort.Path.Path, VirtualSwitch.CreatedClassName); - var vSwitchSearch = new ManagementObjectSearcher(externNIC.Scope, vSwitchQuery); - var vSwitchCollection = new VirtualSwitch.VirtualSwitchCollection(vSwitchSearch.Get()); - - // assert - if (vSwitchCollection.Count < 1) - { - var errMsg = string.Format("No virtual switch for external NIC {0} on Hyper-V server", externNIC.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - VirtualSwitch vSwitch = vSwitchCollection.OfType().First(); - - return vSwitch; - } - - - private void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) - { - // Resource settings are changed through the management service - System.Management.ManagementPath jobPath; - - var ret_val = vmMgmtSvc.ModifyVirtualSystemResources(vm.Path, - resourceSettings, - out jobPath); - // If the Job is done asynchronously - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", - vm.ElementName, - vm.Name, - ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - } - - private ComputerSystem CreateDefaultVm(VirtualSystemManagementService vmMgmtSvc, string name) - { - // Tweak default settings by basing new VM on default global setting object - // with designed display name. - - VirtualSystemGlobalSettingData vs_gs_data = VirtualSystemGlobalSettingData.CreateInstance(); - vs_gs_data.LateBoundObject["ElementName"] = name; - - System.Management.ManagementPath jobPath; - System.Management.ManagementPath defined_sys; - var ret_val = vmMgmtSvc.DefineVirtualSystem( - new string[0], - null, - vs_gs_data.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20), - out defined_sys, - out jobPath); - - // If the Job is done asynchronously - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to create VM {0} due to {1} (DefineVirtualSystem call)", - name, ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - logger.DebugFormat(CultureInfo.InvariantCulture, "Created VM {0}", name); - - // Is the defined_system real? - var vm = new ComputerSystem(defined_sys); - - // Assertion - if (vm.ElementName.CompareTo(name) != 0) - { - var errMsg = string.Format( - "New VM created with wrong name (is {0}, should be {1}, GUID {2})", - vm.ElementName, - name, - vm.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - return vm; - } - - public VirtualSwitchManagementService GetVirtualSwitchManagementService() - { - // VirtualSwitchManagementService is a singleton, most anonymous way of lookup is by asking for the set - // of local instances, which should be size 1. - var virtSwtichSvcCollection = VirtualSwitchManagementService.GetInstances(); - foreach (VirtualSwitchManagementService item in virtSwtichSvcCollection) - { - return item; - } - - var errMsg = string.Format("No Hyper-V subsystem on server"); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - public void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path) - { - // Resource settings are changed through the management service - System.Management.ManagementPath jobPath; - var imgMgr = GetImageManagementService(); - var ret_val = imgMgr.CreateDynamicVirtualHardDisk(MaxInternalSize, Path, out jobPath); - // If the Job is done asynchronously - if (ret_val == ReturnCode.Started) - { - JobCompleted(jobPath); - } - else if (ret_val != ReturnCode.Completed) - { - var errMsg = string.Format( - "Failed to CreateDynamicVirtualHardDisk size {0}, path {1} to {2}", - MaxInternalSize, - Path, - ReturnCode.ToString(ret_val)); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - } - - public ImageManagementService GetImageManagementService() - { - // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set - // of local instances, which should be size 1. - - var coll = ImageManagementService.GetInstances(); - foreach (ImageManagementService item in coll) - { - return item; - } - - var errMsg = string.Format("No Hyper-V subsystem on server"); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - - public VirtualSystemManagementService GetVirtualisationSystemManagementService() - { - // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set - // of local instances, which should be size 1. - - var virtSysMgmtSvcCollection = VirtualSystemManagementService.GetInstances(); - foreach (VirtualSystemManagementService item in virtSysMgmtSvcCollection) - { - return item; - } - - var errMsg = string.Format("No Hyper-V subsystem on server"); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - /// - /// Similar to http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx - /// - /// - /// - private void JobCompleted(ManagementPath jobPath) - { - ConcreteJob jobObj = null; - for(;;) - { - jobObj = new ConcreteJob(jobPath); - if (jobObj.JobState != JobState.Starting && jobObj.JobState != JobState.Running) - { - break; - } - logger.InfoFormat("In progress... {0}% completed.", jobObj.PercentComplete); - System.Threading.Thread.Sleep(1000); - } - - if (jobObj.JobState != JobState.Completed) - { - var errMsg = string.Format( - "Hyper-V Job failed, Error Code:{0}, Description: {1}", - jobObj.ErrorCode, - jobObj.ErrorDescription); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - logger.DebugFormat("WMI job succeeded: {0}, Elapsed={1}", jobObj.Description, jobObj.ElapsedTime); - } - - public void GetProcessorResources(out uint cores, out uint mhz) - { - // Processor processors - cores = 0; - mhz = 0; - Processor.ProcessorCollection procCol = Processor.GetInstances(); - foreach (Processor procInfo in procCol) - { - cores += procInfo.NumberOfCores; - mhz = procInfo.MaxClockSpeed; - } - } - - public void GetProcessorUsageInfo(out double cpuUtilization) - { - PerfFormattedData_Counters_ProcessorInformation.PerfFormattedData_Counters_ProcessorInformationCollection coll = - PerfFormattedData_Counters_ProcessorInformation.GetInstances("Name=\"_Total\""); - cpuUtilization = 100; - // Use the first one - foreach (PerfFormattedData_Counters_ProcessorInformation procInfo in coll) - { - // Idle during a given internal - // See http://library.wmifun.net/cimv2/win32_perfformatteddata_counters_processorinformation.html - cpuUtilization = 100.0 - (double)procInfo.PercentIdleTime; - } - } - - - public void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs) - { - OperatingSystem0 os = new OperatingSystem0(); - physicalRamKBs = os.TotalVisibleMemorySize; - freeMemoryKBs = os.FreePhysicalMemory; - } - - public string GetDefaultVirtualDiskFolder() - { - VirtualSystemManagementServiceSettingData.VirtualSystemManagementServiceSettingDataCollection coll = VirtualSystemManagementServiceSettingData.GetInstances(); - string defaultVirtualHardDiskPath = null; - foreach (VirtualSystemManagementServiceSettingData settings in coll) - { - return settings.DefaultVirtualHardDiskPath; - } - - // assert - if (!System.IO.Directory.Exists(defaultVirtualHardDiskPath) ){ - var errMsg = string.Format( - "Hyper-V DefaultVirtualHardDiskPath is invalid!"); - logger.Error(errMsg); - return null; - } - - return defaultVirtualHardDiskPath; - } - - public ComputerSystem GetComputerSystem(string displayName) - { - var wmiQuery = String.Format("ElementName=\"{0}\"", displayName); - ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances(wmiQuery); - - // Return the first one - foreach (ComputerSystem vm in vmCollection) - { - return vm; - } - return null; - } - - public List GetVmElementNames() - { - List result = new List(); - ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances(); - - // Return the first one - foreach (ComputerSystem vm in vmCollection) - { - if (vm.Caption.StartsWith("Hosting Computer System") ) - { - continue; - } - result.Add(vm.ElementName); - } - return result; - } - - public ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings) - { - // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the - // ProcessorSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); - // - var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ProcessorSettingData.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); - var wmiObjCollection = new ProcessorSettingData.ProcessorSettingDataCollection(wmiObjectSearch.Get()); - - foreach (ProcessorSettingData wmiObj in wmiObjCollection) - { - return wmiObj; - } - - var errMsg = string.Format("No ProcessorSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - public MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings) - { - // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the - // MemorySettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); - // - var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, MemorySettingData.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); - var wmiObjCollection = new MemorySettingData.MemorySettingDataCollection(wmiObjectSearch.Get()); - - foreach (MemorySettingData wmiObj in wmiObjCollection) - { - return wmiObj; - } - - var errMsg = string.Format("No MemorySettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - public ResourceAllocationSettingData GetDvdDriveSettings(VirtualSystemSettingData vmSettings) - { - var wmiObjCollection = GetResourceAllocationSettings(vmSettings); - - foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) - { - if (wmiObj.ResourceType == 16) - { - return wmiObj; - } - } - - var errMsg = string.Format( - "Cannot find the Dvd drive in VirtualSystemSettingData {0}", - vmSettings.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - public ResourceAllocationSettingData GetIDEControllerSettings(VirtualSystemSettingData vmSettings, string cntrllerAddr) - { - var wmiObjCollection = GetResourceAllocationSettings(vmSettings); - - foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) - { - if (wmiObj.ResourceSubType == "Microsoft Emulated IDE Controller" && wmiObj.Address == cntrllerAddr) - { - return wmiObj; - } - } - - var errMsg = string.Format( - "Cannot find the Microsoft Emulated IDE Controlle at address {0} in VirtualSystemSettingData {1}", - cntrllerAddr, - vmSettings.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - /// - /// VM resources, typically hardware a described by a generic MSVM_ResourceAllocationSettingData object. The hardware type being - /// described is identified in two ways: in general terms using an enum in the ResourceType field, and in terms of the implementation - /// using text in the ResourceSubType field. - /// See http://msdn.microsoft.com/en-us/library/cc136877%28v=vs.85%29.aspx - /// - /// - /// - public ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings) - { - // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the - // ResourceAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); - // - var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ResourceAllocationSettingData.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); - var wmiObjCollection = new ResourceAllocationSettingData.ResourceAllocationSettingDataCollection(wmiObjectSearch.Get()); - - if (wmiObjCollection != null) - { - return wmiObjCollection; - } - - var errMsg = string.Format("No ResourceAllocationSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - public SwitchPort[] GetSwitchPorts(ComputerSystem vm) - { - var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); - // Get NIC path - var condition = string.Format("ElementName=\"{0}\"", vm.ElementName); - var switchPortCollection = SwitchPort.GetInstances(virtSwitchMgmtSvc.Scope, condition); - - List result = new List(switchPortCollection.Count); - foreach (SwitchPort item in switchPortCollection) - { - result.Add(item); - } - return result.ToArray(); - } - - - /// - /// Deprecated - /// - /// - /// - public SwitchPort GetSwitchPort(SyntheticEthernetPort nic) - { - // An ASSOCIATOR object provides the cross reference between WMI objects, - // but generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", wmiObject.path, resultclassName); - // - var wmiObjQuery = new RelatedObjectQuery(nic.Path.Path, VmLANEndpoint.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(nic.Scope, wmiObjQuery); - var wmiObjCollection = new VmLANEndpoint.VmLANEndpointCollection(wmiObjectSearch.Get()); - - // assert - if (wmiObjCollection.Count < 1) - { - var errMsg = string.Format("No VmLANEndpoint for external NIC {0} on Hyper-V server", nic.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - VmLANEndpoint vmEndPoint = wmiObjCollection.OfType().First(); - var switchPortQuery = new RelatedObjectQuery(vmEndPoint.Path.Path, SwitchPort.CreatedClassName); - var switchPortSearch = new ManagementObjectSearcher(nic.Scope, switchPortQuery); - var switchPortCollection = new SwitchPort.SwitchPortCollection(switchPortSearch.Get()); - - // assert - if (switchPortCollection.Count < 1) - { - var errMsg = string.Format("No SwitchPort for external NIC {0} on Hyper-V server", nic.Name); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - - SwitchPort switchPort = wmiObjCollection.OfType().First(); - - return switchPort; - } - - public SyntheticEthernetPortSettingData[] GetEthernetPorts(ComputerSystem vm) - { - // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the - // SyntheticEthernetPortSettingData, via the VirtualSystemSettingData. - // However, generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); - // - VirtualSystemSettingData vmSettings = GetVmSettings(vm); - - var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); - var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); - - List results = new List(wmiObjCollection.Count); - foreach (SyntheticEthernetPortSettingData item in wmiObjCollection) - { - results.Add(item); - } - - return results.ToArray(); - } - - public VirtualSystemSettingData GetVmSettings(ComputerSystem vm) - { - // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the - // VirtualSystemSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. - // Instead, we use the System.Management to code the equivalant of - // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); - // - var wmiObjQuery = new RelatedObjectQuery(vm.Path.Path, VirtualSystemSettingData.CreatedClassName); - - // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain - // the virtualisation objects. - var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); - var wmiObjCollection = new VirtualSystemSettingData.VirtualSystemSettingDataCollection(wmiObjectSearch.Get()); - - // When snapshots are taken into account, there can be multiple settings objects - // take the first one that isn't a snapshot - foreach (VirtualSystemSettingData wmiObj in wmiObjCollection) - { - if (wmiObj.SettingType == 3) - { - return wmiObj; - } - } - - var errMsg = string.Format("No VirtualSystemSettingData for VM {0}, path {1}", vm.ElementName, vm.Path.Path); - var ex = new WmiException(errMsg); - logger.Error(errMsg, ex); - throw ex; - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs index 6afa7887694..5a9d58675e8 100755 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs @@ -39,15 +39,13 @@ namespace HypervResource // Trigger assembly load into curren appdomain } + private static ILog logger = LogManager.GetLogger(typeof(WmiCallsV2)); + /// /// Returns ping status of the given ip /// - - private static ILog logger = LogManager.GetLogger(typeof(WmiCallsV2)); - public static String PingHost(String ip) { - return "Success"; } @@ -91,10 +89,1097 @@ namespace HypervResource return vm; } - + /// /// Returns ComputerSystem lacking any NICs and VOLUMEs /// + public ComputerSystem CreateVM(string name, long memory_mb, int vcpus) + { + // Obtain controller for Hyper-V virtualisation subsystem + VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); + + // Create VM with correct name and default resources + ComputerSystem vm = CreateDefaultVm(vmMgmtSvc, name); + + // Update the resource settings for the VM. + + // Resource settings are referenced through the Msvm_VirtualSystemSettingData object. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + // For memory settings, there is no Dynamic Memory, so reservation, limit and quantity are identical. + MemorySettingData memSettings = GetMemSettings(vmSettings); + memSettings.LateBoundObject["VirtualQuantity"] = memory_mb; + memSettings.LateBoundObject["Reservation"] = memory_mb; + memSettings.LateBoundObject["Limit"] = memory_mb; + + // Update the processor settings for the VM, static assignment of 100% for CPU limit + ProcessorSettingData procSettings = GetProcSettings(vmSettings); + procSettings.LateBoundObject["VirtualQuantity"] = vcpus; + procSettings.LateBoundObject["Reservation"] = vcpus; + procSettings.LateBoundObject["Limit"] = 100000; + + ModifyVmResources(vmMgmtSvc, vm, new String[] { + memSettings.LateBoundObject.GetText(TextFormat.CimDtd20), + procSettings.LateBoundObject.GetText(TextFormat.CimDtd20) + }); + logger.InfoFormat("VM with display name {0} has GUID {1}", vm.ElementName, vm.Name); + logger.DebugFormat("Resources for vm {0}: {1} MB memory, {2} vcpus", name, memory_mb, vcpus); + + return vm; + } + + /// + /// Create a (synthetic) nic, and attach it to the vm + /// + /// + /// + /// + /// + public SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac) + { + logger.DebugFormat("Creating nic for VM {0} (GUID {1})", vm.ElementName, vm.Name); + + // Obtain controller for Hyper-V networking subsystem + var vmNetMgmtSvc = GetVirtualSwitchManagementService(); + + // Create NIC resource by cloning the default NIC + var synthNICsSettings = SyntheticEthernetPortSettingData.GetInstances(vmNetMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); + + // Assert + if (synthNICsSettings.Count != 1) + { + var errMsg = string.Format("Internal error, coudl not find default SyntheticEthernetPort instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + var defaultSynthNICSettings = synthNICsSettings.OfType().First(); + + var newSynthNICSettings = new SyntheticEthernetPortSettingData((ManagementBaseObject)defaultSynthNICSettings.LateBoundObject.Clone()); + + // Assign configuration to new NIC + string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' }))); + newSynthNICSettings.LateBoundObject["ElementName"] = vm.ElementName; + newSynthNICSettings.LateBoundObject["Address"] = normalisedMAC; + newSynthNICSettings.LateBoundObject["StaticMacAddress"] = "TRUE"; + newSynthNICSettings.LateBoundObject["VirtualSystemIdentifiers"] = new string[] { "{" + Guid.NewGuid().ToString() + "}" }; + newSynthNICSettings.CommitObject(); + + // Insert NIC into vm + string[] newResources = new string[] { newSynthNICSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20)}; + ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm ); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newResourcePaths.Length); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return new SyntheticEthernetPortSettingData(newResourcePaths[0]); + } + + public const string IDE_HARDDISK_CONTROLLER = "Microsoft:Hyper-V:Emulated IDE Controller"; + public const string IDE_HARDDISK_DRIVE = "Microsoft:Hyper-V:Synthetic Disk Drive"; + public const string IDE_ISO_DRIVE = "Microsoft:Hyper-V:Synthetic DVD Drive"; + + // TODO: names harvested from Msvm_ResourcePool, not clear how to create new instances + public const string IDE_ISO_DISK = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE + public const string IDE_HARDDISK_DISK = "Microsoft:Hyper-V:Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE + + /// + /// Create new VM. By default we start it. + /// + public ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso) + { + var vmInfo = jsonObj.vm; + string vmName = vmInfo.name; + var nicInfo = vmInfo.nics; + int vcpus = vmInfo.cpus; + int memSize = vmInfo.maxRam / 1048576; + string errMsg = vmName; + var diskDrives = vmInfo.disks; + var bootArgs = vmInfo.bootArgs; + + // assert + errMsg = vmName + ": missing disk information, array empty or missing, agent expects *at least* one disk for a VM"; + if (diskDrives == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + // assert + errMsg = vmName + ": missing NIC information, array empty or missing, agent expects at least an empty array."; + if (nicInfo == null ) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + + // For existing VMs, return when we spot one of this name not stopped. In the meantime, remove any existing VMs of same name. + ComputerSystem vmWmiObj = null; + while ((vmWmiObj = GetComputerSystem(vmName)) != null) + { + logger.WarnFormat("Create request for existing vm, name {0}", vmName); + if (vmWmiObj.EnabledState == EnabledState.Disabled) + { + logger.InfoFormat("Deleting existing VM with name {0}, before we go on to create a VM with the same name", vmName); + DestroyVm(vmName); + } + else + { + // TODO: revise exception type + errMsg = string.Format("Create VM failing, because there exists a VM with name {0}, state {1}", + vmName, + EnabledState.ToString(vmWmiObj.EnabledState)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + // Create vm carcase + logger.DebugFormat("Going ahead with create VM {0}, {1} vcpus, {2}MB RAM", vmName, vcpus, memSize); + var newVm = CreateVM(vmName, memSize, vcpus); + + foreach (var diskDrive in diskDrives) + { + string vhdFile = null; + string diskName = null; + VolumeObjectTO volInfo = VolumeObjectTO.ParseJson(diskDrive.data); + if (volInfo != null) + { + // assert + errMsg = vmName + ": volume missing primaryDataStore for disk " + diskDrive.ToString(); + if (volInfo.primaryDataStore == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + diskName = volInfo.name; + + // assert + errMsg = vmName + ": can't deal with DataStore type for disk " + diskDrive.ToString(); + if (volInfo.primaryDataStore == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + errMsg = vmName + ": Malformed PrimaryDataStore for disk " + diskDrive.ToString(); + if (String.IsNullOrEmpty(volInfo.primaryDataStore.path)) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + errMsg = vmName + ": Missing folder PrimaryDataStore for disk " + diskDrive.ToString() + ", missing path: " + volInfo.primaryDataStore.path; + if (!Directory.Exists(volInfo.primaryDataStore.path)) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + vhdFile = volInfo.FullFileName; + if (!System.IO.File.Exists(vhdFile)) + { + errMsg = vmName + ": non-existent volume, missing " + vhdFile + " for drive " + diskDrive.ToString(); + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + logger.Debug("Going to create " + vmName + " with attached voluem " + diskName + " at " + vhdFile); + } + + string driveType = diskDrive.type; + + string ideCtrllr = "0"; + string driveResourceType = null; + switch (driveType) { + case "ROOT": + ideCtrllr = "0"; + driveResourceType = IDE_HARDDISK_DRIVE; + break; + case "ISO": + ideCtrllr = "1"; + driveResourceType = IDE_ISO_DRIVE; + break; + default: + // TODO: double check exception type + errMsg = string.Format("Unknown disk type {0} for disk {1}, vm named {2}", + string.IsNullOrEmpty(driveType) ? "NULL" : driveType, + string.IsNullOrEmpty(diskName) ? "NULL" : diskName, vmName); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName, + string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" +vhdFile ); + AddDiskDriveToVm(newVm, vhdFile, ideCtrllr, driveResourceType); + } + + // Add the Nics to the VM in the deviceId order. + for (int i = 0; i <= 2; i++) + { + foreach (var nic in nicInfo) + { + + int nicid = nic.deviceId; + string mac = nic.mac; + string vlan = null; + string isolationUri = nic.isolationUri; + if (isolationUri != null && isolationUri.StartsWith("vlan://") && !isolationUri.Equals("vlan://untagged")) + { + vlan = isolationUri.Substring("vlan://".Length); + int tmp; + if (!int.TryParse(vlan, out tmp)) + { + // TODO: double check exception type + errMsg = string.Format("Invalid VLAN value {0} for on vm {1} for nic uuid {2}", isolationUri, vmName, nic.uuid); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + if (nicid == i) + { + // Create network adapter + var newAdapter = CreateNICforVm(newVm, mac); + + // connection to vswitch + var portSettings = AttachNicToPort(newVm, newAdapter); + + // set vlan + if (vlan != null) + { + SetPortVlan(vlan, portSettings); + } + + logger.DebugFormat("Created adapter {0} on port {1}, {2}", + newAdapter.Path, portSettings.Path, (vlan == null ? "No VLAN" : "VLAN " + vlan)); + } + } + } + + // pass the boot args for the VM using KVP component. + // We need to pass the boot args to system vm's to get them configured with cloudstack configuration. + // Add new user data + var vm = GetComputerSystem(vmName); + if (bootArgs != null && !String.IsNullOrEmpty((string)bootArgs)) + { + + String bootargs = bootArgs; + AddUserData(vm, bootargs); + + + // Get existing KVP + //var vmSettings = GetVmSettings(vm); + //var kvpInfo = GetKvpSettings(vmSettings); + //logger.DebugFormat("Boot Args presisted on the VM are ", kvpInfo); + //AddUserData(vm, bootargs); + + // Verify key added to subsystem + //kvpInfo = GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + //kvpProps = kvpInfo.HostExchangeItems; + + } + // call patch systemvm iso only for systemvms + if (vmName.StartsWith("r-")) + { + patchSystemVmIso(vmName, systemVmIso); + } + + logger.DebugFormat("Starting VM {0}", vmName); + SetState(newVm, RequiredState.Enabled); + + // we need to reboot to get the hv kvp daemon get started vr gets configured. + if (vmName.StartsWith("r-")) + { + System.Threading.Thread.Sleep(90000); + SetState(newVm, RequiredState.Reboot); + // wait for the second boot and then return with suces + System.Threading.Thread.Sleep(50000); + } + logger.InfoFormat("Started VM {0}", vmName); + return newVm; + } + + private EthernetPortAllocationSettingData AttachNicToPort(ComputerSystem newVm, SyntheticEthernetPortSettingData newAdapter) + { + // Get the virtual switch + VirtualEthernetSwitch vSwitch = GetExternalVirtSwitch(); + + // Create port for adapter + var defaultEthernetPortSettings = EthernetPortAllocationSettingData.GetInstances(vSwitch.Scope, "InstanceID LIKE \"%Default\""); + + // assert + if (defaultEthernetPortSettings.Count != 1) + { + var errMsg = string.Format("Internal error, coudl not find default EthernetPortAllocationSettingData instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + var defaultEthernetPortSettingsObj = defaultEthernetPortSettings.OfType().First(); + var newEthernetPortSettings = new EthernetPortAllocationSettingData((ManagementBaseObject)defaultEthernetPortSettingsObj.LateBoundObject.Clone()); + newEthernetPortSettings.LateBoundObject["Parent"] = newAdapter.Path.Path; + newEthernetPortSettings.LateBoundObject["HostResource"] = new string[] { vSwitch.Path.Path }; + + // Insert NIC into vm + string[] newResources = new string[] { newEthernetPortSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newResourcePaths = AddVirtualResource(newResources, newVm); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", + newVm.ElementName, + newVm.Name, + newResourcePaths.Length); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return new EthernetPortAllocationSettingData(newResourcePaths[0]); + } + + /// this method is to add a dvd drive and attach the systemvm iso. + /// + public void patchSystemVmIso(String vmName, String systemVmIso) + { + ComputerSystem vmObject = GetComputerSystem(vmName); + AddDiskDriveToVm(vmObject, "", "1", IDE_ISO_DRIVE); + AttachIso(vmName, systemVmIso); + } + + + /// + /// + /// + /// IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE + public ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) + { + logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}", + vm.ElementName, + vm.Name, + vhdfile); + + // Determine disk type for drive and assert drive type valid + string diskResourceSubType = null; + switch(driveResourceType) { + case IDE_HARDDISK_DRIVE: + diskResourceSubType = IDE_HARDDISK_DISK; + break; + case IDE_ISO_DRIVE: + diskResourceSubType = IDE_ISO_DISK; + break; + default: + var errMsg = string.Format( + "Unrecognised disk drive type {0} for VM {1} (GUID {2})", + string.IsNullOrEmpty(driveResourceType) ? "NULL": driveResourceType, + vm.ElementName, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ManagementPath newDrivePath = AttachNewDriveToVm(vm, cntrllerAddr, driveResourceType); + + // If there's not disk to insert, we are done. + if (String.IsNullOrEmpty(vhdfile)) + { + logger.DebugFormat("No disk to be added to drive, disk drive {0} is complete", newDrivePath.Path); + } + else + { + InsertDiskImage(vm, vhdfile, diskResourceSubType, newDrivePath); + } + return newDrivePath; + } + + + public void DetachDisk(string displayName, string diskFileName) + { + logger.DebugFormat("Got request to detach virtual disk {0} from vm {1}", diskFileName, displayName); + + ComputerSystem vm = GetComputerSystem(displayName); + if (vm == null) + { + logger.DebugFormat("VM {0} not found", displayName); + return; + } + else + { + RemoveStorageImageFromVm(vm, diskFileName); + } + } + + /// + /// Removes a disk image from a drive, but does not remove the drive itself. + /// + /// + /// + private void RemoveStorageImageFromVm(ComputerSystem vm, string diskFileName) + { + // Obtain StorageAllocationSettingData for disk + StorageAllocationSettingData.StorageAllocationSettingDataCollection storageSettingsObjs = StorageAllocationSettingData.GetInstances(); + + StorageAllocationSettingData imageToRemove = null; + foreach (StorageAllocationSettingData item in storageSettingsObjs) + { + if (item.HostResource == null || item.HostResource.Length != 1) + { + continue; + } + + string hostResource = item.HostResource[0]; + if (!hostResource.Equals(diskFileName)) + { + continue; + } + imageToRemove = item; + } + + // assert + if (imageToRemove == null) + { + var errMsg = string.Format( + "Failed to remove disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", + diskFileName, + vm.ElementName, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + RemoveStorageResource(imageToRemove.Path, vm); + + logger.InfoFormat("REmoved disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", + diskFileName, + vm.ElementName, + vm.Name); + } + + private ManagementPath AttachNewDriveToVm(ComputerSystem vm, string cntrllerAddr, string driveType) + { + // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var ctrller = GetIDEControllerSettings(vmSettings, cntrllerAddr); + + // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type + string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", driveType); + var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery); + + // Set IDE controller and address on the controller for the new drive + newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); + newDiskDriveSettings.LateBoundObject["AddressOnParent"] = "0"; + newDiskDriveSettings.CommitObject(); + + // Add this new disk drive to the VM + logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}", + newDiskDriveSettings.ResourceSubType, + newDiskDriveSettings.Parent, + newDiskDriveSettings.AddressOnParent); + string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm); + + // assert + if (newDrivePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newDrivePaths.Length, + driveType); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.DebugFormat("New disk drive type {0} WMI path is {1}s", + newDiskDriveSettings.ResourceSubType, + newDrivePaths[0].Path); + return newDrivePaths[0]; + } + + + private void InsertDiskImage(ComputerSystem vm, string diskImagePath, string diskResourceSubType, ManagementPath drivePath) + { + // A description of the disk is created by modifying a clone of the default ResourceAllocationSettingData for that disk type + string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", diskResourceSubType); + var newDiskSettings = CloneStorageAllocationSetting(defaultDiskQuery); + + // Set file containing the disk image + newDiskSettings.LateBoundObject["Parent"] = drivePath.Path; + + // V2 API uses HostResource to specify image, see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx + newDiskSettings.LateBoundObject["HostResource"] = new string[] { diskImagePath }; + newDiskSettings.CommitObject(); + + // Add the new Msvm_StorageAllocationSettingData object as a virtual hard disk to the vm. + string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newDiskPaths = AddStorageResource(newDiskResource, vm); + // assert + if (newDiskPaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add disk image type {3} to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newDiskPaths.Length, + diskResourceSubType); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ", + vm.ElementName, + vm.Name, + newDiskPaths[0].Path, + diskImagePath); + } + + /// + /// Create Msvm_StorageAllocationSettingData corresponding to the ISO image, and + /// associate this with the VM's DVD drive. + /// + private void AttachIsoToVm(ComputerSystem vm, string isoPath) + { + // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var driveWmiObj = GetDvdDriveSettings(vmSettings); + + InsertDiskImage(vm, isoPath, IDE_ISO_DISK, driveWmiObj.Path); + } + + + + private static ResourceAllocationSettingData CloneResourceAllocationSetting(string wmiQuery) + { + var defaultDiskDriveSettingsObjs = ResourceAllocationSettingData.GetInstances(wmiQuery); + + // assert + if (defaultDiskDriveSettingsObjs.Count != 1) + { + var errMsg = string.Format("Failed to find Msvm_ResourceAllocationSettingData for the query {0}", wmiQuery); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ResourceAllocationSettingData defaultDiskDriveSettings = defaultDiskDriveSettingsObjs.OfType().First(); + return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); + } + + public void AttachIso(string displayName, string iso) + { + logger.DebugFormat("Got request to attach iso {0} to vm {1}", iso, displayName); + + ComputerSystem vm = GetComputerSystem(displayName); + if (vm == null) + { + logger.DebugFormat("VM {0} not found", displayName); + return; + } + else + { + AttachIsoToVm(vm, iso); + } + } + + public void DestroyVm(dynamic jsonObj) + { + string vmToDestroy = jsonObj.vmName; + DestroyVm(vmToDestroy); + } + + /// + /// Remove all VMs and all SwitchPorts with the displayName. VHD gets deleted elsewhere. + /// + /// + public void DestroyVm(string displayName) + { + logger.DebugFormat("Got request to destroy vm {0}", displayName); + + var vm = GetComputerSystem(displayName); + if ( vm == null ) + { + logger.DebugFormat("VM {0} already destroyed (or never existed)", displayName); + return; + } + + // Stop VM + logger.DebugFormat("Stop VM {0} (GUID {1})", vm.ElementName, vm.Name); + SetState(vm, RequiredState.Disabled); + + // Delete SwitchPort + logger.DebugFormat("Remove associated switch ports for VM {0} (GUID {1})", vm.ElementName, vm.Name); + DeleteSwitchPort(vm.ElementName); + + // Delete VM + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + ManagementPath jobPath; + + do + { + logger.DebugFormat("Delete VM {0} (GUID {1})", vm.ElementName, vm.Name); + var ret_val = virtSysMgmtSvc.DestroySystem(vm.Path, out jobPath); + + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed Delete VM {0} (GUID {1}) due to {2}", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + vm = GetComputerSystem(displayName); + } + while (vm != null); + } + + /// + /// Create new storage media resources, e.g. hard disk images and ISO disk images + /// see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx + /// + /// + /// + private static StorageAllocationSettingData CloneStorageAllocationSetting(string wmiQuery) + { + var defaultDiskImageSettingsObjs = StorageAllocationSettingData.GetInstances(wmiQuery); + + // assert + if (defaultDiskImageSettingsObjs.Count != 1) + { + var errMsg = string.Format("Failed to find Msvm_StorageAllocationSettingData for the query {0}", wmiQuery); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + StorageAllocationSettingData defaultDiskDriveSettings = defaultDiskImageSettingsObjs.OfType().First(); + return new StorageAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); + } + + /// < summary> + /// Removes a storage resource from a computer system. + /// + /// Path that uniquely identifies the resource. + /// VM to which the disk image will be attached. + // Add new + private void RemoveNetworkResource(ManagementPath resourcePath) + { + var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); + ManagementPath jobPath; + var ret_val = virtSwitchMgmtSvc.RemoveResourceSettings( + new ManagementPath[] { resourcePath }, + out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to remove network resources {0} from switch due to {1}", + resourcePath.Path, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + /// < summary> + /// Removes a storage resource from a computer system. + /// + /// Path that uniquely identifies the resource. + /// VM to which the disk image will be attached. + private void RemoveStorageResource(ManagementPath resourcePath, ComputerSystem vm) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + var ret_val = virtSysMgmtSvc.RemoveResourceSettings( + new ManagementPath[] { resourcePath }, + out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to remove resource {0} from VM {1} (GUID {2}) due to {3}", + resourcePath.Path, + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + public void SetState(ComputerSystem vm, ushort requiredState) + { + logger.InfoFormat( + "Changing state of {0} (GUID {1}) to {2}", + vm.ElementName, + vm.Name, + RequiredState.ToString(requiredState)); + + ManagementPath jobPath; + // DateTime is unused + var ret_val = vm.RequestStateChange(requiredState, new DateTime(), out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val == 32775) + { // TODO: check + logger.InfoFormat("RequestStateChange returned 32775, which means vm in wrong state for requested state change. Treating as if requested state was reached"); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to change state of VM {0} (GUID {1}) to {2} due to {3}", + vm.ElementName, + vm.Name, + RequiredState.ToString(requiredState), + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + logger.InfoFormat( + "Successfully changed vm state of {0} (GUID {1} to requested state {2}", + vm.ElementName, + vm.Name, + requiredState); + } + + + //TODO: Write method to delete SwitchPort based on Name + /// + /// Delete switch port by removing settings from the switch + /// + /// + /// + public void DeleteSwitchPort(string elementName) + { + // Get NIC path + var condition = string.Format("ElementName=\"{0}\"", elementName); + var virtSwitchMgmtSvc = GetVirtualSwitchManagementService(); + + var switchPortCollection = EthernetSwitchPort.GetInstances(virtSwitchMgmtSvc.Scope, condition); + if (switchPortCollection.Count == 0) + { + return; + } + + foreach (EthernetSwitchPort port in switchPortCollection) + { + var settings = GetSyntheticEthernetPortSettings(port); + RemoveNetworkResource(settings.Path); + } + } + + public SyntheticEthernetPortSettingData GetSyntheticEthernetPortSettings(EthernetSwitchPort port) + { + // An ASSOCIATOR object provides the cross reference from the EthernetSwitchPort and the + // SyntheticEthernetPortSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(port.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(port.Scope, wmiObjQuery); + var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); + + // When snapshots are taken into account, there can be multiple settings objects + // take the first one that isn't a snapshot + foreach (SyntheticEthernetPortSettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No SyntheticEthernetPortSettingData for port {0}, path {1}", port.ElementName, port.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// Adds storage images to coputer system (disk image, iso image). + /// + /// Msvm_StorageAllocationSettings with HostResource configured with image + /// file and Parent set to a controller associated with the ComputerSystem + /// VM to which the disk image will be attached. + // Add new + private ManagementPath[] AddStorageResource(string[] storageSettings, ComputerSystem vm) + { + return AddVirtualResource(storageSettings, vm); + } + + private ManagementPath[] AddVirtualResource(string[] resourceSettings, ComputerSystem vm ) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + ManagementPath[] resourcePaths; + var ret_val = virtSysMgmtSvc.AddResourceSettings( + vm.Path, + resourceSettings, + out jobPath, + out resourcePaths); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to add resources to VM {0} (GUID {1}) due to {2}", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return resourcePaths; + } + + private ManagementPath[] AddFeatureSettings(string[] featureSettings, ManagementPath affectedConfiguration) + { + var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); + + ManagementPath jobPath; + ManagementPath[] resultSettings; + var ret_val = virtSysMgmtSvc.AddFeatureSettings( + affectedConfiguration, + featureSettings, + out jobPath, + out resultSettings); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to add features settings {0} to resource {1} due to {2}", + featureSettings, + affectedConfiguration, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return resultSettings; + } + + private ManagementPath SetPortVlan(string vlan, EthernetPortAllocationSettingData portPath) + { + logger.DebugFormat("Setting VLAN to {0}", vlan); + + var vmVirtMgmtSvc = GetVirtualisationSystemManagementService(); + EthernetSwitchPortVlanSettingData.GetInstances(); + + // Create NIC resource by cloning the default NIC + var vlanSettings = EthernetSwitchPortVlanSettingData.GetInstances(vmVirtMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); + + // Assert + if (vlanSettings.Count != 1) + { + var errMsg = string.Format("Internal error, could not find default EthernetSwitchPortVlanSettingData instance"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + var defaultVlanSettings = vlanSettings.OfType().First(); + + var newVlanSettings = new EthernetSwitchPortVlanSettingData((ManagementBaseObject)defaultVlanSettings.LateBoundObject.Clone()); + + // Assign configuration to new NIC + newVlanSettings.LateBoundObject["AccessVlanId"] = vlan; + newVlanSettings.LateBoundObject["OperationMode"] = 1; // Access=1, trunk=2, private=3 ; + newVlanSettings.CommitObject(); + + // Insert NIC into vm + string[] newResources = new string[] { newVlanSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newResourcePaths = AddFeatureSettings(newResources, portPath.Path); + + // assert + if (newResourcePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to properly set VLAN to {0} for NIC on port {1}", + vlan, + portPath.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return newResourcePaths[0]; + } + + + /// + /// External VSwitch has an external NIC, and we assume there is only one external NIC and one external vswitch. + /// + /// + /// + /// Throws if there is no vswitch + /// + /// With V1 API, external ethernet port was attached to the land endpoint, which was attached to the switch. + /// e.g. Msvm_ExternalEthernetPort -> SwitchLANEndpoint -> SwitchPort -> VirtualSwitch + /// + /// With V2 API, there are two kinds of lan endpoint: one on the computer system and one on the switch + /// e.g. Msvm_ExternalEthernetPort -> LANEndpoint -> LANEdnpoint -> EthernetSwitchPort -> VirtualEthernetSwitch + /// + public static VirtualEthernetSwitch GetExternalVirtSwitch() + { + // Work back from the first *bound* external NIC we find. + var externNICs = ExternalEthernetPort.GetInstances("IsBound = TRUE"); + + // Assert + if (externNICs.Count == 0 ) + { + var errMsg = "No ExternalEthernetPort available to Hyper-V"; + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + ExternalEthernetPort externNIC = externNICs.OfType().First(); + // A sequence of ASSOCIATOR objects need to be traversed to get from external NIC the vswitch. + // We use ManagementObjectSearcher objects to execute this sequence of questions + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var endpointQuery = new RelatedObjectQuery(externNIC.Path.Path, LANEndpoint.CreatedClassName); + var endpointSearch = new ManagementObjectSearcher(externNIC.Scope, endpointQuery); + var endpointCollection = new LANEndpoint.LANEndpointCollection(endpointSearch.Get()); + + // assert + if (endpointCollection.Count < 1 ) + { + var errMsg = string.Format("No adapter-based LANEndpoint for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + LANEndpoint adapterEndPoint = endpointCollection.OfType().First(); + var switchEndpointQuery = new RelatedObjectQuery(adapterEndPoint.Path.Path, LANEndpoint.CreatedClassName); + var switchEndpointSearch = new ManagementObjectSearcher(externNIC.Scope, switchEndpointQuery); + var switchEndpointCollection = new LANEndpoint.LANEndpointCollection(switchEndpointSearch.Get()); + + // assert + if (endpointCollection.Count < 1) + { + var errMsg = string.Format("No Switch-based LANEndpoint for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + LANEndpoint switchEndPoint = switchEndpointCollection.OfType().First(); + var switchPortQuery = new RelatedObjectQuery(switchEndPoint.Path.Path, EthernetSwitchPort.CreatedClassName); + var switchPortSearch = new ManagementObjectSearcher(switchEndPoint.Scope, switchPortQuery); + var switchPortCollection = new EthernetSwitchPort.EthernetSwitchPortCollection(switchPortSearch.Get()); + + // assert + if (switchPortCollection.Count < 1 ) + { + var errMsg = string.Format("No SwitchPort for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + EthernetSwitchPort switchPort = switchPortCollection.OfType().First(); + var vSwitchQuery = new RelatedObjectQuery(switchPort.Path.Path, VirtualEthernetSwitch.CreatedClassName); + var vSwitchSearch = new ManagementObjectSearcher(externNIC.Scope, vSwitchQuery); + var vSwitchCollection = new VirtualEthernetSwitch.VirtualEthernetSwitchCollection(vSwitchSearch.Get()); + + // assert + if (vSwitchCollection.Count < 1) + { + var errMsg = string.Format("No virtual switch for external NIC {0} on Hyper-V server", externNIC.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + VirtualEthernetSwitch vSwitch = vSwitchCollection.OfType().First(); + return vSwitch; + } + + private static void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) + { + // Resource settings are changed through the management service + System.Management.ManagementPath jobPath; + System.Management.ManagementPath[] results; + + var ret_val = vmMgmtSvc.ModifyResourceSettings( + resourceSettings, + out jobPath, + out results); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + public void DeleteHostKvpItem(ComputerSystem vm, string key) { // Obtain controller for Hyper-V virtualisation subsystem @@ -132,6 +1217,141 @@ namespace HypervResource } } + private static ComputerSystem CreateDefaultVm(VirtualSystemManagementService vmMgmtSvc, string name) + { + // Tweak default settings by basing new VM on default global setting object + // with designed display name. + + VirtualSystemSettingData vs_gs_data = VirtualSystemSettingData.CreateInstance(); + vs_gs_data.LateBoundObject["ElementName"] = name; + + System.Management.ManagementPath jobPath; + System.Management.ManagementPath defined_sys; + var ret_val = vmMgmtSvc.DefineSystem( + null, + new string[0], + vs_gs_data.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20), + out jobPath, + out defined_sys); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to create VM {0} due to {1} (DefineVirtualSystem call)", + name, ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + logger.DebugFormat(CultureInfo.InvariantCulture, "Created VM {0}", name); + + // Is the defined_system real? + var vm = new ComputerSystem(defined_sys); + + // Assertion + if (vm.ElementName.CompareTo(name) != 0) + { + var errMsg = string.Format( + "New VM created with wrong name (is {0}, should be {1}, GUID {2})", + vm.ElementName, + name, + vm.Name); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return vm; + } + + public VirtualEthernetSwitchManagementService GetVirtualSwitchManagementService() + { + // VirtualSwitchManagementService is a singleton, most anonymous way of lookup is by asking for the set + // of local instances, which should be size 1. + var virtSwtichSvcCollection = VirtualEthernetSwitchManagementService.GetInstances(); + foreach (VirtualEthernetSwitchManagementService item in virtSwtichSvcCollection) + { + return item; + } + + var errMsg = string.Format("No Hyper-V subsystem on server"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// Always produces a VHDX. + /// + /// + /// + public void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path) + { + // Produce description of the virtual disk in the format of a Msvm_VirtualHardDiskSettings object + + // Example at http://www.getcodesamples.com/src/FC025DDC/76689747, but + // Is there a template we can use to fill in the settings? + var newVirtHDSettings = VirtualHardDiskSettingData.CreateInstance(); + newVirtHDSettings.LateBoundObject["Type"] = 3; // Dynamic + newVirtHDSettings.LateBoundObject["Format"] = 3; // VHDX + newVirtHDSettings.LateBoundObject["Path"] = Path; + newVirtHDSettings.LateBoundObject["MaxInternalSize"] = MaxInternalSize; + newVirtHDSettings.LateBoundObject["BlockSize"] = 0; // Use defaults + newVirtHDSettings.LateBoundObject["LogicalSectorSize"] = 0; // Use defaults + newVirtHDSettings.LateBoundObject["PhysicalSectorSize"] = 0; // Use defaults + + // Optional: newVirtHDSettings.CommitObject(); + + // Add the new vhd object as a virtual hard disk to the vm. + string newVirtHDSettingsString = newVirtHDSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20); + + // Resource settings are changed through the management service + System.Management.ManagementPath jobPath; + var imgMgr = GetImageManagementService(); + var ret_val = imgMgr.CreateVirtualHardDisk(newVirtHDSettingsString, out jobPath); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to CreateVirtualHardDisk size {0}, path {1} due to {2}", + MaxInternalSize, + Path, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + + public ImageManagementService GetImageManagementService() + { + // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set + // of local instances, which should be size 1. + + var coll = ImageManagementService.GetInstances(); + foreach (ImageManagementService item in coll) + { + return item; + } + + var errMsg = string.Format("No Hyper-V subsystem on server"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public VirtualSystemManagementService GetVirtualisationSystemManagementService() { // VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set @@ -182,6 +1402,61 @@ namespace HypervResource logger.DebugFormat("WMI job succeeded: {0}, Elapsed={1}", jobObj.Description, jobObj.ElapsedTime); } + public void GetProcessorResources(out uint cores, out uint mhz) + { + // Processor processors + cores = 0; + mhz = 0; + Processor.ProcessorCollection procCol = Processor.GetInstances(); + foreach (Processor procInfo in procCol) + { + cores += procInfo.NumberOfCores; + mhz = procInfo.MaxClockSpeed; + } + } + + public void GetProcessorUsageInfo(out double cpuUtilization) + { + PerfFormattedData_Counters_ProcessorInformation.PerfFormattedData_Counters_ProcessorInformationCollection coll = + PerfFormattedData_Counters_ProcessorInformation.GetInstances("Name=\"_Total\""); + cpuUtilization = 100; + // Use the first one + foreach (PerfFormattedData_Counters_ProcessorInformation procInfo in coll) + { + // Idle during a given internal + // See http://library.wmifun.net/cimv2/win32_perfformatteddata_counters_processorinformation.html + cpuUtilization = 100.0 - (double)procInfo.PercentIdleTime; + } + } + + + public void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs) + { + OperatingSystem0 os = new OperatingSystem0(); + physicalRamKBs = os.TotalVisibleMemorySize; + freeMemoryKBs = os.FreePhysicalMemory; + } + + public string GetDefaultVirtualDiskFolder() + { + VirtualSystemManagementServiceSettingData.VirtualSystemManagementServiceSettingDataCollection coll = VirtualSystemManagementServiceSettingData.GetInstances(); + string defaultVirtualHardDiskPath = null; + foreach (VirtualSystemManagementServiceSettingData settings in coll) + { + defaultVirtualHardDiskPath = settings.DefaultVirtualHardDiskPath; + } + + // assert + if (!System.IO.Directory.Exists(defaultVirtualHardDiskPath) ){ + var errMsg = string.Format( + "Hyper-V DefaultVirtualHardDiskPath is invalid!"); + logger.Error(errMsg); + return null; + } + + return defaultVirtualHardDiskPath; + } + public ComputerSystem GetComputerSystem(string displayName) { var wmiQuery = String.Format("ElementName=\"{0}\"", displayName); @@ -212,6 +1487,217 @@ namespace HypervResource return result; } + public ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // ProcessorSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ProcessorSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new ProcessorSettingData.ProcessorSettingDataCollection(wmiObjectSearch.Get()); + + foreach (ProcessorSettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No ProcessorSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // MemorySettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, MemorySettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new MemorySettingData.MemorySettingDataCollection(wmiObjectSearch.Get()); + + foreach (MemorySettingData wmiObj in wmiObjCollection) + { + return wmiObj; + } + + var errMsg = string.Format("No MemorySettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + + public ResourceAllocationSettingData GetDvdDriveSettings(VirtualSystemSettingData vmSettings) + { + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + // DVD drive is '16', see http://msdn.microsoft.com/en-us/library/hh850200(v=vs.85).aspx + if (wmiObj.ResourceType == 16) + { + return wmiObj; + } + } + + var errMsg = string.Format( + "Cannot find the Dvd drive in VirtualSystemSettingData {0}", + vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public ResourceAllocationSettingData GetIDEControllerSettings(VirtualSystemSettingData vmSettings, string cntrllerAddr) + { + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + if (wmiObj.ResourceSubType == IDE_HARDDISK_CONTROLLER && wmiObj.Address == cntrllerAddr) + { + return wmiObj; + } + } + + var errMsg = string.Format( + "Cannot find the Microsoft Emulated IDE Controlle at address {0} in VirtualSystemSettingData {1}", + cntrllerAddr, + vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + /// + /// VM resources, typically hardware a described by a generic MSVM_ResourceAllocationSettingData object. The hardware type being + /// described is identified in two ways: in general terms using an enum in the ResourceType field, and in terms of the implementation + /// using text in the ResourceSubType field. + /// See http://msdn.microsoft.com/en-us/library/cc136877%28v=vs.85%29.aspx + /// + /// + /// + public ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // ResourceAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, ResourceAllocationSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new ResourceAllocationSettingData.ResourceAllocationSettingDataCollection(wmiObjectSearch.Get()); + + if (wmiObjCollection != null) + { + return wmiObjCollection; + } + + var errMsg = string.Format("No ResourceAllocationSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + public EthernetPortAllocationSettingData[] GetEthernetConnections(ComputerSystem vm) + { + // ComputerSystem -> VirtualSystemSettingData -> EthernetPortAllocationSettingData + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // EthernetPortAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, EthernetPortAllocationSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); + var wmiObjCollection = new EthernetPortAllocationSettingData.EthernetPortAllocationSettingDataCollection(wmiObjectSearch.Get()); + + var result = new List(wmiObjCollection.Count); + foreach (EthernetPortAllocationSettingData item in wmiObjCollection) + { + result.Add(item); + } + return result.ToArray(); + } + + + public EthernetSwitchPortVlanSettingData GetVlanSettings(EthernetPortAllocationSettingData ethernetConnection) + { + // An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the + // EthernetPortAllocationSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName); + // + var wmiObjQuery = new RelatedObjectQuery(ethernetConnection.Path.Path, EthernetSwitchPortVlanSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(ethernetConnection.Scope, wmiObjQuery); + var wmiObjCollection = new EthernetSwitchPortVlanSettingData.EthernetSwitchPortVlanSettingDataCollection(wmiObjectSearch.Get()); + + if (wmiObjCollection.Count == 0) + { + return null; + } + + // Assert + if (wmiObjCollection.Count > 1) + { + var errMsg = string.Format("Internal error, morn one VLAN settings for a single ethernetConnection"); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + + return wmiObjCollection.OfType().First(); + } + + + public SyntheticEthernetPortSettingData[] GetEthernetPortSettings(ComputerSystem vm) + { + // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the + // SyntheticEthernetPortSettingData, via the VirtualSystemSettingData. + // However, generated wrappers do not expose a ASSOCIATOR OF query as a method. + // Instead, we use the System.Management to code the equivalant of + // + // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); + // + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + + var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); + + // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain + // the virtualisation objects. + var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); + var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); + + List results = new List(wmiObjCollection.Count); + foreach (SyntheticEthernetPortSettingData item in wmiObjCollection) + { + results.Add(item); + } + + return results.ToArray(); + } + public string GetDefaultDataRoot() { string defaultRootPath = null; @@ -224,9 +1710,8 @@ namespace HypervResource return defaultRootPath; } - + public VirtualSystemSettingData GetVmSettings(ComputerSystem vm) - { // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the // VirtualSystemSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. @@ -281,6 +1766,41 @@ namespace HypervResource logger.Error(errMsg, ex); throw ex; } + + public void GetSummaryInfo(Dictionary vmProcessorInfo, List vmsToInspect) + { + // Process info available from WMI, + // See http://msdn.microsoft.com/en-us/library/hh850062(v=vs.85).aspx + uint[] requestedInfo = new uint[] { // TODO: correct? + 0, // Name + 1, // ElementName + 4, // Number of processes + 101 // ProcessorLoad + }; + + System.Management.ManagementBaseObject[] sysSummary; + var vmsvc = GetVirtualisationSystemManagementService(); + System.Management.ManagementPath[] vmPaths = vmsToInspect.ToArray(); + vmsvc.GetSummaryInformation(requestedInfo, vmPaths, out sysSummary); + + foreach (var summary in sysSummary) + { + + var summaryInfo = new SummaryInformation(summary); + + logger.Debug("VM " + summaryInfo.Name + "(elementName " + summaryInfo.ElementName + ") has " + + summaryInfo.NumberOfProcessors + " CPUs, and load of " + summaryInfo.ProcessorLoad); + var vmInfo = new VmStatsEntry + { + cpuUtilization = summaryInfo.ProcessorLoad, + numCPUs = summaryInfo.NumberOfProcessors, + networkReadKBs = 1, + networkWriteKBs = 1, + entityType = "vm" + }; + vmProcessorInfo.Add(summaryInfo.ElementName, vmInfo); + } + } } public class WmiException : Exception diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs index 1226561ff3e..6cc57483268 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs @@ -1,321 +1,320 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -using System; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; -using System.Management; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using System.IO; -using log4net; -using HypervResource; -using CloudStack.Plugin.AgentShell; -using System.Collections.Generic; -using NSubstitute; -using System.Web.Http; -using Xunit; - -namespace ServerResource.Tests -{ - public class HypervResourceController1Test - { - - protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; - protected static string testCifsPath = AgentSettings.Default.testCifsPath; - protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; - protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; - protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; - protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; - protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); - protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); - - // TODO: differentiate between NFS and HTTP template URLs. - protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; - protected static String testSampleTemplateURL = testSampleTemplateUUID; - - // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. - protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; - protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; - protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; - protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; - protected static String testSampleVolumeWorkingURIJSON; - protected static String testSampleVolumeCorruptURIJSON; - protected static String testSampleVolumeTempURIJSON; - - protected static String testSampleTemplateURLJSON; - protected static String testLocalStorePathJSON; - - protected static IWmiCalls wmiCalls; - - - private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceController1Test)); - - /// - /// Test WmiCalls to which incoming HTTP POST requests are dispatched. - /// - /// TODO: revise beyond first approximation - /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. - /// A second approximation would use the AgentShell settings files directly. - /// A third approximation would look to invoke ServerResource methods via an HTTP request - /// - - public HypervResourceController1Test() - { - wmiCalls = Substitute.For(); - //AgentService.ConfigServerResource(); - HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; - HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; - HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; - HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; - HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; - - - // Used to create existing StoragePool in preparation for the ModifyStoragePool - testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); - - // Make sure secondary store is available. - string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); - s_logger.Info("Test secondary storage in " + fullPath); - DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); - if (!testSecondarStoreDir.Exists) - { - try - { - testSecondarStoreDir.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); - } - } - - // Convert to secondary storage string to canonical path - testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; - AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; - - // Make sure local primary storage is available - DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); - //Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); - - // Convert to local primary storage string to canonical path - testLocalStorePath = testPoolDir.FullName; - AgentSettings.Default.local_storage_path = testLocalStorePath; - - // Clean up old test files in local storage folder - FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); - // Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); - - testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); - s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); - - - // Capture other JSON encoded paths - testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); - testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); - - // TODO: may need to initialise the server resource in future. - // s_hypervresource.initialize(); - - // Verify sample template is in place storage pool - s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON - + " sample template at " + testSampleTemplateURLJSON); - } - - private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, - String dstPath, - String dstFileName) - { - var newFullname = Path.Combine(dstPath, dstFileName); - var newFileInfo = new FileInfo(newFullname); - if (!newFileInfo.Exists) - { - newFileInfo = srcFile.CopyTo(newFullname); - } - newFileInfo.Refresh(); - Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); - - return JsonConvert.SerializeObject(newFileInfo.FullName); - } - - [Fact] - public void TestCreateCommand() - { - DirectoryInfo localStorePath = new DirectoryInfo(testLocalStorePath); - if (!localStorePath.Exists) - { - try - { - localStorePath.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + localStorePath.FullName + " failed due to " + ex.Message); - } - } - - FileInfo sampleTemplateFile = new FileInfo(Path.Combine(testLocalStorePath, testSampleTemplateUUID)); - if (!sampleTemplateFile.Exists) - { - //Create a file to write to. - using (StreamWriter sw = sampleTemplateFile.CreateText()) - { - sw.WriteLine("This is fake template file for test"); - } - } - var counter = 0; - wmiCalls.When(x => x.CreateDynamicVirtualHardDisk(Arg.Any(), Arg.Any())).Do(x => counter++); - // TODO: Need sample to update the test. - // Arrange - String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCalls = wmiCalls; - - Assert.True(Directory.Exists(testLocalStorePath), testLocalStorePath + " does not exist "); - string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); - Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); - int fileCount = Directory.GetFiles(testLocalStorePath).Length; - s_logger.Debug(" test local store has " + fileCount + "files"); - - // Act - // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. - dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); - s_logger.Debug("CreateDynamicVirtualHardDisk method is called " + counter + " times"); - - //Assert.Equal(counter, 1); - - JObject ansAsProperty2 = jsonResult[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - Assert.NotNull(ans); - Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); - Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); - FileInfo newFile = new FileInfo((string)ans.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - sampleTemplateFile.Delete(); - } - - /// - /// Possible additional tests: place an ISO in the drive - /// - - [Fact] - public void TestStartCommand() - { - ComputerSystem system = new ComputerSystem(); - wmiCalls.DeployVirtualMachine(Arg.Any(), Arg.Any()).Returns(system); - - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCalls = wmiCalls; - String sample = getSampleStartCommand(); - - - dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); - - // Act - dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); - - // Assert - Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); - Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); - - Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); - } - - [Fact] - public void TestStopCommand() - { - //string vmName = "Test VM"; - var counter = 0; - wmiCalls.When(x => x.DestroyVm(Arg.Any())).Do(x => counter++); - - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCalls = wmiCalls; - - String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; - dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); - - // Act - dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); - - // Assert VM is gone! - Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); - Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); - - Assert.Null((string)stopAns[0][CloudStackTypes.StopAnswer].details); - Assert.Equal(counter, 1); - } - - public static String getSamplePrimaryDataStoreInfo() - { - String samplePrimaryDataStoreInfo = - "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + - "{\"uuid\":\"" + testLocalStoreUUID + "\"," + - "\"id\":201," + - "\"host\":\"" + testPrimaryDataStoreHost + "\"," + - "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"path\":" + testLocalStorePathJSON + "," + - "\"port\":0}" + - "}"; - return samplePrimaryDataStoreInfo; - } - - public static String getSampleVolumeObjectTO() - { - String sampleVolumeObjectTO = - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"format\":\"VHDX\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? - "\"accountId\":3,\"id\":10}" + - "}"; // end of destTO - return sampleVolumeObjectTO; - } - - public static String getSampleStartCommand() - { - String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + - "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + - "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + - "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + - "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + - ",\"disks\":[" + - "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + - "{\"diskSeq\":1,\"type\":\"ISO\"}" + - "]," + - "\"nics\":[" + - "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + - "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + - "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + - "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + - "]},\"contextMap\":{},\"wait\":0}"; - return sample; - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +using System; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using NSubstitute; +using System.Web.Http; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceController1Test + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static IWmiCallsV2 wmiCallsV2; + + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceController1Test)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + + public HypervResourceController1Test() + { + wmiCallsV2 = Substitute.For(); + //AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + //Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + // Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact] + public void TestCreateCommand() + { + DirectoryInfo localStorePath = new DirectoryInfo(testLocalStorePath); + if (!localStorePath.Exists) + { + try + { + localStorePath.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + localStorePath.FullName + " failed due to " + ex.Message); + } + } + + FileInfo sampleTemplateFile = new FileInfo(Path.Combine(testLocalStorePath, testSampleTemplateUUID)); + if (!sampleTemplateFile.Exists) + { + //Create a file to write to. + using (StreamWriter sw = sampleTemplateFile.CreateText()) + { + sw.WriteLine("This is fake template file for test"); + } + } + var counter = 0; + wmiCallsV2.When(x => x.CreateDynamicVirtualHardDisk(Arg.Any(), Arg.Any())).Do(x => counter++); + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + Assert.True(Directory.Exists(testLocalStorePath), testLocalStorePath + " does not exist "); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + s_logger.Debug("CreateDynamicVirtualHardDisk method is called " + counter + " times"); + + //Assert.Equal(counter, 1); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + sampleTemplateFile.Delete(); + } + + /// + /// Possible additional tests: place an ISO in the drive + /// + + [Fact] + public void TestStartCommand() + { + ComputerSystem system = new ComputerSystem(); + wmiCallsV2.DeployVirtualMachine(Arg.Any(), Arg.Any()).Returns(system); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + + Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); + } + + [Fact] + public void TestStopCommand() + { + //string vmName = "Test VM"; + var counter = 0; + wmiCallsV2.When(x => x.DestroyVm(Arg.Any())).Do(x => counter++); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + + Assert.Null((string)stopAns[0][CloudStackTypes.StopAnswer].details); + Assert.Equal(counter, 1); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs index c66c6162017..fab1b8243b2 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs @@ -1,1149 +1,1147 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -using System; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; -using System.Management; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using System.IO; -using log4net; -using HypervResource; -using CloudStack.Plugin.AgentShell; -using System.Collections.Generic; -using System.Xml; -using Xunit; - -namespace ServerResource.Tests -{ - public class HypervResourceControllerTest - { - protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; - protected static string testCifsPath = AgentSettings.Default.testCifsPath; - protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; - protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; - protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; - protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; - protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); - protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); - - // TODO: differentiate between NFS and HTTP template URLs. - protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; - protected static String testSampleTemplateURL = testSampleTemplateUUID; - - // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. - protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; - protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; - protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; - protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; - protected static String testSampleVolumeWorkingURIJSON; - protected static String testSampleVolumeCorruptURIJSON; - protected static String testSampleVolumeTempURIJSON; - - protected static String testSampleTemplateURLJSON; - protected static String testLocalStorePathJSON; - - protected static WmiCalls wmiCalls = new WmiCalls(); - protected static WmiCallsV2 wmiCallsV2 = new WmiCallsV2(); - - private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceControllerTest)); - - /// - /// Test WmiCalls to which incoming HTTP POST requests are dispatched. - /// - /// TODO: revise beyond first approximation - /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. - /// A second approximation would use the AgentShell settings files directly. - /// A third approximation would look to invoke ServerResource methods via an HTTP request - /// - public HypervResourceControllerTest() - { - AgentService.ConfigServerResource(); - HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; - HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; - HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; - HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; - HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; - - - // Used to create existing StoragePool in preparation for the ModifyStoragePool - testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); - - // Make sure secondary store is available. - string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); - s_logger.Info("Test secondary storage in " + fullPath); - DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); - if (!testSecondarStoreDir.Exists) - { - try - { - testSecondarStoreDir.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); - } - } - - // Convert to secondary storage string to canonical path - testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; - AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; - - // Make sure local primary storage is available - DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); - Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); - - // Convert to local primary storage string to canonical path - testLocalStorePath = testPoolDir.FullName; - AgentSettings.Default.local_storage_path = testLocalStorePath; - - // Clean up old test files in local storage folder - FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); - Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); - - - // Delete all temporary files in local folder save the testVolWorks - foreach (var file in testPoolDir.GetFiles()) - { - if (file.FullName == testVolWorks.FullName) - { - continue; - } - file.Delete(); - file.Refresh(); - Assert.False(file.Exists, "removed file from previous test called " + file.FullName); - } - - // Recreate starting point files for test, and record JSON encoded paths for each ... - testSampleVolumeTempURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeTempUUID); - s_logger.Info("Created " + testSampleVolumeTempURIJSON); - testSampleVolumeCorruptURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeCorruptUUID); - s_logger.Info("Created " + testSampleVolumeCorruptURIJSON); - CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleTemplateUUID); - testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); - s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); - - // ... including a secondary storage template: - CreateTestDiskImageFromExistingImage(testVolWorks, testSecondarStoreDir.FullName, "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); - s_logger.Info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + " in secondary (NFS) storage."); - - - // Capture other JSON encoded paths - testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); - testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); - - // TODO: may need to initialise the server resource in future. - // s_hypervresource.initialize(); - - // Verify sample template is in place storage pool - s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON - + " sample template at " + testSampleTemplateURLJSON); - } - - private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, - String dstPath, - String dstFileName) - { - var newFullname = Path.Combine(dstPath, dstFileName); - var newFileInfo = new FileInfo(newFullname); - if (!newFileInfo.Exists) - { - newFileInfo = srcFile.CopyTo(newFullname); - } - newFileInfo.Refresh(); - Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); - - return JsonConvert.SerializeObject(newFileInfo.FullName); - } - - [Fact(Skip="these are functional tests")] - public void TestPrimaryStorageDownloadCommandHTTP() - { - string downloadURI = "https://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; - corePrimaryStorageDownloadCommandTestCycle(downloadURI); - } - - private void corePrimaryStorageDownloadCommandTestCycle(string downloadURI) - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - dynamic jsonPSDCmd = JsonConvert.DeserializeObject(samplePrimaryDownloadCommand()); - jsonPSDCmd.url = downloadURI; - - // Act - dynamic jsonResult = rsrcServer.PrimaryStorageDownloadCommand(jsonPSDCmd); - - // Assert - JObject ansAsProperty = jsonResult[0]; - dynamic ans = ansAsProperty.GetValue(CloudStackTypes.PrimaryStorageDownloadAnswer); - Assert.True((bool)ans.result, "PrimaryStorageDownloadCommand did not succeed " + ans.details); - - // Test that URL of downloaded template works for file creation. - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(CreateCommandSample()); - jsonCreateCmd.templateUrl = ans.installPath; - dynamic jsonAns2 = rsrcServer.CreateCommand(jsonCreateCmd); - JObject ansAsProperty2 = jsonAns2[0]; - dynamic ans2 = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - - Assert.True((bool)ans2.result, (string)ans2.details); - - FileInfo newFile = new FileInfo((string)ans2.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - } - - private string samplePrimaryDownloadCommand() - { - String cmdJson = "{\"localPath\":" + testLocalStorePathJSON + - ",\"poolUuid\":\"" + testLocalStoreUUID + "\",\"poolId\":201," + - "\"secondaryStorageUrl\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + - "\"primaryStorageUrl\":\"nfs://" + HypervResourceController.config.StorageIpAddress + "E:\\\\Disks\\\\Disks\"," + - "\"url\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + - "\"format\":\"VHDX\",\"accountId\":2,\"name\":\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + - ",\"contextMap\":{},\"wait\":10800}"; - return cmdJson; - } - - public string CreateCommandSample() - { - String sample = "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":17,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"wait\":0}"; - return sample; - } - - [Fact(Skip="these are functional tests")] - public void TestDestroyCommand() - { - // Arrange - String sampleVolume = getSampleVolumeObjectTO(); - String destoryCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; - "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt - + "\",\"storagePoolType\":\"Filesystem\"," - + "\"mountPoint\":" - + testLocalStorePathJSON - + ",\"path\":" + testSampleVolumeTempURIJSON - + ",\"storagePoolUuid\":\"" + testLocalStoreUUID - + "\"," - + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; - - HypervResourceController rsrcServer = new HypervResourceController(); - dynamic jsonDestoryCmd = JsonConvert.DeserializeObject(destoryCmd); - - // Act - dynamic destoryAns = rsrcServer.DestroyCommand(jsonDestoryCmd); - - // Assert - JObject ansAsProperty2 = destoryAns[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); - String path = jsonDestoryCmd.volume.path; - Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); - Assert.True(!File.Exists(path), "Failed to delete file " + path); - } - - [Fact(Skip="these are functional tests")] - public void TestCreateCommand() - { - // TODO: Need sample to update the test. - // Arrange - String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); - HypervResourceController rsrcServer = new HypervResourceController(); - - Assert.True(Directory.Exists(testLocalStorePath)); - string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); - Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); - int fileCount = Directory.GetFiles(testLocalStorePath).Length; - s_logger.Debug(" test local store has " + fileCount + "files"); - - // Act - // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. - dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); - - JObject ansAsProperty2 = jsonResult[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - Assert.NotNull(ans); - Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); - Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); - FileInfo newFile = new FileInfo((string)ans.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - } - - /// - /// Possible additional tests: place an ISO in the drive - /// - [Fact(Skip="these are functional tests")] - public void TestStartStopCommand() - { - string vmName = TestStartCommand(); - TestStopCommand(vmName); - } - - public static String getSamplePrimaryDataStoreInfo() - { - String samplePrimaryDataStoreInfo = - "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + - "{\"uuid\":\"" + testLocalStoreUUID + "\"," + - "\"id\":201," + - "\"host\":\"" + testPrimaryDataStoreHost + "\"," + - "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"path\":" + testLocalStorePathJSON + "," + - "\"port\":0}" + - "}"; - return samplePrimaryDataStoreInfo; - } - - public static String getSampleVolumeObjectTO() - { - String sampleVolumeObjectTO = - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"format\":\"VHDX\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? - "\"accountId\":3,\"id\":10}" + - "}"; // end of destTO - return sampleVolumeObjectTO; - } - - public static String getSampleStartCommand() - { - String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + - "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + - "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + - "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + - "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + - ",\"disks\":[" + - "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + - "{\"diskSeq\":1,\"type\":\"ISO\"}" + - "]," + - "\"nics\":[" + - "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + - "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + - "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + - "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + - "]},\"contextMap\":{},\"wait\":0}"; - return sample; - } - - - [Fact(Skip="these are functional tests")] - public void TestCopyCommandFromCifs() - { - // Arrange - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testCifsPath + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.NfsTO\":" + - "{\"_url\":\"" + testCifsUrl + "\"," + // Unique item here - "\"_role\":\"Image\"}" + - "}," + // end of imageDataStore - "\"hypervisorType\":\"Hyperv\"," + - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"Test of CIFS Download\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"," + - "\"hypervisorType\":\"Hyperv\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetupCifs(null, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - // Repeat to verify ability to detect existing file. - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - File.Delete(dwnldDest); - } - - [Fact(Skip="these are functional tests")] - public void TestCopyCommand() - { - // Arrange - string sampleCopyCommandToCreateVolumeFromTemplate = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + - "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + - "\"id\":5," + - "\"format\":\"VHDX\"," + - "\"accountId\":1," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":false," + - "\"displayText\":\"tiny Linux\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"ROOT-5\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - "\"vmName\":\"i-3-5-VM\"," + - "\"accountId\":3," + - "\"id\":10 }" + - "}," + // end of destTO - "\"wait\":0}"; // end of Copy Command - #endregion - //"name":"ROOT-8","size":140616708,"volumeId":8,"vmName":"s-8-VM","accountId":1,"id":8}},"contextMap":{},"wait":0} - - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testS3TemplateName + ".vhdx" + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.S3TO\":" + - "{\"id\":1," + - "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + - "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + - "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + - "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + - "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + - "\"httpsFlag\":false," + - "\"created\":\"May 19, 2013 4:17:25 PM\"}" + - "}," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); - - // Repeat to verify ability to detect existing file. - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - File.Delete(dwnldDest); - File.Delete(newVolName); - } - - private static void CreateVolumeFromTemplate(HypervResourceController rsrcServer, dynamic jsonCloneCopyCmd, string newVolName) - { - dynamic copyResult = rsrcServer.CopyCommand(jsonCloneCopyCmd); - - // Assert - Assert.NotNull(copyResult[0][CloudStackTypes.CopyCmdAnswer]); - Assert.True((bool)copyResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + copyResult[0][CloudStackTypes.CopyCmdAnswer].details); - Assert.True(File.Exists(newVolName), "CopyCommand failed to generate " + newVolName); - } - - private static void DownloadTemplateToPrimaryStorage(HypervResourceController rsrcServer, dynamic jsonDownloadCopyCmd, string dwnldDest) - { - dynamic dwnldResult = rsrcServer.CopyCommand(jsonDownloadCopyCmd); - - // Assert - Assert.NotNull(dwnldResult[0][CloudStackTypes.CopyCmdAnswer]); - Assert.True((bool)dwnldResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + dwnldResult[0][CloudStackTypes.CopyCmdAnswer].details); - Assert.True(File.Exists(dwnldDest), "CopyCommand failed to generate " + dwnldDest); - } - - [Fact(Skip="these are functional tests")] - public void TestCopyCommandBz2Img() - { - // Arrange - string sampleCopyCommandToCreateVolumeFromTemplate = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + - "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + - "\"id\":5," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\":\"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":false," + - "\"displayText\":\"tiny Linux\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"ROOT-5\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - "\"vmName\":\"i-3-5-VM\"," + - "\"accountId\":1," + - "\"id\":10}" + - "}," + // end of destTO - "\"wait\":0}"; // end of Copy Command - #endregion - - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testSystemVMTemplateName + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.S3TO\":" + - "{\"id\":1," + - "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + - "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + - "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + - "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + - "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + - "\"httpsFlag\":false," + - "\"created\":\"May 19, 2013 4:17:25 PM\"}" + - "}," + // end of imageDataStore - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); - - File.Delete(dwnldDest); - File.Delete(newVolName); - } - - private static void CopyCommandTestSetup(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) - { - rsrcServer = new HypervResourceController(); - jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); - TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); - dwnldDest = dwnldTemplate.FullFileName; - - jsonCloneCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandToCreateVolumeFromTemplate); - VolumeObjectTO newVol = VolumeObjectTO.ParseJson(jsonCloneCopyCmd.destTO); - newVol.format = dwnldTemplate.format; - newVolName = dwnldTemplate.FullFileName; - - if (File.Exists(dwnldDest)) - { - File.Delete(dwnldDest); - } - if (File.Exists(newVolName)) - { - File.Delete(newVolName); - } - } - - private static void CopyCommandTestSetupCifs(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) - { - rsrcServer = new HypervResourceController(); - jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); - TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); - dwnldDest = dwnldTemplate.FullFileName; - - if (File.Exists(dwnldDest)) - { - File.Delete(dwnldDest); - } - newVolName = null; - jsonCloneCopyCmd = null; - } - - [Fact(Skip="these are functional tests")] - public void TestModifyStoragePoolCommand() - { - // Create dummy folder - String folderName = Path.Combine(".", "Dummy"); - if (!Directory.Exists(folderName)) - { - Directory.CreateDirectory(folderName); - } - - var pool = new - { // From java class StorageFilerTO - type = Enum.GetName(typeof(StoragePoolType), StoragePoolType.Filesystem), - host = "127.0.0.1", - port = -1, - path = folderName, - uuid = Guid.NewGuid().ToString(), - userInfo = string.Empty // Used in future to hold credential - }; - - var cmd = new - { - add = true, - pool = pool, - localPath = folderName - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.ModifyStoragePoolCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.ModifyStoragePoolAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - - // Clean up - var cmd2 = new - { - pool = pool, - localPath = folderName - }; - JToken tok2 = JToken.FromObject(cmd); - - // Act - dynamic jsonResult2 = controller.DeleteStoragePoolCommand(tok2); - - // Assert - dynamic ans2 = jsonResult2[0][CloudStackTypes.Answer]; - Assert.True((bool)ans2.result, (string)ans2.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void CreateStoragePoolCommand() - { - var cmd = new { localPath = "NULL" }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.CreateStoragePoolCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.Answer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void MaintainCommand() - { - // Omit HostEnvironment object, as this is a series of settings currently not used. - var cmd = new { }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.MaintainCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.MaintainAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void SetupCommand() - { - // Omit HostEnvironment object, as this is a series of settings currently not used. - var cmd = new { multipath = false, needSetup = true }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.SetupCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.SetupAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void TestPassingUserdataToVm() - { - // Sample data - String key = "cloudstack-vm-userdata"; - String value = "username=root;password=1pass@word1"; - - // Find the VM - List vmNames = wmiCallsV2.GetVmElementNames(); - - // Get associated WMI object - var vm = wmiCallsV2.GetComputerSystem(AgentSettings.Default.testKvpVmName); - - // Get existing KVP - var vmSettings = wmiCallsV2.GetVmSettings(vm); - var kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); - - // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. - string[] kvpProps = kvpInfo.HostExchangeItems; - - // If the value already exists, delete it - foreach (var item in kvpProps) - { - String wmiObjectXml = item; - String existingKey; - String existingValue; - ParseKVP(wmiObjectXml, out existingKey, out existingValue); - - if (existingKey == key) - { - wmiCallsV2.DeleteHostKvpItem(vm, existingKey); - break; - } - } - - // Add new user data - wmiCallsV2.AddUserData(vm, value); - - // Verify key added to subsystem - kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); - - // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. - kvpProps = kvpInfo.HostExchangeItems; - - // If the value already exists, delete it - bool userDataInPlace = false; - foreach (var item in kvpProps) - { - String wmiObjectXml = item; - String existingKey; - String existingValue; - ParseKVP(wmiObjectXml, out existingKey, out existingValue); - - if (existingKey == key && existingValue == value) - { -// wmiCallsV2.DeleteHostKvpItem(vm, existingKey); - userDataInPlace = true; - break; - } - } - - Assert.True(userDataInPlace, "User data key / value did no save properly"); - } - - private static void ParseKVP(String wmiObjectXml, out String existingKey, out String existingValue) - { - // Reference: http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/12/05/enumerating-parent-kvp-data.aspx - - // Create XML parser - var xmlDoc = new XmlDocument(); - - // Load WMI object - xmlDoc.LoadXml(wmiObjectXml); - - // Use xpath to get name and value - var namePropXpath = "/INSTANCE/PROPERTY[@NAME='Name']/VALUE"; - var nameNode = xmlDoc.SelectSingleNode(namePropXpath); - existingKey = nameNode.InnerText; - var dataPropXpath = "/INSTANCE/PROPERTY[@NAME='Data']/VALUE"; - var dataNode = xmlDoc.SelectSingleNode(dataPropXpath); - existingValue = dataNode.InnerText; - } - - [Fact(Skip="these are functional tests")] - public void GetVmStatsCommandFail() - { - // Use WMI to find existing VMs - List vmNames = new List(); - vmNames.Add("FakeVM"); - - var cmd = new - { - hostGuid = "FAKEguid", - hostName = AgentSettings.Default.host, - vmNames = vmNames - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetVmStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds, fake VM means no answer for the named VM - } - - [Fact(Skip="these are functional tests")] - public void GetVmStatsCommand() - { - // Use WMI to find existing VMs - List vmNames = wmiCalls.GetVmElementNames(); - - var cmd = new - { - hostGuid = "FAKEguid", - hostName = AgentSettings.Default.host, - vmNames = vmNames - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetVmStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); - } - - [Fact(Skip="these are functional tests")] - public void GetStorageStatsCommand() - { - // TODO: Update sample data to unsure it is using correct info. - String sample = String.Format( - #region string_literal -"{{\"" + - "id\":{0}," + - "\"localPath\":{1}," + - "\"pooltype\":\"Filesystem\"," + - "\"contextMap\":{{}}," + - "\"wait\":0}}", - JsonConvert.SerializeObject(AgentSettings.Default.testLocalStoreUUID), - JsonConvert.SerializeObject(AgentSettings.Default.testLocalStorePath) - ); - #endregion - var cmd = JsonConvert.DeserializeObject(sample); - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetStorageStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetStorageStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); - Assert.True((long)ans.used <= (long)ans.capacity); // TODO: verify that capacity is indeed capacity and not used. - } - - // TODO: can we speed up this command? The logic takes over a second. - [Fact(Skip="these are functional tests")] - public void GetHostStatsCommand() - { - // Arrange - long hostIdVal = 5; - HypervResourceController controller = new HypervResourceController(); - string sample = string.Format( - #region string_literal -"{{" + - "\"hostGuid\":\"B4AE5970-FCBF-4780-9F8A-2D2E04FECC34-HypervResource\"," + - "\"hostName\":\"CC-SVR11\"," + - "\"hostId\":{0}," + - "\"contextMap\":{{}}," + - "\"wait\":0}}", - JsonConvert.SerializeObject(hostIdVal)); - #endregion - var cmd = JsonConvert.DeserializeObject(sample); - JToken tok = JToken.FromObject(cmd); - - // Act - dynamic jsonResult = controller.GetHostStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; - Assert.True((bool)ans.result); - Assert.True(hostIdVal == (long)ans.hostStats.hostId); - Assert.True(0.0 < (double)ans.hostStats.totalMemoryKBs); - Assert.True(0.0 < (double)ans.hostStats.freeMemoryKBs); - Assert.True(0.0 <= (double)ans.hostStats.networkReadKBs); - Assert.True(0.0 <= (double)ans.hostStats.networkWriteKBs); - Assert.True(0.0 <= (double)ans.hostStats.cpuUtilization); - Assert.True(100.0 >= (double)ans.hostStats.cpuUtilization); - Assert.True("host".Equals((string)ans.hostStats.entityType)); - Assert.True(String.IsNullOrEmpty((string)ans.details)); - } - - [Fact(Skip="these are functional tests")] - public void GetHostStatsCommandFail() - { - // Arrange - HypervResourceController controller = new HypervResourceController(); - var cmd = new { GetHostStatsCommand = new { hostId = "badvalueType" } }; - JToken tokFail = JToken.FromObject(cmd); - - // Act - dynamic jsonResult = controller.GetHostStatsCommand(tokFail); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; - Assert.False((bool)ans.result); - Assert.Null((string)ans.hostStats); - Assert.NotNull(ans.details); - } - - [Fact(Skip="these are functional tests")] - public void TestStartupCommand() - { - // Arrange - HypervResourceController controller = new HypervResourceController(); - String sampleStartupRoutingCommand = - #region string_literal - "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + - "\"cpus\":0," + - "\"speed\":0," + - "\"memory\":0," + - "\"dom0MinMemory\":0," + - "\"poolSync\":false," + - "\"vms\":{}," + - "\"hypervisorType\":\"Hyperv\"," + - "\"hostDetails\":{" + - "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + - "}," + - "\"type\":\"Routing\"," + - "\"dataCenter\":\"1\"," + - "\"pod\":\"1\"," + - "\"cluster\":\"1\"," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"name\":\"localhost\"," + - "\"version\":\"4.2.0\"," + - "\"privateIpAddress\":\"1\"," + - "\"storageIpAddress\":\"1\"," + - "\"contextMap\":{}," + - "\"wait\":0}}]"; - #endregion - - uint cores; - uint mhz; - wmiCalls.GetProcessorResources(out cores, out mhz); - ulong memory_mb; - ulong freememory; - wmiCalls.GetMemoryResources(out memory_mb, out freememory); - memory_mb *= 1024; - long capacityBytes; - long availableBytes; - HypervResourceController.GetCapacityForLocalPath(wmiCalls.GetDefaultVirtualDiskFolder(), - out capacityBytes, out availableBytes); - var DefaultVirtualDiskFolder = JsonConvert.SerializeObject(wmiCalls.GetDefaultVirtualDiskFolder()); - string expected = - #region string_literal - "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + - "\"cpus\":" + cores + "," + - "\"speed\":" + mhz + "," + - "\"memory\":" + memory_mb + "," + - "\"dom0MinMemory\":" + (AgentSettings.Default.dom0MinMemory * 1024 * 1024) + "," + - "\"poolSync\":false," + - "\"vms\":{}," + - "\"hypervisorType\":\"Hyperv\"," + - "\"hostDetails\":{" + - "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + - "}," + - "\"type\":\"Routing\"," + - "\"dataCenter\":\"1\"," + - "\"pod\":\"1\"," + - "\"cluster\":\"1\"," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"name\":\"localhost\"," + - "\"version\":\"4.2.0\"," + - "\"privateIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"storageIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"contextMap\":{}," + - "\"wait\":0," + - "\"privateNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + - "\"privateMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + - "\"storageNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + - "\"storageMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + - "\"gatewayIpAddress\":\"" + AgentSettings.Default.gateway_ip_address + "\"" + - ",\"caps\":\"hvm\"" + - "}}," + - "{\"com.cloud.agent.api.StartupStorageCommand\":{" + - "\"poolInfo\":{" + - "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"host\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"localPath\":" + DefaultVirtualDiskFolder + "," + - "\"hostPath\":" + DefaultVirtualDiskFolder + "," + - "\"poolType\":\"Filesystem\"," + - "\"capacityBytes\":" + capacityBytes + "," + - "\"availableBytes\":" + availableBytes + "," + - "\"details\":null" + - "}," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"dataCenter\":\"1\"," + - "\"resourceType\":\"STORAGE_POOL\"" + - "}}]"; - #endregion - - dynamic jsonArray = JsonConvert.DeserializeObject(sampleStartupRoutingCommand); - - // Act - dynamic jsonResult = controller.StartupCommand(jsonArray); - - // Assert - string actual = JsonConvert.SerializeObject(jsonResult); - Assert.Equal(expected, actual); - } - - - private static string TestStartCommand() - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - String sample = getSampleStartCommand(); - - - dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); - - // Act - dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); - - // Assert - Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); - Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); - string vmCmdName = jsonStartCmd.vm.name.Value; - var vm = wmiCalls.GetComputerSystem(vmCmdName); - VirtualSystemSettingData vmSettings = wmiCalls.GetVmSettings(vm); - MemorySettingData memSettings = wmiCalls.GetMemSettings(vmSettings); - ProcessorSettingData procSettings = wmiCalls.GetProcSettings(vmSettings); - dynamic jsonObj = JsonConvert.DeserializeObject(sample); - var vmInfo = jsonObj.vm; - string vmName = vmInfo.name; - var nicInfo = vmInfo.nics; - int vcpus = vmInfo.cpus; - int memSize = vmInfo.maxRam / 1048576; - Assert.True((long)memSettings.VirtualQuantity == memSize); - Assert.True((long)memSettings.Reservation == memSize); - Assert.True((long)memSettings.Limit == memSize); - Assert.True((int)procSettings.VirtualQuantity == vcpus); - Assert.True((int)procSettings.Reservation == vcpus); - Assert.True((int)procSettings.Limit == 100000); - - // examine NIC - SyntheticEthernetPortSettingData[] nicSettingsViaVm = wmiCalls.GetEthernetPorts(vm); - Assert.True(nicSettingsViaVm.Length > 0, "Should be at least one ethernet port on VM"); - string expectedMac = (string)jsonStartCmd.vm.nics[0].mac; - string strippedExpectedMac = expectedMac.Replace(":", string.Empty); - Assert.Equal(nicSettingsViaVm[0].Address.ToLower(), strippedExpectedMac.ToLower()); - - // Assert switchport has correct VLAN - SwitchPort[] switchPorts = wmiCalls.GetSwitchPorts(vm); - VirtualSwitchManagementService vmNetMgmtSvc = wmiCalls.GetVirtualSwitchManagementService(); - VLANEndpointSettingData vlanSettings = wmiCalls.GetVlanEndpointSettings(vmNetMgmtSvc, switchPorts[0].Path); - string isolationUri = (string)jsonStartCmd.vm.nics[0].isolationUri; - string vlan = isolationUri.Replace("vlan://", string.Empty); - Assert.Equal(vlanSettings.AccessVLAN.ToString(), vlan); - - return vmName; - } - - private static void TestStopCommand(string vmName) - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; - dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); - - // Act - dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); - - // Assert VM is gone! - Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); - Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); - var finalVm = wmiCalls.GetComputerSystem(vmName); - Assert.True(wmiCalls.GetComputerSystem(vmName) == null); - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +using System; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using System.Xml; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceControllerTest + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static WmiCallsV2 wmiCallsV2 = new WmiCallsV2(); + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceControllerTest)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + public HypervResourceControllerTest() + { + AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + + // Delete all temporary files in local folder save the testVolWorks + foreach (var file in testPoolDir.GetFiles()) + { + if (file.FullName == testVolWorks.FullName) + { + continue; + } + file.Delete(); + file.Refresh(); + Assert.False(file.Exists, "removed file from previous test called " + file.FullName); + } + + // Recreate starting point files for test, and record JSON encoded paths for each ... + testSampleVolumeTempURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeTempUUID); + s_logger.Info("Created " + testSampleVolumeTempURIJSON); + testSampleVolumeCorruptURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeCorruptUUID); + s_logger.Info("Created " + testSampleVolumeCorruptURIJSON); + CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleTemplateUUID); + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + // ... including a secondary storage template: + CreateTestDiskImageFromExistingImage(testVolWorks, testSecondarStoreDir.FullName, "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); + s_logger.Info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + " in secondary (NFS) storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact(Skip="these are functional tests")] + public void TestPrimaryStorageDownloadCommandHTTP() + { + string downloadURI = "https://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; + corePrimaryStorageDownloadCommandTestCycle(downloadURI); + } + + private void corePrimaryStorageDownloadCommandTestCycle(string downloadURI) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonPSDCmd = JsonConvert.DeserializeObject(samplePrimaryDownloadCommand()); + jsonPSDCmd.url = downloadURI; + + // Act + dynamic jsonResult = rsrcServer.PrimaryStorageDownloadCommand(jsonPSDCmd); + + // Assert + JObject ansAsProperty = jsonResult[0]; + dynamic ans = ansAsProperty.GetValue(CloudStackTypes.PrimaryStorageDownloadAnswer); + Assert.True((bool)ans.result, "PrimaryStorageDownloadCommand did not succeed " + ans.details); + + // Test that URL of downloaded template works for file creation. + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(CreateCommandSample()); + jsonCreateCmd.templateUrl = ans.installPath; + dynamic jsonAns2 = rsrcServer.CreateCommand(jsonCreateCmd); + JObject ansAsProperty2 = jsonAns2[0]; + dynamic ans2 = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + + Assert.True((bool)ans2.result, (string)ans2.details); + + FileInfo newFile = new FileInfo((string)ans2.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + private string samplePrimaryDownloadCommand() + { + String cmdJson = "{\"localPath\":" + testLocalStorePathJSON + + ",\"poolUuid\":\"" + testLocalStoreUUID + "\",\"poolId\":201," + + "\"secondaryStorageUrl\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + + "\"primaryStorageUrl\":\"nfs://" + HypervResourceController.config.StorageIpAddress + "E:\\\\Disks\\\\Disks\"," + + "\"url\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + + "\"format\":\"VHDX\",\"accountId\":2,\"name\":\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + + ",\"contextMap\":{},\"wait\":10800}"; + return cmdJson; + } + + public string CreateCommandSample() + { + String sample = "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":17,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"wait\":0}"; + return sample; + } + + [Fact(Skip="these are functional tests")] + public void TestDestroyCommand() + { + // Arrange + String sampleVolume = getSampleVolumeObjectTO(); + String destoryCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; + "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + testLocalStorePathJSON + + ",\"path\":" + testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonDestoryCmd = JsonConvert.DeserializeObject(destoryCmd); + + // Act + dynamic destoryAns = rsrcServer.DestroyCommand(jsonDestoryCmd); + + // Assert + JObject ansAsProperty2 = destoryAns[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); + String path = jsonDestoryCmd.volume.path; + Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); + Assert.True(!File.Exists(path), "Failed to delete file " + path); + } + + [Fact(Skip="these are functional tests")] + public void TestCreateCommand() + { + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + + Assert.True(Directory.Exists(testLocalStorePath)); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + /// + /// Possible additional tests: place an ISO in the drive + /// + [Fact(Skip="these are functional tests")] + public void TestStartStopCommand() + { + string vmName = TestStartCommand(); + TestStopCommand(vmName); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandFromCifs() + { + // Arrange + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testCifsPath + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.NfsTO\":" + + "{\"_url\":\"" + testCifsUrl + "\"," + // Unique item here + "\"_role\":\"Image\"}" + + "}," + // end of imageDataStore + "\"hypervisorType\":\"Hyperv\"," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"Test of CIFS Download\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"," + + "\"hypervisorType\":\"Hyperv\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetupCifs(null, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommand() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHDX\"," + + "\"accountId\":1," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":3," + + "\"id\":10 }" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + //"name":"ROOT-8","size":140616708,"volumeId":8,"vmName":"s-8-VM","accountId":1,"id":8}},"contextMap":{},"wait":0} + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testS3TemplateName + ".vhdx" + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CreateVolumeFromTemplate(HypervResourceController rsrcServer, dynamic jsonCloneCopyCmd, string newVolName) + { + dynamic copyResult = rsrcServer.CopyCommand(jsonCloneCopyCmd); + + // Assert + Assert.NotNull(copyResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)copyResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + copyResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(newVolName), "CopyCommand failed to generate " + newVolName); + } + + private static void DownloadTemplateToPrimaryStorage(HypervResourceController rsrcServer, dynamic jsonDownloadCopyCmd, string dwnldDest) + { + dynamic dwnldResult = rsrcServer.CopyCommand(jsonDownloadCopyCmd); + + // Assert + Assert.NotNull(dwnldResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)dwnldResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + dwnldResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(dwnldDest), "CopyCommand failed to generate " + dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandBz2Img() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\":\"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":1," + + "\"id\":10}" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testSystemVMTemplateName + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CopyCommandTestSetup(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + jsonCloneCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandToCreateVolumeFromTemplate); + VolumeObjectTO newVol = VolumeObjectTO.ParseJson(jsonCloneCopyCmd.destTO); + newVol.format = dwnldTemplate.format; + newVolName = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + if (File.Exists(newVolName)) + { + File.Delete(newVolName); + } + } + + private static void CopyCommandTestSetupCifs(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + newVolName = null; + jsonCloneCopyCmd = null; + } + + [Fact(Skip="these are functional tests")] + public void TestModifyStoragePoolCommand() + { + // Create dummy folder + String folderName = Path.Combine(".", "Dummy"); + if (!Directory.Exists(folderName)) + { + Directory.CreateDirectory(folderName); + } + + var pool = new + { // From java class StorageFilerTO + type = Enum.GetName(typeof(StoragePoolType), StoragePoolType.Filesystem), + host = "127.0.0.1", + port = -1, + path = folderName, + uuid = Guid.NewGuid().ToString(), + userInfo = string.Empty // Used in future to hold credential + }; + + var cmd = new + { + add = true, + pool = pool, + localPath = folderName + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.ModifyStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.ModifyStoragePoolAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + + // Clean up + var cmd2 = new + { + pool = pool, + localPath = folderName + }; + JToken tok2 = JToken.FromObject(cmd); + + // Act + dynamic jsonResult2 = controller.DeleteStoragePoolCommand(tok2); + + // Assert + dynamic ans2 = jsonResult2[0][CloudStackTypes.Answer]; + Assert.True((bool)ans2.result, (string)ans2.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void CreateStoragePoolCommand() + { + var cmd = new { localPath = "NULL" }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.CreateStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.Answer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void MaintainCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.MaintainCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.MaintainAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void SetupCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { multipath = false, needSetup = true }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.SetupCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.SetupAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void TestPassingUserdataToVm() + { + // Sample data + String key = "cloudstack-vm-userdata"; + String value = "username=root;password=1pass@word1"; + + // Find the VM + List vmNames = wmiCallsV2.GetVmElementNames(); + + // Get associated WMI object + var vm = wmiCallsV2.GetComputerSystem(AgentSettings.Default.testKvpVmName); + + // Get existing KVP + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + string[] kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key) + { + wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + break; + } + } + + // Add new user data + wmiCallsV2.AddUserData(vm, value); + + // Verify key added to subsystem + kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + bool userDataInPlace = false; + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key && existingValue == value) + { +// wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + userDataInPlace = true; + break; + } + } + + Assert.True(userDataInPlace, "User data key / value did no save properly"); + } + + private static void ParseKVP(String wmiObjectXml, out String existingKey, out String existingValue) + { + // Reference: http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/12/05/enumerating-parent-kvp-data.aspx + + // Create XML parser + var xmlDoc = new XmlDocument(); + + // Load WMI object + xmlDoc.LoadXml(wmiObjectXml); + + // Use xpath to get name and value + var namePropXpath = "/INSTANCE/PROPERTY[@NAME='Name']/VALUE"; + var nameNode = xmlDoc.SelectSingleNode(namePropXpath); + existingKey = nameNode.InnerText; + var dataPropXpath = "/INSTANCE/PROPERTY[@NAME='Data']/VALUE"; + var dataNode = xmlDoc.SelectSingleNode(dataPropXpath); + existingValue = dataNode.InnerText; + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommandFail() + { + // Use WMI to find existing VMs + List vmNames = new List(); + vmNames.Add("FakeVM"); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds, fake VM means no answer for the named VM + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommand() + { + // Use WMI to find existing VMs + List vmNames = wmiCallsV2.GetVmElementNames(); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + } + + [Fact(Skip="these are functional tests")] + public void GetStorageStatsCommand() + { + // TODO: Update sample data to unsure it is using correct info. + String sample = String.Format( + #region string_literal +"{{\"" + + "id\":{0}," + + "\"localPath\":{1}," + + "\"pooltype\":\"Filesystem\"," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStoreUUID), + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStorePath) + ); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetStorageStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetStorageStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + Assert.True((long)ans.used <= (long)ans.capacity); // TODO: verify that capacity is indeed capacity and not used. + } + + // TODO: can we speed up this command? The logic takes over a second. + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommand() + { + // Arrange + long hostIdVal = 5; + HypervResourceController controller = new HypervResourceController(); + string sample = string.Format( + #region string_literal +"{{" + + "\"hostGuid\":\"B4AE5970-FCBF-4780-9F8A-2D2E04FECC34-HypervResource\"," + + "\"hostName\":\"CC-SVR11\"," + + "\"hostId\":{0}," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(hostIdVal)); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.True((bool)ans.result); + Assert.True(hostIdVal == (long)ans.hostStats.hostId); + Assert.True(0.0 < (double)ans.hostStats.totalMemoryKBs); + Assert.True(0.0 < (double)ans.hostStats.freeMemoryKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkReadKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkWriteKBs); + Assert.True(0.0 <= (double)ans.hostStats.cpuUtilization); + Assert.True(100.0 >= (double)ans.hostStats.cpuUtilization); + Assert.True("host".Equals((string)ans.hostStats.entityType)); + Assert.True(String.IsNullOrEmpty((string)ans.details)); + } + + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommandFail() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + var cmd = new { GetHostStatsCommand = new { hostId = "badvalueType" } }; + JToken tokFail = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tokFail); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.False((bool)ans.result); + Assert.Null((string)ans.hostStats); + Assert.NotNull(ans.details); + } + + [Fact(Skip="these are functional tests")] + public void TestStartupCommand() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + String sampleStartupRoutingCommand = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":0," + + "\"speed\":0," + + "\"memory\":0," + + "\"dom0MinMemory\":0," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"1\"," + + "\"storageIpAddress\":\"1\"," + + "\"contextMap\":{}," + + "\"wait\":0}}]"; + #endregion + + uint cores; + uint mhz; + wmiCallsV2.GetProcessorResources(out cores, out mhz); + ulong memory_mb; + ulong freememory; + wmiCallsV2.GetMemoryResources(out memory_mb, out freememory); + memory_mb *= 1024; + long capacityBytes; + long availableBytes; + HypervResourceController.GetCapacityForLocalPath(wmiCallsV2.GetDefaultVirtualDiskFolder(), + out capacityBytes, out availableBytes); + var DefaultVirtualDiskFolder = JsonConvert.SerializeObject(wmiCallsV2.GetDefaultVirtualDiskFolder()); + string expected = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":" + cores + "," + + "\"speed\":" + mhz + "," + + "\"memory\":" + memory_mb + "," + + "\"dom0MinMemory\":" + (AgentSettings.Default.dom0MinMemory * 1024 * 1024) + "," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"storageIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"contextMap\":{}," + + "\"wait\":0," + + "\"privateNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"privateMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"storageNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"storageMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"gatewayIpAddress\":\"" + AgentSettings.Default.gateway_ip_address + "\"" + + ",\"caps\":\"hvm\"" + + "}}," + + "{\"com.cloud.agent.api.StartupStorageCommand\":{" + + "\"poolInfo\":{" + + "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"host\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"localPath\":" + DefaultVirtualDiskFolder + "," + + "\"hostPath\":" + DefaultVirtualDiskFolder + "," + + "\"poolType\":\"Filesystem\"," + + "\"capacityBytes\":" + capacityBytes + "," + + "\"availableBytes\":" + availableBytes + "," + + "\"details\":null" + + "}," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"dataCenter\":\"1\"," + + "\"resourceType\":\"STORAGE_POOL\"" + + "}}]"; + #endregion + + dynamic jsonArray = JsonConvert.DeserializeObject(sampleStartupRoutingCommand); + + // Act + dynamic jsonResult = controller.StartupCommand(jsonArray); + + // Assert + string actual = JsonConvert.SerializeObject(jsonResult); + Assert.Equal(expected, actual); + } + + + private static string TestStartCommand() + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + string vmCmdName = jsonStartCmd.vm.name.Value; + var vm = wmiCallsV2.GetComputerSystem(vmCmdName); + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var memSettings = wmiCallsV2.GetMemSettings(vmSettings); + var procSettings = wmiCallsV2.GetProcSettings(vmSettings); + dynamic jsonObj = JsonConvert.DeserializeObject(sample); + var vmInfo = jsonObj.vm; + string vmName = vmInfo.name; + var nicInfo = vmInfo.nics; + int vcpus = vmInfo.cpus; + int memSize = vmInfo.maxRam / 1048576; + Assert.True((long)memSettings.VirtualQuantity == memSize); + Assert.True((long)memSettings.Reservation == memSize); + Assert.True((long)memSettings.Limit == memSize); + Assert.True((int)procSettings.VirtualQuantity == vcpus); + Assert.True((int)procSettings.Reservation == vcpus); + Assert.True((int)procSettings.Limit == 100000); + + // examine NIC for correctness + var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm); + Assert.True(nicSettingsViaVm.Length > 0, "Should be at least one ethernet port on VM"); + string expectedMac = (string)jsonStartCmd.vm.nics[0].mac; + string strippedExpectedMac = expectedMac.Replace(":", string.Empty); + Assert.Equal(nicSettingsViaVm[0].Address.ToLower(), strippedExpectedMac.ToLower()); + + // Assert switchport has correct VLAN + var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm); + var vlanSettings = wmiCallsV2.GetVlanSettings(ethernetConnections[0]); + string isolationUri = (string)jsonStartCmd.vm.nics[0].isolationUri; + string vlan = isolationUri.Replace("vlan://", string.Empty); + Assert.Equal(vlanSettings.AccessVlanId.ToString(), vlan); + + return vmName; + } + + private static void TestStopCommand(string vmName) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + var finalVm = wmiCallsV2.GetComputerSystem(vmName); + Assert.True(wmiCallsV2.GetComputerSystem(vmName) == null); + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj index 2e7a93cd747..de35f68fe85 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/ServerResource.Tests.csproj @@ -1,136 +1,136 @@ - - - - Debug - AnyCPU - - - 2.0 - {925FD1DE-6211-4E10-9949-3751B8ABDF59} - Library - Properties - ServerResource.Tests - ServerResource.Tests - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\NoUnitTestsDebug\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\NoUnitTests\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll - - - ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll - - - ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll - - - - ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll - - - ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll - - - - - - - - - - - - - - - - - - - - ..\packages\xunit.1.9.2\lib\net20\xunit.dll - - - - - - - - - - Designer - - - - - Designer - - - - - {9060b539-62d0-4e71-a6c6-5944828774e9} - AgentShell - - - {c963dfff-65ba-4e71-ada5-526a4da4e0b2} - HypervResource - - - {db824727-bdc3-437c-a364-7a811d8a160f} - WmiWrappers - - - - + + + + Debug + AnyCPU + + + 2.0 + {925FD1DE-6211-4E10-9949-3751B8ABDF59} + Library + Properties + ServerResource.Tests + ServerResource.Tests + v4.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + + + + + + + + + + + + + + + + + + + + ..\packages\xunit.1.9.2\lib\net20\xunit.dll + + + + + + + + + + + Designer + + + + + Designer + + + + + {9060b539-62d0-4e71-a6c6-5944828774e9} + AgentShell + + + {c963dfff-65ba-4e71-ada5-526a4da4e0b2} + HypervResource + + + {db824727-bdc3-437c-a364-7a811d8a160f} + WmiWrappers + + + + - - - - - + --> + + + + + \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ComputerSystem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ComputerSystem.cs deleted file mode 100644 index 082db9dca61..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ComputerSystem.cs +++ /dev/null @@ -1,1298 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ComputerSystem - public class ComputerSystem : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ComputerSystem"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ComputerSystem() { - this.InitializeObject(null, null, null); - } - - public ComputerSystem(string keyCreationClassName, string keyName) { - this.InitializeObject(null, new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); - } - - public ComputerSystem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ComputerSystem(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ComputerSystem(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ComputerSystem(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of NUMA nodes that are currently assigned to the virtual machine.")] - public ushort[] AssignedNumaNodeList { - get { - return ((ushort[])(curObj["AssignedNumaNodeList"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Dedicated { - get { - return ((ushort[])(curObj["Dedicated"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOnTimeInMillisecondsNull { - get { - if ((curObj["OnTimeInMilliseconds"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"For the virtual system, this property describes the total up time, in milliseconds, since the machine was last turned on, reset, or restored. This time excludes the time the virtual system was in the paused state. For the host system, this property is set to NULL.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong OnTimeInMilliseconds { - get { - if ((curObj["OnTimeInMilliseconds"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["OnTimeInMilliseconds"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherDedicatedDescriptions { - get { - return ((string[])(curObj["OtherDedicatedDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProcessIDNull { - get { - if ((curObj["ProcessID"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The identifier of the process under which this virtual machine is running. This v" + - "alue can be used to uniquely identify the instance of Vmwp.exe on the system tha" + - "t is running the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint ProcessID { - get { - if ((curObj["ProcessID"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["ProcessID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResetCapabilityNull { - get { - if ((curObj["ResetCapability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResetCapability { - get { - if ((curObj["ResetCapability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResetCapability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Roles { - get { - return ((string[])(curObj["Roles"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastConfigurationChangeNull { - get { - if ((curObj["TimeOfLastConfigurationChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The date and time when the virtual machine configuration file was last modified. " + - "The configuration file is modified during certain virtual machine operations, as" + - " well as when any of the virtual machine or device settings are added, modified," + - " or removed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastConfigurationChange { - get { - if ((curObj["TimeOfLastConfigurationChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastConfigurationChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOnTimeInMilliseconds() { - if ((this.IsOnTimeInMillisecondsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProcessID() { - if ((this.IsProcessIDNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResetCapability() { - if ((this.IsResetCapabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastConfigurationChange() { - if ((this.IsTimeOfLastConfigurationChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName) { - string strPath = "ROOT\\virtualization:Msvm_ComputerSystem"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ComputerSystemCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ComputerSystemCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ComputerSystemCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ComputerSystem"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ComputerSystemCollection(clsObject.GetInstances(enumOptions)); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ComputerSystem", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ComputerSystemCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ComputerSystem CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ComputerSystem(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(UInt16 RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) - { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((UInt16)(RequestedState)); - inParams["TimeoutPeriod"] = null; // "0"; // ToDmtfTimeInterval(TimeoutPeriod); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(uint PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((uint)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ComputerSystemCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ComputerSystemCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ComputerSystem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ComputerSystemEnumerator(privColObj.GetEnumerator()); - } - - public class ComputerSystemEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ComputerSystemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ComputerSystem(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ConcreteJob.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ConcreteJob.cs deleted file mode 100644 index 1b4e293452f..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ConcreteJob.cs +++ /dev/null @@ -1,1665 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ConcreteJob - public class ConcreteJob : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - public static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ConcreteJob"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ConcreteJob() { - this.InitializeObject(null, null, null); - } - - public ConcreteJob(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); - } - - public ConcreteJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ConcreteJob(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ConcreteJob(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ConcreteJob(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCancellableNull { - get { - if ((curObj["Cancellable"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether the job can be cancelled. The value of this property does not g" + - "uarantee that a request to cancel the job will succeed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Cancellable { - get { - if ((curObj["Cancellable"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Cancellable"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDeleteOnCompletionNull { - get { - if ((curObj["DeleteOnCompletion"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool DeleteOnCompletion { - get { - if ((curObj["DeleteOnCompletion"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["DeleteOnCompletion"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsElapsedTimeNull { - get { - if ((curObj["ElapsedTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan ElapsedTime { - get { - if ((curObj["ElapsedTime"] != null)) { - return ToTimeSpan(((string)(curObj["ElapsedTime"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorCodeNull { - get { - if ((curObj["ErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ErrorCode { - get { - if ((curObj["ErrorCode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ErrorCode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorSummaryDescription { - get { - return ((string)(curObj["ErrorSummaryDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsJobRunTimesNull { - get { - if ((curObj["JobRunTimes"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint JobRunTimes { - get { - if ((curObj["JobRunTimes"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["JobRunTimes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsJobStateNull { - get { - if ((curObj["JobState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort JobState { - get { - if ((curObj["JobState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["JobState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string JobStatus { - get { - return ((string)(curObj["JobStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLocalOrUtcTimeNull { - get { - if ((curObj["LocalOrUtcTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LocalOrUtcTime { - get { - if ((curObj["LocalOrUtcTime"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LocalOrUtcTime"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Notify { - get { - return ((string)(curObj["Notify"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherRecoveryAction { - get { - return ((string)(curObj["OtherRecoveryAction"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Owner { - get { - return ((string)(curObj["Owner"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPercentCompleteNull { - get { - if ((curObj["PercentComplete"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PercentComplete { - get { - if ((curObj["PercentComplete"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PercentComplete"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPriorityNull { - get { - if ((curObj["Priority"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Priority { - get { - if ((curObj["Priority"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Priority"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRecoveryActionNull { - get { - if ((curObj["RecoveryAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RecoveryAction { - get { - if ((curObj["RecoveryAction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RecoveryAction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunDayNull { - get { - if ((curObj["RunDay"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public sbyte RunDay { - get { - if ((curObj["RunDay"] == null)) { - return System.Convert.ToSByte(0); - } - return ((sbyte)(curObj["RunDay"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunDayOfWeekNull { - get { - if ((curObj["RunDayOfWeek"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public sbyte RunDayOfWeek { - get { - if ((curObj["RunDayOfWeek"] == null)) { - return System.Convert.ToSByte(0); - } - return ((sbyte)(curObj["RunDayOfWeek"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunMonthNull { - get { - if ((curObj["RunMonth"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public byte RunMonth { - get { - if ((curObj["RunMonth"] == null)) { - return System.Convert.ToByte(0); - } - return ((byte)(curObj["RunMonth"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunStartIntervalNull { - get { - if ((curObj["RunStartInterval"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan RunStartInterval { - get { - if ((curObj["RunStartInterval"] != null)) { - return ToTimeSpan(((string)(curObj["RunStartInterval"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsScheduledStartTimeNull { - get { - if ((curObj["ScheduledStartTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime ScheduledStartTime { - get { - if ((curObj["ScheduledStartTime"] != null)) { - return ToDateTime(((string)(curObj["ScheduledStartTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartTimeNull { - get { - if ((curObj["StartTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime StartTime { - get { - if ((curObj["StartTime"] != null)) { - return ToDateTime(((string)(curObj["StartTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeBeforeRemovalNull { - get { - if ((curObj["TimeBeforeRemoval"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan TimeBeforeRemoval { - get { - if ((curObj["TimeBeforeRemoval"] != null)) { - return ToTimeSpan(((string)(curObj["TimeBeforeRemoval"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeSubmittedNull { - get { - if ((curObj["TimeSubmitted"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeSubmitted { - get { - if ((curObj["TimeSubmitted"] != null)) { - return ToDateTime(((string)(curObj["TimeSubmitted"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUntilTimeNull { - get { - if ((curObj["UntilTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime UntilTime { - get { - if ((curObj["UntilTime"] != null)) { - return ToDateTime(((string)(curObj["UntilTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCancellable() { - if ((this.IsCancellableNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDeleteOnCompletion() { - if ((this.IsDeleteOnCompletionNull == false)) { - return true; - } - return false; - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - private bool ShouldSerializeElapsedTime() { - if ((this.IsElapsedTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCode() { - if ((this.IsErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeJobRunTimes() { - if ((this.IsJobRunTimesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeJobState() { - if ((this.IsJobStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLocalOrUtcTime() { - if ((this.IsLocalOrUtcTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePercentComplete() { - if ((this.IsPercentCompleteNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePriority() { - if ((this.IsPriorityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRecoveryAction() { - if ((this.IsRecoveryActionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunDay() { - if ((this.IsRunDayNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunDayOfWeek() { - if ((this.IsRunDayOfWeekNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunMonth() { - if ((this.IsRunMonthNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunStartInterval() { - if ((this.IsRunStartIntervalNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeScheduledStartTime() { - if ((this.IsScheduledStartTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStartTime() { - if ((this.IsStartTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeBeforeRemoval() { - if ((this.IsTimeBeforeRemovalNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeSubmitted() { - if ((this.IsTimeSubmittedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUntilTime() { - if ((this.IsUntilTimeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_ConcreteJob"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ConcreteJobCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ConcreteJobCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ConcreteJobCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ConcreteJob"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ConcreteJobCollection(clsObject.GetInstances(enumOptions)); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ConcreteJob", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ConcreteJobCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ConcreteJob CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ConcreteJob(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint GetError(out string Error) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetError", inParams, null); - Error = System.Convert.ToString(outParams.Properties["Error"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Error = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetErrorEx(out string[] Errors) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetErrorEx", inParams, null); - Errors = ((string[])(outParams.Properties["Errors"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Errors = null; - return System.Convert.ToUInt32(0); - } - } - - public uint KillJob(bool DeleteOnKill) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("KillJob"); - inParams["DeleteOnKill"] = ((bool)(DeleteOnKill)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("KillJob", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ConcreteJobCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ConcreteJobCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ConcreteJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ConcreteJobEnumerator(privColObj.GetEnumerator()); - } - - public class ConcreteJobEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ConcreteJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ConcreteJob(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchPort.cs deleted file mode 100644 index a2e44a4111f..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchPort.cs +++ /dev/null @@ -1,1708 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_SwitchPort - public class SwitchPort : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_SwitchPort"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SwitchPort() { - this.InitializeObject(null, null, null); - } - - public SwitchPort(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(SwitchPort.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public SwitchPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SwitchPort.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public SwitchPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SwitchPort(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SwitchPort(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SwitchPort(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The list of IPv4 addresses which are valid in ARP and neighbor Discovery packets. -Each address in the list must point a text string of an IPv4 address in dotted-decimal notation as in ""192.168.16.0"", an example of an IPv4 address in dotted-decimalnotation.")] - public string[] AllowedIPv4Addresses { - get { - return ((string[])(curObj["AllowedIPv4Addresses"])); - } - set { - curObj["AllowedIPv4Addresses"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The list of IPv6 addresses which are valid in ARP and neighbor Discovery packets.The basic string representation consists of 8 hexadecimal numbers separated by colons.A string of consecutive zero numbers may be replaced with a double-colon.There can only be one double-colon in the string representation of the IPv6 address.The last 32 bits may be represented in IPv4-style dotted-octet notationif the address is a IPv4-compatible address.")] - public string[] AllowedIPv6Addresses { - get { - return ((string[])(curObj["AllowedIPv6Addresses"])); - } - set { - curObj["AllowedIPv6Addresses"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAllowMacSpoofingNull { - get { - if ((curObj["AllowMacSpoofing"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether the port will allow MAC spoofing. -TRUE: The port will allow MAC addresses to be spoofed. All valid unicast MAC address values are allowed except those of ports with the AllowMacSpoofing property set to FALSE. -FALSE: The port will allow only MAC addresses configured within Hyper-V management to be used.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AllowMacSpoofing { - get { - if ((curObj["AllowMacSpoofing"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AllowMacSpoofing"])); - } - set { - curObj["AllowMacSpoofing"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBroadcastResetSupportedNull { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BroadcastResetSupported { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BroadcastResetSupported"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsChimneyOffloadLimitNull { - get { - if ((curObj["ChimneyOffloadLimit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current Chimney offloading limit on this port. The limit is the maximum usage" + - " of TCP Chimney Offloading resources on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint ChimneyOffloadLimit { - get { - if ((curObj["ChimneyOffloadLimit"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["ChimneyOffloadLimit"])); - } - set { - curObj["ChimneyOffloadLimit"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsChimneyOffloadUsageNull { - get { - if ((curObj["ChimneyOffloadUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current Chimney offloading usage on this port.The usage is the amount of TCP " + - "Chimney Offloading resources in use on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint ChimneyOffloadUsage { - get { - if ((curObj["ChimneyOffloadUsage"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["ChimneyOffloadUsage"])); - } - set { - curObj["ChimneyOffloadUsage"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsChimneyOffloadWeightNull { - get { - if ((curObj["ChimneyOffloadWeight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The weight assigned to this port for TCP Chimney Offloading. The weight is the relative importance when assigning TCP Chimney Offloading resources. Setting the ChimneyOffloadWeight property to 0 disables TCP Chimney Offloading on the port. The default is 0. -The ChimneyOffloadWeight property is not supported until Windows Server 2008 R2.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint ChimneyOffloadWeight { - get { - if ((curObj["ChimneyOffloadWeight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["ChimneyOffloadWeight"])); - } - set { - curObj["ChimneyOffloadWeight"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTypeDescription { - get { - return ((string)(curObj["OtherTypeDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortNumberNull { - get { - if ((curObj["PortNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortNumber { - get { - if ((curObj["PortNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortNumber"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPreventIPSpoofingNull { - get { - if ((curObj["PreventIPSpoofing"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether the IP spoofing prevention is enabled on the port. -TRUE: IP Spoofing checks will be enabled on ARP and Neighbor Discoverypackets. Router Advertisements and Router redirects will be blocked from the port -FALSE: No IP spoofing checks will be performed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PreventIPSpoofing { - get { - if ((curObj["PreventIPSpoofing"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PreventIPSpoofing"])); - } - set { - curObj["PreventIPSpoofing"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolIFTypeNull { - get { - if ((curObj["ProtocolIFType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolIFType { - get { - if ((curObj["ProtocolIFType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolIFType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolTypeNull { - get { - if ((curObj["ProtocolType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolType { - get { - if ((curObj["ProtocolType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The Azman scope for the switch service. This scope will be used when performing a" + - "ccess checks for the switch service.")] - public string ScopeOfResidence { - get { - return ((string)(curObj["ScopeOfResidence"])); - } - set { - curObj["ScopeOfResidence"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The current status of the object. Operational and non-operational status can be defined. Operational status can include ""OK"", ""Degraded"", and ""Pred Fail"". ""Pred Fail"" indicates whether an element is functioning properly, but is predicting a failure (for example, a SMART-enabled hard drive). -Non-operational status can include ""Error"", ""Starting"", ""Stopping"", and ""Service"". ""Service"" can apply during disk mirror-resilvering, reloading a user permissions list, or other administrative work. Not all such work is online, but the managed element is neither ""OK"" nor in one of the other states.")] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVMQOffloadLimitNull { - get { - if ((curObj["VMQOffloadLimit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current VMQ offloading limit on this port. The limit is the maximum usage of " + - "VMQ offloading resources on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint VMQOffloadLimit { - get { - if ((curObj["VMQOffloadLimit"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["VMQOffloadLimit"])); - } - set { - curObj["VMQOffloadLimit"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVMQOffloadUsageNull { - get { - if ((curObj["VMQOffloadUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current VMQ offloading usage on this port. The usage is the amount of VMQ res" + - "ources in use on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint VMQOffloadUsage { - get { - if ((curObj["VMQOffloadUsage"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["VMQOffloadUsage"])); - } - set { - curObj["VMQOffloadUsage"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVMQOffloadWeightNull { - get { - if ((curObj["VMQOffloadWeight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The weight assigned to this port for virtual machine queue (VMQ) offloading. The " + - "weight is the relative importance when assigning VMQ resources. Setting the VMQO" + - "ffloadWeight property to 0 disables VMQ on the port. The default is 100.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint VMQOffloadWeight { - get { - if ((curObj["VMQOffloadWeight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["VMQOffloadWeight"])); - } - set { - curObj["VMQOffloadWeight"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private void ResetAllowedIPv4Addresses() { - curObj["AllowedIPv4Addresses"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetAllowedIPv6Addresses() { - curObj["AllowedIPv6Addresses"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAllowMacSpoofing() { - if ((this.IsAllowMacSpoofingNull == false)) { - return true; - } - return false; - } - - private void ResetAllowMacSpoofing() { - curObj["AllowMacSpoofing"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeBroadcastResetSupported() { - if ((this.IsBroadcastResetSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeChimneyOffloadLimit() { - if ((this.IsChimneyOffloadLimitNull == false)) { - return true; - } - return false; - } - - private void ResetChimneyOffloadLimit() { - curObj["ChimneyOffloadLimit"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeChimneyOffloadUsage() { - if ((this.IsChimneyOffloadUsageNull == false)) { - return true; - } - return false; - } - - private void ResetChimneyOffloadUsage() { - curObj["ChimneyOffloadUsage"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeChimneyOffloadWeight() { - if ((this.IsChimneyOffloadWeightNull == false)) { - return true; - } - return false; - } - - private void ResetChimneyOffloadWeight() { - curObj["ChimneyOffloadWeight"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortNumber() { - if ((this.IsPortNumberNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePreventIPSpoofing() { - if ((this.IsPreventIPSpoofingNull == false)) { - return true; - } - return false; - } - - private void ResetPreventIPSpoofing() { - curObj["PreventIPSpoofing"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeProtocolIFType() { - if ((this.IsProtocolIFTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolType() { - if ((this.IsProtocolTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private void ResetScopeOfResidence() { - curObj["ScopeOfResidence"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVMQOffloadLimit() { - if ((this.IsVMQOffloadLimitNull == false)) { - return true; - } - return false; - } - - private void ResetVMQOffloadLimit() { - curObj["VMQOffloadLimit"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeVMQOffloadUsage() { - if ((this.IsVMQOffloadUsageNull == false)) { - return true; - } - return false; - } - - private void ResetVMQOffloadUsage() { - curObj["VMQOffloadUsage"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeVMQOffloadWeight() { - if ((this.IsVMQOffloadWeightNull == false)) { - return true; - } - return false; - } - - private void ResetVMQOffloadWeight() { - curObj["VMQOffloadWeight"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_SwitchPort"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SwitchPortCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SwitchPortCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SwitchPortCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SwitchPortCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SwitchPort"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SwitchPortCollection(clsObject.GetInstances(enumOptions)); - } - - public static SwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SwitchPort", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SwitchPortCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SwitchPort CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SwitchPort(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint BroadcastReset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("BroadcastReset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class SwitchPortCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SwitchPortCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SwitchPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SwitchPortEnumerator(privColObj.GetEnumerator()); - } - - public class SwitchPortEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SwitchPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SwitchPort(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpoint.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpoint.cs deleted file mode 100644 index d5c0bb0a52c..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpoint.cs +++ /dev/null @@ -1,1390 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VLANEndpoint - public class VLANEndpoint : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VLANEndpoint"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VLANEndpoint() { - this.InitializeObject(null, null, null); - } - - public VLANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VLANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VLANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VLANEndpoint(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VLANEndpoint(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VLANEndpoint(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBroadcastResetSupportedNull { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BroadcastResetSupported { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BroadcastResetSupported"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDesiredEndpointModeNull { - get { - if ((curObj["DesiredEndpointMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DesiredEndpointMode { - get { - if ((curObj["DesiredEndpointMode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DesiredEndpointMode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDesiredVLANTrunkEncapsulationNull { - get { - if ((curObj["DesiredVLANTrunkEncapsulation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DesiredVLANTrunkEncapsulation { - get { - if ((curObj["DesiredVLANTrunkEncapsulation"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DesiredVLANTrunkEncapsulation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsGVRPStatusNull { - get { - if ((curObj["GVRPStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort GVRPStatus { - get { - if ((curObj["GVRPStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["GVRPStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperationalEndpointModeNull { - get { - if ((curObj["OperationalEndpointMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperationalEndpointMode { - get { - if ((curObj["OperationalEndpointMode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperationalEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperationalVLANTrunkEncapsulationNull { - get { - if ((curObj["OperationalVLANTrunkEncapsulation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperationalVLANTrunkEncapsulation { - get { - if ((curObj["OperationalVLANTrunkEncapsulation"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperationalVLANTrunkEncapsulation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEndpointMode { - get { - return ((string)(curObj["OtherEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTrunkEncapsulation { - get { - return ((string)(curObj["OtherTrunkEncapsulation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTypeDescription { - get { - return ((string)(curObj["OtherTypeDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolIFTypeNull { - get { - if ((curObj["ProtocolIFType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolIFType { - get { - if ((curObj["ProtocolIFType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolIFType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolTypeNull { - get { - if ((curObj["ProtocolType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolType { - get { - if ((curObj["ProtocolType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The endpoint mode supported by this port.")] - public ushort[] SupportedEndpointModes { - get { - return ((ushort[])(curObj["SupportedEndpointModes"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeBroadcastResetSupported() { - if ((this.IsBroadcastResetSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDesiredEndpointMode() { - if ((this.IsDesiredEndpointModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDesiredVLANTrunkEncapsulation() { - if ((this.IsDesiredVLANTrunkEncapsulationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeGVRPStatus() { - if ((this.IsGVRPStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperationalEndpointMode() { - if ((this.IsOperationalEndpointModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperationalVLANTrunkEncapsulation() { - if ((this.IsOperationalVLANTrunkEncapsulationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolIFType() { - if ((this.IsProtocolIFTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolType() { - if ((this.IsProtocolTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_VLANEndpoint"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VLANEndpointCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VLANEndpointCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VLANEndpointCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VLANEndpointCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VLANEndpoint"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VLANEndpointCollection(clsObject.GetInstances(enumOptions)); - } - - public static VLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VLANEndpoint", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VLANEndpointCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VLANEndpoint CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VLANEndpoint(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint BroadcastReset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("BroadcastReset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VLANEndpointCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VLANEndpointCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VLANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VLANEndpointEnumerator(privColObj.GetEnumerator()); - } - - public class VLANEndpointEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VLANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VLANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitchManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitchManagementService.cs deleted file mode 100644 index 9a4b5d2f996..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitchManagementService.cs +++ /dev/null @@ -1,1379 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSwitchManagementService - public class VirtualSwitchManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualSwitchManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSwitchManagementService() { - this.InitializeObject(null, null, null); - } - - public VirtualSwitchManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSwitchManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSwitchManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSwitchManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSwitchManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSwitchManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSwitchManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSwitchManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSwitchManagementService"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSwitchManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSwitchManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSwitchManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSwitchManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSwitchManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint BindExternalEthernetPort(System.Management.ManagementPath ExternalEthernetPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("BindExternalEthernetPort"); - inParams["ExternalEthernetPort"] = ((System.Management.ManagementPath)(ExternalEthernetPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("BindExternalEthernetPort", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint ConnectSwitchPort(System.Management.ManagementPath LANEndpoint, System.Management.ManagementPath SwitchPort, out System.Management.ManagementPath ActiveConnection) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ConnectSwitchPort"); - inParams["LANEndpoint"] = ((System.Management.ManagementPath)(LANEndpoint)).Path; - inParams["SwitchPort"] = ((System.Management.ManagementPath)(SwitchPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConnectSwitchPort", inParams, null); - ActiveConnection = null; - if ((outParams.Properties["ActiveConnection"] != null)) { - ActiveConnection = new System.Management.ManagementPath((string)outParams.Properties["ActiveConnection"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ActiveConnection = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateInternalEthernetPort(string FriendlyName, string MACAddress, string Name, out System.Management.ManagementPath CreatedInternalEthernetPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateInternalEthernetPort"); - inParams["FriendlyName"] = ((string)(FriendlyName)); - inParams["MACAddress"] = ((string)(MACAddress)); - inParams["Name"] = ((string)(Name)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateInternalEthernetPort", inParams, null); - CreatedInternalEthernetPort = null; - if ((outParams.Properties["CreatedInternalEthernetPort"] != null)) { - CreatedInternalEthernetPort = new System.Management.ManagementPath((string)outParams.Properties["CreatedInternalEthernetPort"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CreatedInternalEthernetPort = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateInternalEthernetPortDynamicMac(string FriendlyName, string Name, out System.Management.ManagementPath CreatedInternalEthernetPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateInternalEthernetPortDynamicMac"); - inParams["FriendlyName"] = ((string)(FriendlyName)); - inParams["Name"] = ((string)(Name)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateInternalEthernetPortDynamicMac", inParams, null); - CreatedInternalEthernetPort = null; - if ((outParams.Properties["CreatedInternalEthernetPort"] != null)) { - CreatedInternalEthernetPort = new System.Management.ManagementPath((string)outParams.Properties["CreatedInternalEthernetPort"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CreatedInternalEthernetPort = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateSwitch(string FriendlyName, string Name, uint NumLearnableAddresses, string ScopeOfResidence, out System.Management.ManagementPath CreatedVirtualSwitch) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateSwitch"); - inParams["FriendlyName"] = ((string)(FriendlyName)); - inParams["Name"] = ((string)(Name)); - inParams["NumLearnableAddresses"] = ((uint)(NumLearnableAddresses)); - inParams["ScopeOfResidence"] = ((string)(ScopeOfResidence)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateSwitch", inParams, null); - CreatedVirtualSwitch = null; - if ((outParams.Properties["CreatedVirtualSwitch"] != null)) { - CreatedVirtualSwitch = new System.Management.ManagementPath((string)outParams.Properties["CreatedVirtualSwitch"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CreatedVirtualSwitch = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateSwitchPort(string FriendlyName, string Name, string ScopeOfResidence, System.Management.ManagementPath VirtualSwitch, out System.Management.ManagementPath CreatedSwitchPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateSwitchPort"); - inParams["FriendlyName"] = ((string)(FriendlyName)); - inParams["Name"] = ((string)(Name)); - inParams["ScopeOfResidence"] = ((string)(ScopeOfResidence)); - inParams["VirtualSwitch"] = ((System.Management.ManagementPath)(VirtualSwitch)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateSwitchPort", inParams, null); - CreatedSwitchPort = null; - if ((outParams.Properties["CreatedSwitchPort"] != null)) { - CreatedSwitchPort = new System.Management.ManagementPath((string)outParams.Properties["CreatedSwitchPort"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CreatedSwitchPort = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DeleteInternalEthernetPort(System.Management.ManagementPath InternalEthernetPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DeleteInternalEthernetPort"); - inParams["InternalEthernetPort"] = ((System.Management.ManagementPath)(InternalEthernetPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DeleteInternalEthernetPort", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint DeleteSwitch(System.Management.ManagementPath VirtualSwitch) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DeleteSwitch"); - inParams["VirtualSwitch"] = ((System.Management.ManagementPath)(VirtualSwitch)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DeleteSwitch", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint DeleteSwitchPort(System.Management.ManagementPath SwitchPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DeleteSwitchPort"); - inParams["SwitchPort"] = ((System.Management.ManagementPath)(SwitchPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DeleteSwitchPort", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint DisconnectSwitchPort(System.Management.ManagementPath SwitchPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DisconnectSwitchPort"); - inParams["SwitchPort"] = ((System.Management.ManagementPath)(SwitchPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DisconnectSwitchPort", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetupSwitch(System.Management.ManagementPath ExternalEthernetPort, System.Management.ManagementPath ExternalSwitchPort, string InternalEthernetPortFriendlyName, string InternalEthernetPortName, System.Management.ManagementPath InternalSwitchPort, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetupSwitch"); - inParams["ExternalEthernetPort"] = ((System.Management.ManagementPath)(ExternalEthernetPort)).Path; - inParams["ExternalSwitchPort"] = ((System.Management.ManagementPath)(ExternalSwitchPort)).Path; - inParams["InternalEthernetPortFriendlyName"] = ((string)(InternalEthernetPortFriendlyName)); - inParams["InternalEthernetPortName"] = ((string)(InternalEthernetPortName)); - inParams["InternalSwitchPort"] = ((System.Management.ManagementPath)(InternalSwitchPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetupSwitch", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint TeardownSwitch(System.Management.ManagementPath ExternalEthernetPort, System.Management.ManagementPath InternalEthernetPort, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("TeardownSwitch"); - inParams["ExternalEthernetPort"] = ((System.Management.ManagementPath)(ExternalEthernetPort)).Path; - inParams["InternalEthernetPort"] = ((System.Management.ManagementPath)(InternalEthernetPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("TeardownSwitch", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint UnbindExternalEthernetPort(System.Management.ManagementPath ExternalEthernetPort) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("UnbindExternalEthernetPort"); - inParams["ExternalEthernetPort"] = ((System.Management.ManagementPath)(ExternalEthernetPort)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("UnbindExternalEthernetPort", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSwitchManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSwitchManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSwitchManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSwitchManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSwitchManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSwitchManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSwitchManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemGlobalSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemGlobalSettingData.cs deleted file mode 100644 index bb484c25f19..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemGlobalSettingData.cs +++ /dev/null @@ -1,1513 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemGlobalSettingData - public class VirtualSystemGlobalSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualSystemGlobalSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemGlobalSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemGlobalSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemGlobalSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemGlobalSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemGlobalSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Any additional information provided to the recovery action. The meaning of this property is defined by the action in AutomaticRecoveryAction. If AutomaticRecoveryAction is 0 (""None"") or 1 (""Restart""), this value is NULL. If AutomaticRecoveryAction is 2 (""Revert to Snapshot""), this is the object path to a snapshot that should be applied on failure of the virtual machine worker process. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public string AdditionalRecoveryInformation { - get { - return ((string)(curObj["AdditionalRecoveryInformation"])); - } - set { - curObj["AdditionalRecoveryInformation"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAllowFullSCSICommandSetNull { - get { - if ((curObj["AllowFullSCSICommandSet"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether SCSI commands from the guest operating system are passed to pass-through disks. If TRUE, SCSI commands emitted by the guest operating system to pass-through disks are not filtered.It is recommended that SCSI filtering remains enabled for production deployments. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class. -Windows Server 2008: The AllowFullSCSICommandSet property is not supported.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AllowFullSCSICommandSet { - get { - if ((curObj["AllowFullSCSICommandSet"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AllowFullSCSICommandSet"])); - } - set { - curObj["AllowFullSCSICommandSet"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoActivateNull { - get { - if ((curObj["AutoActivate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoActivate { - get { - if ((curObj["AutoActivate"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoActivate"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticRecoveryActionNull { - get { - if ((curObj["AutomaticRecoveryAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The action to be taken if the virtual machine worker process terminates abnormally. The default action is 1 (""Restart""). -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public AutomaticRecoveryActionValues AutomaticRecoveryAction { - get { - if ((curObj["AutomaticRecoveryAction"] == null)) { - return ((AutomaticRecoveryActionValues)(System.Convert.ToInt32(3))); - } - return ((AutomaticRecoveryActionValues)(System.Convert.ToInt32(curObj["AutomaticRecoveryAction"]))); - } - set { - if ((AutomaticRecoveryActionValues.NULL_ENUM_VALUE == value)) { - curObj["AutomaticRecoveryAction"] = null; - } - else { - curObj["AutomaticRecoveryAction"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticShutdownActionNull { - get { - if ((curObj["AutomaticShutdownAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The action to take when the host is shut down. The default action is 1 (\"Save Sta" + - "te\").\nThis is a read-only property, but it can be changed using the ModifyVirtua" + - "lSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public AutomaticShutdownActionValues AutomaticShutdownAction { - get { - if ((curObj["AutomaticShutdownAction"] == null)) { - return ((AutomaticShutdownActionValues)(System.Convert.ToInt32(3))); - } - return ((AutomaticShutdownActionValues)(System.Convert.ToInt32(curObj["AutomaticShutdownAction"]))); - } - set { - if ((AutomaticShutdownActionValues.NULL_ENUM_VALUE == value)) { - curObj["AutomaticShutdownAction"] = null; - } - else { - curObj["AutomaticShutdownAction"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticStartupActionNull { - get { - if ((curObj["AutomaticStartupAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The action to be taken when the host is started. The default action is 1 (\"Restar" + - "t if Previously Running\").\nThis is a read-only property, but it can be changed u" + - "sing the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService c" + - "lass.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public AutomaticStartupActionValues AutomaticStartupAction { - get { - if ((curObj["AutomaticStartupAction"] == null)) { - return ((AutomaticStartupActionValues)(System.Convert.ToInt32(3))); - } - return ((AutomaticStartupActionValues)(System.Convert.ToInt32(curObj["AutomaticStartupAction"]))); - } - set { - if ((AutomaticStartupActionValues.NULL_ENUM_VALUE == value)) { - curObj["AutomaticStartupAction"] = null; - } - else { - curObj["AutomaticStartupAction"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticStartupActionDelayNull { - get { - if ((curObj["AutomaticStartupActionDelay"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time interval to wait before performing the startup action. By default, there" + - " is no delay.\nThis is a read-only property, but it can be changed using the Modi" + - "fyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan AutomaticStartupActionDelay { - get { - if ((curObj["AutomaticStartupActionDelay"] != null)) { - return ToTimeSpan(((string)(curObj["AutomaticStartupActionDelay"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - set { - curObj["AutomaticStartupActionDelay"] = ToDmtfTimeInterval(((System.TimeSpan)(value))); - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCreationTimeNull { - get { - if ((curObj["CreationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime CreationTime { - get { - if ((curObj["CreationTime"] != null)) { - return ToDateTime(((string)(curObj["CreationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugChannelIdNull { - get { - if ((curObj["DebugChannelId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The channel identifier used to debug the virtual system using the VUD unified deb" + - "ugger.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint DebugChannelId { - get { - if ((curObj["DebugChannelId"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["DebugChannelId"])); - } - set { - curObj["DebugChannelId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugPortNull { - get { - if ((curObj["DebugPort"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The tcpip port used to debug the virtual system using synthetic debugging.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint DebugPort { - get { - if ((curObj["DebugPort"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["DebugPort"])); - } - set { - curObj["DebugPort"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugPortEnabledNull { - get { - if ((curObj["DebugPortEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Whether the virtual system is using synthetic debugging.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public DebugPortEnabledValues DebugPortEnabled { - get { - if ((curObj["DebugPortEnabled"] == null)) { - return ((DebugPortEnabledValues)(System.Convert.ToInt32(3))); - } - return ((DebugPortEnabledValues)(System.Convert.ToInt32(curObj["DebugPortEnabled"]))); - } - set { - if ((DebugPortEnabledValues.NULL_ENUM_VALUE == value)) { - curObj["DebugPortEnabled"] = null; - } - else { - curObj["DebugPortEnabled"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The fully-qualified path to the root directory of the virtual machine's data store. This store is managed by the virtual system management service and may contain private data from multiple virtual systems. This property may only be specified at the time the virtual machine is defined. -This is a read-only property, but it can be changed before the virtual machine is created using the DefineVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public string ExternalDataRoot { - get { - return ((string)(curObj["ExternalDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherVirtualSystemType { - get { - return ((string)(curObj["OtherVirtualSystemType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The authorization scope to use in determining the access control policy for this " + - "virtual system.\nThis is a read-only property, but it can be changed using the Mo" + - "difyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public string ScopeOfResidence { - get { - return ((string)(curObj["ScopeOfResidence"])); - } - set { - curObj["ScopeOfResidence"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSettingTypeNull { - get { - if ((curObj["SettingType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public SettingTypeValues SettingType { - get { - if ((curObj["SettingType"] == null)) { - return ((SettingTypeValues)(System.Convert.ToInt32(0))); - } - return ((SettingTypeValues)(System.Convert.ToInt32(curObj["SettingType"]))); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The fully-qualified path to the root directory of the data store used to store snapshots for this virtual system. This store is managed by the virtual system management service and may contain private data from multiple virtual systems. This property may only be changed if the virtual system has no snapshots. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public string SnapshotDataRoot { - get { - return ((string)(curObj["SnapshotDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The version of the virtual system in a format of \"major.minor\", for example \"2.0\"" + - ".\nWindows Server 2008: The Version property is not supported.")] - public string Version { - get { - return ((string)(curObj["Version"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualSystemTypeNull { - get { - if ((curObj["VirtualSystemType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort VirtualSystemType { - get { - if ((curObj["VirtualSystemType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["VirtualSystemType"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private void ResetAdditionalRecoveryInformation() { - curObj["AdditionalRecoveryInformation"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAllowFullSCSICommandSet() { - if ((this.IsAllowFullSCSICommandSetNull == false)) { - return true; - } - return false; - } - - private void ResetAllowFullSCSICommandSet() { - curObj["AllowFullSCSICommandSet"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAutoActivate() { - if ((this.IsAutoActivateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticRecoveryAction() { - if ((this.IsAutomaticRecoveryActionNull == false)) { - return true; - } - return false; - } - - private void ResetAutomaticRecoveryAction() { - curObj["AutomaticRecoveryAction"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAutomaticShutdownAction() { - if ((this.IsAutomaticShutdownActionNull == false)) { - return true; - } - return false; - } - - private void ResetAutomaticShutdownAction() { - curObj["AutomaticShutdownAction"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAutomaticStartupAction() { - if ((this.IsAutomaticStartupActionNull == false)) { - return true; - } - return false; - } - - private void ResetAutomaticStartupAction() { - curObj["AutomaticStartupAction"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - private bool ShouldSerializeAutomaticStartupActionDelay() { - if ((this.IsAutomaticStartupActionDelayNull == false)) { - return true; - } - return false; - } - - private void ResetAutomaticStartupActionDelay() { - curObj["AutomaticStartupActionDelay"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeCreationTime() { - if ((this.IsCreationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDebugChannelId() { - if ((this.IsDebugChannelIdNull == false)) { - return true; - } - return false; - } - - private void ResetDebugChannelId() { - curObj["DebugChannelId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeDebugPort() { - if ((this.IsDebugPortNull == false)) { - return true; - } - return false; - } - - private void ResetDebugPort() { - curObj["DebugPort"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeDebugPortEnabled() { - if ((this.IsDebugPortEnabledNull == false)) { - return true; - } - return false; - } - - private void ResetDebugPortEnabled() { - curObj["DebugPortEnabled"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetScopeOfResidence() { - curObj["ScopeOfResidence"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeSettingType() { - if ((this.IsSettingTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualSystemType() { - if ((this.IsVirtualSystemTypeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSystemGlobalSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemGlobalSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemGlobalSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemGlobalSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemGlobalSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemGlobalSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemGlobalSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemGlobalSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemGlobalSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum AutomaticRecoveryActionValues { - - None = 0, - - Restart = 1, - - Revert_to_Snapshot = 2, - - NULL_ENUM_VALUE = 3, - } - - public enum AutomaticShutdownActionValues { - - Turn_Off = 0, - - Save_State = 1, - - ShutDown = 2, - - NULL_ENUM_VALUE = 3, - } - - public enum AutomaticStartupActionValues { - - None = 0, - - Restart_if_Previously_Running = 1, - - Always_Startup = 2, - - NULL_ENUM_VALUE = 3, - } - - public enum DebugPortEnabledValues { - - Off = 0, - - On = 1, - - OnAutoAssigned = 2, - - NULL_ENUM_VALUE = 3, - } - - public enum SettingTypeValues { - - Input = 1, - - Recorded = 2, - - Current = 3, - - Capability = 4, - - Snapshot = 5, - - Global = 32768, - - NULL_ENUM_VALUE = 0, - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemGlobalSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemGlobalSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemGlobalSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemGlobalSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemGlobalSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemGlobalSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemGlobalSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementService.cs deleted file mode 100644 index 81016a2db23..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementService.cs +++ /dev/null @@ -1,1731 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementService - public class VirtualSystemManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualSystemManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemManagementService() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSystemManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSystemManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemManagementService"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint AddKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint AddVirtualSystemResources(string[] ResourceSettingData, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] NewResources) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddVirtualSystemResources"); - inParams["ResourceSettingData"] = ((string[])(ResourceSettingData)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddVirtualSystemResources", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - NewResources = null; - if ((outParams.Properties["NewResources"] != null) && outParams.Properties["NewResources"].Value != null) - { - int len = ((System.Array)(outParams.Properties["NewResources"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["NewResources"].Value)).GetValue(iCounter).ToString()); - } - NewResources = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - NewResources = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ApplyVirtualSystemSnapshot(System.Management.ManagementPath ComputerSystem, System.Management.ManagementPath SnapshotSettingData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ApplyVirtualSystemSnapshot"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["SnapshotSettingData"] = ((System.Management.ManagementPath)(SnapshotSettingData)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ApplyVirtualSystemSnapshot", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint ApplyVirtualSystemSnapshotEx(System.Management.ManagementPath ComputerSystem, System.Management.ManagementPath SnapshotSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ApplyVirtualSystemSnapshotEx"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["SnapshotSettingData"] = ((System.Management.ManagementPath)(SnapshotSettingData)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ApplyVirtualSystemSnapshotEx", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CheckSystemCompatibilityInfo(byte[] CompatibilityInfo, out string[] Reasons) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CheckSystemCompatibilityInfo"); - inParams["CompatibilityInfo"] = ((byte[])(CompatibilityInfo)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CheckSystemCompatibilityInfo", inParams, null); - Reasons = ((string[])(outParams.Properties["Reasons"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Reasons = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CloneVirtualSystem(System.Management.ManagementPath SourceInstance, System.Management.ManagementPath SourceSystem, out System.Management.ManagementPath ClonedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CloneVirtualSystem"); - inParams["SourceInstance"] = ((System.Management.ManagementPath)(SourceInstance)).Path; - inParams["SourceSystem"] = ((System.Management.ManagementPath)(SourceSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CloneVirtualSystem", inParams, null); - ClonedSystem = null; - if ((outParams.Properties["ClonedSystem"] != null)) { - ClonedSystem = new System.Management.ManagementPath(outParams.Properties["ClonedSystem"].Value.ToString()); - } - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ClonedSystem = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateVirtualSystemSnapshot(System.Management.ManagementPath SourceSystem, out System.Management.ManagementPath Job, out System.Management.ManagementPath SnapshotSettingData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualSystemSnapshot"); - inParams["SourceSystem"] = ((System.Management.ManagementPath)(SourceSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualSystemSnapshot", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - SnapshotSettingData = null; - if ((outParams.Properties["SnapshotSettingData"] != null)) { - SnapshotSettingData = new System.Management.ManagementPath((string)outParams.Properties["SnapshotSettingData"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - SnapshotSettingData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DefineVirtualSystem(string[] ResourceSettingData, string SourceSettingPath, string SystemSettingData, out System.Management.ManagementPath DefinedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DefineVirtualSystem"); - inParams["ResourceSettingData"] = ((string[])(ResourceSettingData)); - inParams["SourceSetting"] = SourceSettingPath; - inParams["SystemSettingData"] = ((string)(SystemSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineVirtualSystem", inParams, null); - DefinedSystem = null; - if ((outParams.Properties["DefinedSystem"] != null)) { - DefinedSystem = new System.Management.ManagementPath((string)outParams.Properties["DefinedSystem"].Value); - } - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - DefinedSystem = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DestroyVirtualSystem(System.Management.ManagementPath ComputerSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DestroyVirtualSystem"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroyVirtualSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ExportVirtualSystem(System.Management.ManagementPath ComputerSystem, bool CopyVmState, string ExportDirectory, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ExportVirtualSystem"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["CopyVmState"] = ((bool)(CopyVmState)); - inParams["ExportDirectory"] = ((string)(ExportDirectory)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportVirtualSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ExportVirtualSystemEx(System.Management.ManagementPath ComputerSystem, string ExportDirectory, string ExportSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ExportVirtualSystemEx"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["ExportDirectory"] = ((string)(ExportDirectory)); - inParams["ExportSettingData"] = ((string)(ExportSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportVirtualSystemEx", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint FormatError(string[] Errors, out string ErrorMessage) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("FormatError"); - inParams["Errors"] = ((string[])(Errors)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("FormatError", inParams, null); - ErrorMessage = System.Convert.ToString(outParams.Properties["ErrorMessage"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ErrorMessage = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetSummaryInformation(uint[] RequestedInformation, System.Management.ManagementPath[] SettingData, out System.Management.ManagementBaseObject[] SummaryInformation) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetSummaryInformation"); - inParams["RequestedInformation"] = ((uint[])(RequestedInformation)); - if ((SettingData != null)) { - int len = ((System.Array)(SettingData)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(SettingData)).GetValue(iCounter))).Path; - } - inParams["SettingData"] = arrProp; - } - else { - inParams["SettingData"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSummaryInformation", inParams, null); - SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - SummaryInformation = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetSystemCompatibilityInfo(System.Management.ManagementPath ComputerSystem, out byte[] CompatibilityInfo) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetSystemCompatibilityInfo"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSystemCompatibilityInfo", inParams, null); - CompatibilityInfo = ((byte[])(outParams.Properties["CompatibilityInfo"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CompatibilityInfo = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualSystemImportSettingData(string ImportDirectory, out System.Management.ManagementBaseObject ImportSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualSystemImportSettingData"); - inParams["ImportDirectory"] = ((string)(ImportDirectory)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualSystemImportSettingData", inParams, null); - ImportSettingData = ((System.Management.ManagementBaseObject)(outParams.Properties["ImportSettingData"].Value)); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ImportSettingData = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualSystemThumbnailImage(ushort HeightPixels, System.Management.ManagementPath TargetSystem, ushort WidthPixels, out byte[] ImageData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualSystemThumbnailImage"); - inParams["HeightPixels"] = ((ushort)(HeightPixels)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - inParams["WidthPixels"] = ((ushort)(WidthPixels)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualSystemThumbnailImage", inParams, null); - ImageData = ((byte[])(outParams.Properties["ImageData"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ImageData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ImportVirtualSystem(bool GenerateNewID, string ImportDirectory, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ImportVirtualSystem"); - inParams["GenerateNewID"] = ((bool)(GenerateNewID)); - inParams["ImportDirectory"] = ((string)(ImportDirectory)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportVirtualSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ImportVirtualSystemEx(string ImportDirectory, string ImportSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ImportVirtualSystemEx"); - inParams["ImportDirectory"] = ((string)(ImportDirectory)); - inParams["ImportSettingData"] = ((string)(ImportSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportVirtualSystemEx", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint InstantiateVirtualSystem(System.Management.ManagementPath VirtualSystemSettingData, out System.Management.ManagementPath ComputerSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("InstantiateVirtualSystem"); - inParams["VirtualSystemSettingData"] = ((System.Management.ManagementPath)(VirtualSystemSettingData)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("InstantiateVirtualSystem", inParams, null); - ComputerSystem = null; - if ((outParams.Properties["ComputerSystem"] != null)) { - ComputerSystem = new System.Management.ManagementPath((string)outParams.Properties["ComputerSystem"].Value); - } - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ComputerSystem = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyServiceSettings(string SettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyServiceSettings"); - inParams["SettingData"] = ((string)(SettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyVirtualSystem(System.Management.ManagementPath ComputerSystem, string SystemSettingData, out System.Management.ManagementPath Job, out System.Management.ManagementPath ModifiedSettingData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyVirtualSystem"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["SystemSettingData"] = ((string)(SystemSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyVirtualSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ModifiedSettingData = null; - if ((outParams.Properties["ModifiedSettingData"] != null)) { - ModifiedSettingData = new System.Management.ManagementPath((string)outParams.Properties["ModifiedSettingData"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ModifiedSettingData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyVirtualSystemResources(System.Management.ManagementPath ComputerSystem, string[] ResourceSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyVirtualSystemResources"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["ResourceSettingData"] = ((string[])(ResourceSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyVirtualSystemResources", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint PlanVirtualSystem(string[] ResourceSettingData, System.Management.ManagementPath SourceSetting, string SystemSettingData, out System.Management.ManagementPath Job, out System.Management.ManagementPath PlannedSystemSettingData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("PlanVirtualSystem"); - inParams["ResourceSettingData"] = ((string[])(ResourceSettingData)); - inParams["SourceSetting"] = ((System.Management.ManagementPath)(SourceSetting)).Path; - inParams["SystemSettingData"] = ((string)(SystemSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("PlanVirtualSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - PlannedSystemSettingData = null; - if ((outParams.Properties["PlannedSystemSettingData"] != null)) { - PlannedSystemSettingData = new System.Management.ManagementPath((string)outParams.Properties["PlannedSystemSettingData"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - PlannedSystemSettingData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveVirtualSystemResources(System.Management.ManagementPath[] ResourceSettingData, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveVirtualSystemResources"); - if ((ResourceSettingData != null)) { - int len = ((System.Array)(ResourceSettingData)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettingData)).GetValue(iCounter))).Path; - } - inParams["ResourceSettingData"] = arrProp; - } - else { - inParams["ResourceSettingData"] = null; - } - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveVirtualSystemResources", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveVirtualSystemSnapshot(System.Management.ManagementPath SnapshotSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveVirtualSystemSnapshot"); - inParams["SnapshotSettingData"] = ((System.Management.ManagementPath)(SnapshotSettingData)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveVirtualSystemSnapshot", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveVirtualSystemSnapshotTree(System.Management.ManagementPath SnapshotSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveVirtualSystemSnapshotTree"); - inParams["SnapshotSettingData"] = ((System.Management.ManagementPath)(SnapshotSettingData)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveVirtualSystemSnapshotTree", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementServiceSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementServiceSettingData.cs deleted file mode 100644 index fde04ac4396..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemManagementServiceSettingData.cs +++ /dev/null @@ -1,731 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData - public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemManagementServiceSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemManagementServiceSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string BiosLockString { - get { - return ((string)(curObj["BiosLockString"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + - "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + - "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultExternalDataRoot { - get { - return ((string)(curObj["DefaultExternalDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + - "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + - "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultVirtualHardDiskPath { - get { - return ((string)(curObj["DefaultVirtualHardDiskPath"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MaximumMacAddress { - get { - return ((string)(curObj["MaximumMacAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MinimumMacAddress { - get { - return ((string)(curObj["MinimumMacAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumaSpanningEnabledNull { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Reserved for future use.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool NumaSpanningEnabled { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["NumaSpanningEnabled"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + - "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + - "ttings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This is a read-only property, but it can be changed using the ModifyServiceSettin" + - "gs method of the Msvm_VirtualSystemManagementService class.")] - public string ScopeOfResidence { - get { - return ((string)(curObj["ScopeOfResidence"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeNumaSpanningEnabled() { - if ((this.IsNumaSpanningEnabledNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSystemManagementServiceSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemManagementServiceSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemManagementServiceSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemSettingData.cs deleted file mode 100644 index ae2b7f80ae8..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSystemSettingData.cs +++ /dev/null @@ -1,1206 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemSettingData - public class VirtualSystemSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualSystemSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoActivateNull { - get { - if ((curObj["AutoActivate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoActivate { - get { - if ((curObj["AutoActivate"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoActivate"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the base board for the virtual computer system.\nThis is a re" + - "ad-only property, but it can be changed using the ModifyVirtualSystem method of " + - "the Msvm_VirtualSystemManagementService class.")] - public string BaseBoardSerialNumber { - get { - return ((string)(curObj["BaseBoardSerialNumber"])); - } - set { - curObj["BaseBoardSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The globally-unique identifier for the BIOS of the virtual computer system.\nThis " + - "is a read-only property, but it can be changed using the ModifyVirtualSystem met" + - "hod of the Msvm_VirtualSystemManagementService class.")] - public string BIOSGUID { - get { - return ((string)(curObj["BIOSGUID"])); - } - set { - curObj["BIOSGUID"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBIOSNumLockNull { - get { - if ((curObj["BIOSNumLock"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"This property is set to TRUE if the num lock key is set to on by the BIOS, FALSE if the num lock key is set to off by the BIOS. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BIOSNumLock { - get { - if ((curObj["BIOSNumLock"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BIOSNumLock"])); - } - set { - curObj["BIOSNumLock"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the BIOS for the virtual computer system.\nThis is a read-onl" + - "y property, but it can be changed using the ModifyVirtualSystem method of the Ms" + - "vm_VirtualSystemManagementService class.")] - public string BIOSSerialNumber { - get { - return ((string)(curObj["BIOSSerialNumber"])); - } - set { - curObj["BIOSSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The boot order set within the BIOS of the virtual computer system. This property is an array of values, max length 4, where each value indicates a device to boot from. The virtual computer system will first attempt to boot from the device indicated by the first value within the array. If that device does not contain a boot sector, the virtual computer system will attempt to boot from the next device specified by the BootOrder property and so on. If no device specified within the BootOrder contains a boot sector the virtual computer system will fail to boot. The default value for a virtual computer system is [0, 1, 2, 3, 4]. -Value definitions: -0 (Floppy): The virtual computer system will attempt to boot from the floppy disk within the floppy drive. -1 (CD-ROM): The virtual computer system will attempt to boot from the first CD or DVD disk found with a boot sector. -2 (IDE Hard Drive): The virtual computer system will attempt to boot from the first hard drive found attached to an IDE controller with a boot sector. -3 (PXE Boot): The virtual computer system will attempt to PXE boot from the network. -4 (SCSI Hard Drive): The virtual computer system will attempt to boot from the first hard drive found attached to a SCSI controller with a boot sector. -5-65535: Reserved -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public ushort[] BootOrder { - get { - return ((ushort[])(curObj["BootOrder"])); - } - set { - curObj["BootOrder"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The asset tag of the chassis for the virtual computer system.\nThis is a read-only" + - " property, but it can be changed using the ModifyVirtualSystem method of the Msv" + - "m_VirtualSystemManagementService class.")] - public string ChassisAssetTag { - get { - return ((string)(curObj["ChassisAssetTag"])); - } - set { - curObj["ChassisAssetTag"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the chassis for the virtual computer system.\nThis is a read-" + - "only property, but it can be changed using the ModifyVirtualSystem method of the" + - " Msvm_VirtualSystemManagementService class.")] - public string ChassisSerialNumber { - get { - return ((string)(curObj["ChassisSerialNumber"])); - } - set { - curObj["ChassisSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCreationTimeNull { - get { - if ((curObj["CreationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime CreationTime { - get { - if ((curObj["CreationTime"] != null)) { - return ToDateTime(((string)(curObj["CreationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("A free-form string containing notes for the system.\nThis is a read-only property," + - " but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualS" + - "ystemManagementService class.")] - public string Notes { - get { - return ((string)(curObj["Notes"])); - } - set { - curObj["Notes"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"For non-uniform memory access (NUMA)-capable systems, this is the list of NUMA nodes on which the virtual machine is to be run. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public ushort[] NumaNodeList { - get { - return ((ushort[])(curObj["NumaNodeList"])); - } - set { - curObj["NumaNodeList"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumaNodesAreRequiredNull { - get { - if ((curObj["NumaNodesAreRequired"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"For non-uniform memory access (NUMA)-capable systems, this value indicates whether the nodes specified in NumaNodeList are required or preferred. If this value is TRUE (the nodes are required), the virtual machine will fail to start if there are not enough resources available on the specified NUMA nodes. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool NumaNodesAreRequired { - get { - if ((curObj["NumaNodesAreRequired"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["NumaNodesAreRequired"])); - } - set { - curObj["NumaNodesAreRequired"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherVirtualSystemType { - get { - return ((string)(curObj["OtherVirtualSystemType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The object path for the snapshot Msvm_VirtualSystemSettingData from which this ob" + - "ject is based. This property will be NULL if this object is not based off a snap" + - "shot.")] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSettingTypeNull { - get { - if ((curObj["SettingType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort SettingType { - get { - if ((curObj["SettingType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["SettingType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualSystemTypeNull { - get { - if ((curObj["VirtualSystemType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort VirtualSystemType { - get { - if ((curObj["VirtualSystemType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["VirtualSystemType"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutoActivate() { - if ((this.IsAutoActivateNull == false)) { - return true; - } - return false; - } - - private void ResetBaseBoardSerialNumber() { - curObj["BaseBoardSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBIOSGUID() { - curObj["BIOSGUID"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeBIOSNumLock() { - if ((this.IsBIOSNumLockNull == false)) { - return true; - } - return false; - } - - private void ResetBIOSNumLock() { - curObj["BIOSNumLock"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBIOSSerialNumber() { - curObj["BIOSSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBootOrder() { - curObj["BootOrder"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetChassisAssetTag() { - curObj["ChassisAssetTag"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetChassisSerialNumber() { - curObj["ChassisSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeCreationTime() { - if ((this.IsCreationTimeNull == false)) { - return true; - } - return false; - } - - private void ResetNotes() { - curObj["Notes"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetNumaNodeList() { - curObj["NumaNodeList"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeNumaNodesAreRequired() { - if ((this.IsNumaNodesAreRequiredNull == false)) { - return true; - } - return false; - } - - private void ResetNumaNodesAreRequired() { - curObj["NumaNodesAreRequired"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeSettingType() { - if ((this.IsSettingTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualSystemType() { - if ((this.IsVirtualSystemTypeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSystemSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VmLANEndpoint.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VmLANEndpoint.cs deleted file mode 100644 index 040882eb748..00000000000 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VmLANEndpoint.cs +++ /dev/null @@ -1,1342 +0,0 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VmLANEndpoint - public class VmLANEndpoint : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VmLANEndpoint"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VmLANEndpoint() { - this.InitializeObject(null, null, null); - } - - public VmLANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VmLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VmLANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VmLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VmLANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VmLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VmLANEndpoint(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VmLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VmLANEndpoint(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VmLANEndpoint(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] AliasAddresses { - get { - return ((string[])(curObj["AliasAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBroadcastResetSupportedNull { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BroadcastResetSupported { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BroadcastResetSupported"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConnectedNull { - get { - if ((curObj["Connected"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Connected { - get { - if ((curObj["Connected"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Connected"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] GroupAddresses { - get { - return ((string[])(curObj["GroupAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string LANID { - get { - return ((string)(curObj["LANID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLANTypeNull { - get { - if ((curObj["LANType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LANType { - get { - if ((curObj["LANType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string MACAddress { - get { - return ((string)(curObj["MACAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLANType { - get { - return ((string)(curObj["OtherLANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTypeDescription { - get { - return ((string)(curObj["OtherTypeDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolIFTypeNull { - get { - if ((curObj["ProtocolIFType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolIFType { - get { - if ((curObj["ProtocolIFType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolIFType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolTypeNull { - get { - if ((curObj["ProtocolType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolType { - get { - if ((curObj["ProtocolType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeBroadcastResetSupported() { - if ((this.IsBroadcastResetSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConnected() { - if ((this.IsConnectedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLANType() { - if ((this.IsLANTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolIFType() { - if ((this.IsProtocolIFTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolType() { - if ((this.IsProtocolTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_VmLANEndpoint"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VmLANEndpointCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VmLANEndpointCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VmLANEndpointCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VmLANEndpointCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VmLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VmLANEndpoint"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VmLANEndpointCollection(clsObject.GetInstances(enumOptions)); - } - - public static VmLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VmLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VmLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VmLANEndpoint", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VmLANEndpointCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VmLANEndpoint CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VmLANEndpoint(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint BroadcastReset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("BroadcastReset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VmLANEndpointCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VmLANEndpointCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VmLANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VmLANEndpointEnumerator(privColObj.GetEnumerator()); - } - - public class VmLANEndpointEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VmLANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VmLANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs index 7c5b0781eb1..e5b225840d3 100755 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs @@ -1447,8 +1447,8 @@ inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestReplicationStateChange", inParams, null); Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1462,12 +1462,13 @@ if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + inParams["RequestedState"] = RequestedState; + inParams["TimeoutPeriod"] = null; // ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs new file mode 100755 index 00000000000..79420850ba1 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs @@ -0,0 +1,1147 @@ +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_EthernetPortAllocationSettingData + public class EthernetPortAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetPortAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetPortAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetPortAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetPortAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"EnabledState is an integer enumeration that indicates whether the allocation request is enabled or disabled. When an allocation request is marked as Disabled (3), then the allocation is not processed. The EnabledState for an active configuration is always marked as Enabled (2).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public EnabledStateValues EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return ((EnabledStateValues)(System.Convert.ToInt32(0))); + } + return ((EnabledStateValues)(System.Convert.ToInt32(curObj["EnabledState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of friendly names corresponding to each entry in the RequiredFeatures.")] + public string[] RequiredFeatureHints { + get { + return ((string[])(curObj["RequiredFeatureHints"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of feature identifers representing all the features that are required fo" + + "r a port.")] + public string[] RequiredFeatures { + get { + return ((string[])(curObj["RequiredFeatures"])); + } + set { + curObj["RequiredFeatures"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the network resource pool from which a connection will be" + + " allocated to test replica system when it is created.")] + public string TestReplicaPoolID { + get { + return ((string)(curObj["TestReplicaPoolID"])); + } + set { + curObj["TestReplicaPoolID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the friendly name of the virtual network switch to which " + + "a connection will be allocated for the test replica system when it is created.")] + public string TestReplicaSwitchName { + get { + return ((string)(curObj["TestReplicaSwitchName"])); + } + set { + curObj["TestReplicaSwitchName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private void ResetRequiredFeatures() { + curObj["RequiredFeatures"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private void ResetTestReplicaPoolID() { + curObj["TestReplicaPoolID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTestReplicaSwitchName() { + curObj["TestReplicaSwitchName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetPortAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetPortAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetPortAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetPortAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetPortAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetPortAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetPortAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetPortAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum EnabledStateValues { + + Enabled = 2, + + Disabled = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetPortAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetPortAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetPortAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetPortAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetPortAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs old mode 100644 new mode 100755 similarity index 83% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPort.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs index b3031274ce4..7a14ed92c0b --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPort.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs @@ -1,1960 +1,2102 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_SyntheticEthernetPort - public class SyntheticEthernetPort : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_SyntheticEthernetPort"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SyntheticEthernetPort() { - this.InitializeObject(null, null, null); - } - - public SyntheticEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public SyntheticEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public SyntheticEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SyntheticEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SyntheticEthernetPort(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SyntheticEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SyntheticEthernetPort(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SyntheticEthernetPort(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsActiveMaximumTransmissionUnitNull { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong ActiveMaximumTransmissionUnit { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoSenseNull { - get { - if ((curObj["AutoSense"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoSense { - get { - if ((curObj["AutoSense"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoSense"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Capabilities { - get { - return ((ushort[])(curObj["Capabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] CapabilityDescriptions { - get { - return ((string[])(curObj["CapabilityDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] EnabledCapabilities { - get { - return ((ushort[])(curObj["EnabledCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFullDuplexNull { - get { - if ((curObj["FullDuplex"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool FullDuplex { - get { - if ((curObj["FullDuplex"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["FullDuplex"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLinkTechnologyNull { - get { - if ((curObj["LinkTechnology"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LinkTechnology { - get { - if ((curObj["LinkTechnology"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LinkTechnology"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLocationIndicatorNull { - get { - if ((curObj["LocationIndicator"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LocationIndicator { - get { - if ((curObj["LocationIndicator"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LocationIndicator"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxSpeedNull { - get { - if ((curObj["MaxSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxSpeed { - get { - if ((curObj["MaxSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxSpeed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] NetworkAddresses { - get { - return ((string[])(curObj["NetworkAddresses"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherEnabledCapabilities { - get { - return ((string[])(curObj["OtherEnabledCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLinkTechnology { - get { - return ((string)(curObj["OtherLinkTechnology"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherNetworkPortType { - get { - return ((string)(curObj["OtherNetworkPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherPortType { - get { - return ((string)(curObj["OtherPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PermanentAddress { - get { - return ((string)(curObj["PermanentAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortNumberNull { - get { - if ((curObj["PortNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortNumber { - get { - if ((curObj["PortNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortNumber"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortTypeNull { - get { - if ((curObj["PortType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortType { - get { - if ((curObj["PortType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedSpeedNull { - get { - if ((curObj["RequestedSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong RequestedSpeed { - get { - if ((curObj["RequestedSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["RequestedSpeed"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSpeedNull { - get { - if ((curObj["Speed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Speed { - get { - if ((curObj["Speed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Speed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSupportedMaximumTransmissionUnitNull { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong SupportedMaximumTransmissionUnit { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUsageRestrictionNull { - get { - if ((curObj["UsageRestriction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort UsageRestriction { - get { - if ((curObj["UsageRestriction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["UsageRestriction"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeActiveMaximumTransmissionUnit() { - if ((this.IsActiveMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutoSense() { - if ((this.IsAutoSenseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeFullDuplex() { - if ((this.IsFullDuplexNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLinkTechnology() { - if ((this.IsLinkTechnologyNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLocationIndicator() { - if ((this.IsLocationIndicatorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxSpeed() { - if ((this.IsMaxSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortNumber() { - if ((this.IsPortNumberNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortType() { - if ((this.IsPortTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedSpeed() { - if ((this.IsRequestedSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSpeed() { - if ((this.IsSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSupportedMaximumTransmissionUnit() { - if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUsageRestriction() { - if ((this.IsUsageRestrictionNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_SyntheticEthernetPort"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SyntheticEthernetPortCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SyntheticEthernetPortCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SyntheticEthernetPortCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SyntheticEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SyntheticEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SyntheticEthernetPort"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SyntheticEthernetPortCollection(clsObject.GetInstances(enumOptions)); - } - - public static SyntheticEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SyntheticEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SyntheticEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPort", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SyntheticEthernetPortCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SyntheticEthernetPort CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SyntheticEthernetPort(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class SyntheticEthernetPortCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SyntheticEthernetPortCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SyntheticEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SyntheticEthernetPortEnumerator(privColObj.GetEnumerator()); - } - - public class SyntheticEthernetPortEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SyntheticEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SyntheticEthernetPort(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPort + public class EthernetSwitchPort : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetSwitchPort"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetSwitchPort() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPort(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetSwitchPort(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIOVOffloadUsageNull { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current I/O virtualization (IOV) offload usage on this port. The usage is the" + + "amount of IOV resources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint IOVOffloadUsage { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["IOVOffloadUsage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVMQOffloadUsageNull { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current VMQ offloading usage on this port. The usage is the amount of VMQ res" + + "ources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint VMQOffloadUsage { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["VMQOffloadUsage"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIOVOffloadUsage() { + if ((this.IsIOVOffloadUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVMQOffloadUsage() { + if ((this.IsVMQOffloadUsageNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetSwitchPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetSwitchPort"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetSwitchPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPort CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetSwitchPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetSwitchPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetSwitchPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPort(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpointSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs old mode 100644 new mode 100755 similarity index 69% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpointSettingData.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs index faab8d490a8..5478235677a --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VLANEndpointSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs @@ -1,885 +1,1005 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_VLANEndpointSettingData - public class VLANEndpointSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VLANEndpointSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VLANEndpointSettingData() { - this.InitializeObject(null, null, null); - } - - public VLANEndpointSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VLANEndpointSettingData.ConstructPath(keyInstanceID)), null); - } - - public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VLANEndpointSettingData.ConstructPath(keyInstanceID)), null); - } - - public VLANEndpointSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VLANEndpointSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VLANEndpointSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VLANEndpointSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAccessVLANNull { - get { - if ((curObj["AccessVLAN"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AccessVLAN { - get { - if ((curObj["AccessVLAN"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AccessVLAN"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDefaultVLANNull { - get { - if ((curObj["DefaultVLAN"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DefaultVLAN { - get { - if ((curObj["DefaultVLAN"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DefaultVLAN"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNativeVLANNull { - get { - if ((curObj["NativeVLAN"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort NativeVLAN { - get { - if ((curObj["NativeVLAN"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["NativeVLAN"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryVlanNull { - get { - if ((curObj["PrimaryVlan"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The primary Vlan if the port is in Private Vlan mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryVlan { - get { - if ((curObj["PrimaryVlan"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryVlan"])); - } - set { - curObj["PrimaryVlan"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PruneEligibleVLANList { - get { - return ((ushort[])(curObj["PruneEligibleVLANList"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPVlanModeNull { - get { - if ((curObj["PVlanMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The private VLAN Mode mode supported by this port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public PVlanModeValues PVlanMode { - get { - if ((curObj["PVlanMode"] == null)) { - return ((PVlanModeValues)(System.Convert.ToInt32(3))); - } - return ((PVlanModeValues)(System.Convert.ToInt32(curObj["PVlanMode"]))); - } - set { - if ((PVlanModeValues.NULL_ENUM_VALUE == value)) { - curObj["PVlanMode"] = null; - } - else { - curObj["PVlanMode"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSecondaryVlanNull { - get { - if ((curObj["SecondaryVlan"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The secondary Vlan if the port is in Private Vlan mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort SecondaryVlan { - get { - if ((curObj["SecondaryVlan"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["SecondaryVlan"])); - } - set { - curObj["SecondaryVlan"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] TrunkedVLANList { - get { - return ((ushort[])(curObj["TrunkedVLANList"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAccessVLAN() { - if ((this.IsAccessVLANNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDefaultVLAN() { - if ((this.IsDefaultVLANNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNativeVLAN() { - if ((this.IsNativeVLANNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryVlan() { - if ((this.IsPrimaryVlanNull == false)) { - return true; - } - return false; - } - - private void ResetPrimaryVlan() { - curObj["PrimaryVlan"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializePVlanMode() { - if ((this.IsPVlanModeNull == false)) { - return true; - } - return false; - } - - private void ResetPVlanMode() { - curObj["PVlanMode"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeSecondaryVlan() { - if ((this.IsSecondaryVlanNull == false)) { - return true; - } - return false; - } - - private void ResetSecondaryVlan() { - curObj["SecondaryVlan"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_VLANEndpointSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VLANEndpointSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VLANEndpointSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VLANEndpointSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VLANEndpointSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VLANEndpointSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VLANEndpointSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VLANEndpointSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VLANEndpointSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VLANEndpointSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VLANEndpointSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum PVlanModeValues { - - Unknown0 = 0, - - Incoming = 1, - - Outgoing = 2, - - NULL_ENUM_VALUE = 3, - } - - // Enumerator implementation for enumerating instances of the class. - public class VLANEndpointSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VLANEndpointSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VLANEndpointSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VLANEndpointSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VLANEndpointSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VLANEndpointSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VLANEndpointSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPortVlanSettingData + public class EthernetSwitchPortVlanSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetSwitchPortVlanSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetSwitchPortVlanSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPortVlanSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAccessVlanIdNull { + get { + if ((curObj["AccessVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in access mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AccessVlanId { + get { + if ((curObj["AccessVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AccessVlanId"])); + } + set { + curObj["AccessVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNativeVlanIdNull { + get { + if ((curObj["NativeVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in trunk mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NativeVlanId { + get { + if ((curObj["NativeVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NativeVlanId"])); + } + set { + curObj["NativeVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperationModeNull { + get { + if ((curObj["OperationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan operation modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public OperationModeValues OperationMode { + get { + if ((curObj["OperationMode"] == null)) { + return ((OperationModeValues)(System.Convert.ToInt32(0))); + } + return ((OperationModeValues)(System.Convert.ToInt32(curObj["OperationMode"]))); + } + set { + if ((OperationModeValues.NULL_ENUM_VALUE == value)) { + curObj["OperationMode"] = null; + } + else { + curObj["OperationMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryVlanIdNull { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The primary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryVlanId { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryVlanId"])); + } + set { + curObj["PrimaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The prune vlan ID bitmap in trunk mode.")] + public ushort[] PruneVlanIdArray { + get { + return ((ushort[])(curObj["PruneVlanIdArray"])); + } + set { + curObj["PruneVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPvlanModeNull { + get { + if ((curObj["PvlanMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The private vlan modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public PvlanModeValues PvlanMode { + get { + if ((curObj["PvlanMode"] == null)) { + return ((PvlanModeValues)(System.Convert.ToInt32(0))); + } + return ((PvlanModeValues)(System.Convert.ToInt32(curObj["PvlanMode"]))); + } + set { + if ((PvlanModeValues.NULL_ENUM_VALUE == value)) { + curObj["PvlanMode"] = null; + } + else { + curObj["PvlanMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSecondaryVlanIdNull { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort SecondaryVlanId { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["SecondaryVlanId"])); + } + set { + curObj["SecondaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID bitmap in private mode.")] + public ushort[] SecondaryVlanIdArray { + get { + return ((ushort[])(curObj["SecondaryVlanIdArray"])); + } + set { + curObj["SecondaryVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The trunk vlan ID bitmap in trunk mode.")] + public ushort[] TrunkVlanIdArray { + get { + return ((ushort[])(curObj["TrunkVlanIdArray"])); + } + set { + curObj["TrunkVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAccessVlanId() { + if ((this.IsAccessVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetAccessVlanId() { + curObj["AccessVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeNativeVlanId() { + if ((this.IsNativeVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetNativeVlanId() { + curObj["NativeVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeOperationMode() { + if ((this.IsOperationModeNull == false)) { + return true; + } + return false; + } + + private void ResetOperationMode() { + curObj["OperationMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePrimaryVlanId() { + if ((this.IsPrimaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetPrimaryVlanId() { + curObj["PrimaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPruneVlanIdArray() { + curObj["PruneVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePvlanMode() { + if ((this.IsPvlanModeNull == false)) { + return true; + } + return false; + } + + private void ResetPvlanMode() { + curObj["PvlanMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeSecondaryVlanId() { + if ((this.IsSecondaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetSecondaryVlanId() { + curObj["SecondaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetSecondaryVlanIdArray() { + curObj["SecondaryVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTrunkVlanIdArray() { + curObj["TrunkVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPortVlanSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetSwitchPortVlanSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetSwitchPortVlanSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetSwitchPortVlanSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPortVlanSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortVlanSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPortVlanSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetSwitchPortVlanSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum OperationModeValues { + + Access = 1, + + Trunk = 2, + + Private = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum PvlanModeValues { + + Isolated = 1, + + Community = 2, + + Promiscuous = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetSwitchPortVlanSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortVlanSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortVlanSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortVlanSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortVlanSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ExternalEthernetPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs old mode 100644 new mode 100755 similarity index 90% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ExternalEthernetPort.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs index a479c60b02b..ab233861171 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ExternalEthernetPort.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs @@ -1,1996 +1,2070 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ExternalEthernetPort - public class ExternalEthernetPort : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ExternalEthernetPort"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ExternalEthernetPort() { - this.InitializeObject(null, null, null); - } - - public ExternalEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public ExternalEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ExternalEthernetPort(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ExternalEthernetPort(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ExternalEthernetPort(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsActiveMaximumTransmissionUnitNull { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong ActiveMaximumTransmissionUnit { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoSenseNull { - get { - if ((curObj["AutoSense"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoSense { - get { - if ((curObj["AutoSense"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoSense"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Capabilities { - get { - return ((ushort[])(curObj["Capabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] CapabilityDescriptions { - get { - return ((string[])(curObj["CapabilityDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] EnabledCapabilities { - get { - return ((ushort[])(curObj["EnabledCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFullDuplexNull { - get { - if ((curObj["FullDuplex"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool FullDuplex { - get { - if ((curObj["FullDuplex"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["FullDuplex"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsBoundNull { - get { - if ((curObj["IsBound"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("If this property is true, then this Ethernet port can be connected to the switche" + - "s and thus can provide connectivity to virtual machine. If this property is fals" + - "e, then this Ethernet is not being used by the virtual machine networking archit" + - "ecture.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsBound { - get { - if ((curObj["IsBound"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsBound"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLinkTechnologyNull { - get { - if ((curObj["LinkTechnology"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LinkTechnology { - get { - if ((curObj["LinkTechnology"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LinkTechnology"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLocationIndicatorNull { - get { - if ((curObj["LocationIndicator"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LocationIndicator { - get { - if ((curObj["LocationIndicator"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LocationIndicator"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxSpeedNull { - get { - if ((curObj["MaxSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxSpeed { - get { - if ((curObj["MaxSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxSpeed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] NetworkAddresses { - get { - return ((string[])(curObj["NetworkAddresses"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherEnabledCapabilities { - get { - return ((string[])(curObj["OtherEnabledCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLinkTechnology { - get { - return ((string)(curObj["OtherLinkTechnology"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherNetworkPortType { - get { - return ((string)(curObj["OtherNetworkPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherPortType { - get { - return ((string)(curObj["OtherPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PermanentAddress { - get { - return ((string)(curObj["PermanentAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortNumberNull { - get { - if ((curObj["PortNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortNumber { - get { - if ((curObj["PortNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortNumber"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortTypeNull { - get { - if ((curObj["PortType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortType { - get { - if ((curObj["PortType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedSpeedNull { - get { - if ((curObj["RequestedSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong RequestedSpeed { - get { - if ((curObj["RequestedSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["RequestedSpeed"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSpeedNull { - get { - if ((curObj["Speed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Speed { - get { - if ((curObj["Speed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Speed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSupportedMaximumTransmissionUnitNull { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong SupportedMaximumTransmissionUnit { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUsageRestrictionNull { - get { - if ((curObj["UsageRestriction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort UsageRestriction { - get { - if ((curObj["UsageRestriction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["UsageRestriction"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeActiveMaximumTransmissionUnit() { - if ((this.IsActiveMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutoSense() { - if ((this.IsAutoSenseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeFullDuplex() { - if ((this.IsFullDuplexNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIsBound() { - if ((this.IsIsBoundNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLinkTechnology() { - if ((this.IsLinkTechnologyNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLocationIndicator() { - if ((this.IsLocationIndicatorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxSpeed() { - if ((this.IsMaxSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortNumber() { - if ((this.IsPortNumberNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortType() { - if ((this.IsPortTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedSpeed() { - if ((this.IsRequestedSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSpeed() { - if ((this.IsSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSupportedMaximumTransmissionUnit() { - if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUsageRestriction() { - if ((this.IsUsageRestrictionNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_ExternalEthernetPort"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ExternalEthernetPortCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ExternalEthernetPortCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ExternalEthernetPortCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ExternalEthernetPort"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ExternalEthernetPortCollection(clsObject.GetInstances(enumOptions)); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ExternalEthernetPort", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ExternalEthernetPortCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ExternalEthernetPort CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ExternalEthernetPort(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ExternalEthernetPortCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ExternalEthernetPortCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ExternalEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ExternalEthernetPortEnumerator(privColObj.GetEnumerator()); - } - - public class ExternalEthernetPortEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ExternalEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ExternalEthernetPort(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ExternalEthernetPort + public class ExternalEthernetPort : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ExternalEthernetPort"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ExternalEthernetPort() { + this.InitializeObject(null, null, null); + } + + public ExternalEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ExternalEthernetPort(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ExternalEthernetPort(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsBoundNull { + get { + if ((curObj["IsBound"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("If this property is true, then this Ethernet port can be connected to the switche" + + "s and thus can provide connectivity to virtual machine. If this property is fals" + + "e, then this Ethernet is not being used by the virtual machine networking archit" + + "ecture.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsBound { + get { + if ((curObj["IsBound"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsBound"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIsBound() { + if ((this.IsIsBoundNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ExternalEthernetPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ExternalEthernetPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ExternalEthernetPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ExternalEthernetPort"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ExternalEthernetPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ExternalEthernetPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ExternalEthernetPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ExternalEthernetPort CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ExternalEthernetPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ExternalEthernetPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ExternalEthernetPortCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ExternalEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ExternalEthernetPortEnumerator(privColObj.GetEnumerator()); + } + + public class ExternalEthernetPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ExternalEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ExternalEthernetPort(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ImageManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs old mode 100644 new mode 100755 similarity index 80% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ImageManagementService.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs index 0b8962db2d2..b7ec9ed6320 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ImageManagementService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs @@ -1,1401 +1,1508 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ImageManagementService - public class ImageManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ImageManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ImageManagementService() { - this.InitializeObject(null, null, null); - } - - public ImageManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public ImageManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ImageManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ImageManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ImageManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_ImageManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ImageManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ImageManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ImageManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ImageManagementService"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ImageManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ImageManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ImageManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ImageManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ImageManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint CompactVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CompactVirtualHardDisk"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CompactVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ConvertVirtualHardDisk(string DestinationPath, string SourcePath, ushort Type, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ConvertVirtualHardDisk"); - inParams["DestinationPath"] = ((string)(DestinationPath)); - inParams["SourcePath"] = ((string)(SourcePath)); - inParams["Type"] = ((ushort)(Type)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConvertVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateDifferencingVirtualHardDisk(string ParentPath, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateDifferencingVirtualHardDisk"); - inParams["ParentPath"] = ((string)(ParentPath)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateDifferencingVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateDynamicVirtualHardDisk"); - inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateDynamicVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateFixedVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateFixedVirtualHardDisk"); - inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateFixedVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateVirtualFloppyDisk(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualFloppyDisk"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualFloppyDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ExpandVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ExpandVirtualHardDisk"); - inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExpandVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualHardDiskInfo(string Path, out string Info, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskInfo"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskInfo", inParams, null); - Info = System.Convert.ToString(outParams.Properties["Info"].Value); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Info = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint MergeVirtualHardDisk(string DestinationPath, string SourcePath, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("MergeVirtualHardDisk"); - inParams["DestinationPath"] = ((string)(DestinationPath)); - inParams["SourcePath"] = ((string)(SourcePath)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MergeVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Mount(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("Mount"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Mount", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ReconnectParentVirtualHardDisk(string ChildPath, bool Force, string ParentPath, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ReconnectParentVirtualHardDisk"); - inParams["ChildPath"] = ((string)(ChildPath)); - inParams["Force"] = ((bool)(Force)); - inParams["ParentPath"] = ((string)(ParentPath)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ReconnectParentVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint Unmount(string Path) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("Unmount"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Unmount", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint ValidateVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ValidateVirtualHardDisk"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidateVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ImageManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ImageManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ImageManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ImageManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class ImageManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ImageManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ImageManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ImageManagementService + public class ImageManagementService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ImageManagementService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ImageManagementService() { + this.InitializeObject(null, null, null); + } + + public ImageManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ImageManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ImageManagementService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ImageManagementService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ImageManagementService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ImageManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ImageManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ImageManagementService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ImageManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ImageManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ImageManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ImageManagementService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ImageManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AttachVirtualHardDisk(bool AssignDriveLetter, string Path, bool ReadOnly, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AttachVirtualHardDisk"); + inParams["AssignDriveLetter"] = ((bool)(AssignDriveLetter)); + inParams["Path"] = ((string)(Path)); + inParams["ReadOnly"] = ((bool)(ReadOnly)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AttachVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CompactVirtualHardDisk(ushort Mode, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CompactVirtualHardDisk"); + inParams["Mode"] = ((ushort)(Mode)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CompactVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ConvertVirtualHardDisk(string SourcePath, string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ConvertVirtualHardDisk"); + inParams["SourcePath"] = ((string)(SourcePath)); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConvertVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CreateVirtualFloppyDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualFloppyDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualFloppyDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CreateVirtualHardDisk(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualHardDisk"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualHardDiskSettingData(string Path, out System.Management.ManagementPath Job, out string SettingData) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskSettingData"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + SettingData = System.Convert.ToString(outParams.Properties["SettingData"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + SettingData = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualHardDiskState(string Path, out System.Management.ManagementPath Job, out string State) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskState"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskState", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + State = System.Convert.ToString(outParams.Properties["State"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + State = null; + return System.Convert.ToUInt32(0); + } + } + + public uint MergeVirtualHardDisk(string DestinationPath, string SourcePath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("MergeVirtualHardDisk"); + inParams["DestinationPath"] = ((string)(DestinationPath)); + inParams["SourcePath"] = ((string)(SourcePath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MergeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ResizeVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ResizeVirtualHardDisk"); + inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ResizeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetParentVirtualHardDisk(string ChildPath, bool IgnoreIDMismatch, string LeafPath, string ParentPath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetParentVirtualHardDisk"); + inParams["ChildPath"] = ((string)(ChildPath)); + inParams["IgnoreIDMismatch"] = ((bool)(IgnoreIDMismatch)); + inParams["LeafPath"] = ((string)(LeafPath)); + inParams["ParentPath"] = ((string)(ParentPath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetParentVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetVirtualHardDiskSettingData(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetVirtualHardDiskSettingData"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint ValidateVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ValidateVirtualHardDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ImageManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ImageManagementServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ImageManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ImageManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class ImageManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ImageManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ImageManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs index 187699dba20..4ca4d50663a 100755 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs @@ -1311,8 +1311,9 @@ inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchLANEndpoint.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs old mode 100644 new mode 100755 similarity index 81% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchLANEndpoint.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs index 75d20ca0c64..eb660b4cd44 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SwitchLANEndpoint.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs @@ -1,1342 +1,1405 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_SwitchLANEndpoint - public class SwitchLANEndpoint : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_SwitchLANEndpoint"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SwitchLANEndpoint() { - this.InitializeObject(null, null, null); - } - - public SwitchLANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(SwitchLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public SwitchLANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SwitchLANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public SwitchLANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SwitchLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SwitchLANEndpoint(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SwitchLANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SwitchLANEndpoint(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SwitchLANEndpoint(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] AliasAddresses { - get { - return ((string[])(curObj["AliasAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBroadcastResetSupportedNull { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BroadcastResetSupported { - get { - if ((curObj["BroadcastResetSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BroadcastResetSupported"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConnectedNull { - get { - if ((curObj["Connected"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Connected { - get { - if ((curObj["Connected"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Connected"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] GroupAddresses { - get { - return ((string[])(curObj["GroupAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string LANID { - get { - return ((string)(curObj["LANID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLANTypeNull { - get { - if ((curObj["LANType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LANType { - get { - if ((curObj["LANType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string MACAddress { - get { - return ((string)(curObj["MACAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLANType { - get { - return ((string)(curObj["OtherLANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTypeDescription { - get { - return ((string)(curObj["OtherTypeDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolIFTypeNull { - get { - if ((curObj["ProtocolIFType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolIFType { - get { - if ((curObj["ProtocolIFType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolIFType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolTypeNull { - get { - if ((curObj["ProtocolType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolType { - get { - if ((curObj["ProtocolType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeBroadcastResetSupported() { - if ((this.IsBroadcastResetSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConnected() { - if ((this.IsConnectedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLANType() { - if ((this.IsLANTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolIFType() { - if ((this.IsProtocolIFTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolType() { - if ((this.IsProtocolTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_SwitchLANEndpoint"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SwitchLANEndpointCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SwitchLANEndpointCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SwitchLANEndpointCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SwitchLANEndpointCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SwitchLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SwitchLANEndpoint"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SwitchLANEndpointCollection(clsObject.GetInstances(enumOptions)); - } - - public static SwitchLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SwitchLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SwitchLANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SwitchLANEndpoint", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SwitchLANEndpointCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SwitchLANEndpoint CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SwitchLANEndpoint(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint BroadcastReset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("BroadcastReset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class SwitchLANEndpointCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SwitchLANEndpointCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SwitchLANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SwitchLANEndpointEnumerator(privColObj.GetEnumerator()); - } - - public class SwitchLANEndpointEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SwitchLANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SwitchLANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_LANEndpoint + public class LANEndpoint : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_LANEndpoint"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public LANEndpoint() { + this.InitializeObject(null, null, null); + } + + public LANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public LANEndpoint(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public LANEndpoint(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public LANEndpoint(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] AliasAddresses { + get { + return ((string[])(curObj["AliasAddresses"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConnectedNull { + get { + if ((curObj["Connected"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Connected { + get { + if ((curObj["Connected"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Connected"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] GroupAddresses { + get { + return ((string[])(curObj["GroupAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string LANID { + get { + return ((string)(curObj["LANID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLANTypeNull { + get { + if ((curObj["LANType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LANType { + get { + if ((curObj["LANType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string MACAddress { + get { + return ((string)(curObj["MACAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLANType { + get { + return ((string)(curObj["OtherLANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherTypeDescription { + get { + return ((string)(curObj["OtherTypeDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProtocolIFTypeNull { + get { + if ((curObj["ProtocolIFType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolIFType { + get { + if ((curObj["ProtocolIFType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolIFType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProtocolTypeNull { + get { + if ((curObj["ProtocolType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolType { + get { + if ((curObj["ProtocolType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConnected() { + if ((this.IsConnectedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLANType() { + if ((this.IsLANTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProtocolIFType() { + if ((this.IsProtocolIFTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProtocolType() { + if ((this.IsProtocolTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_LANEndpoint"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static LANEndpointCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static LANEndpointCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static LANEndpointCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static LANEndpointCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_LANEndpoint"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new LANEndpointCollection(clsObject.GetInstances(enumOptions)); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_LANEndpoint", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new LANEndpointCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static LANEndpoint CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new LANEndpoint(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class LANEndpointCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public LANEndpointCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new LANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new LANEndpointEnumerator(privColObj.GetEnumerator()); + } + + public class LANEndpointEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public LANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new LANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_MemorySettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs old mode 100644 new mode 100755 similarity index 91% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_MemorySettingData.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs index 3e5d903d5b1..378fc8ad36a --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_MemorySettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs @@ -1,1083 +1,1146 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_MemorySettingData - public class MemorySettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_MemorySettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public MemorySettingData() { - this.InitializeObject(null, null, null); - } - - public MemorySettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); - } - - public MemorySettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public MemorySettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public MemorySettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public MemorySettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Address or other identifying information to uniquely name the logical device. Thi" + - "s property is always set to \"Microsoft:GUID\".")] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The format of the corresponding DeviceID property, or the supported device IDs wh" + - "en used to represent a capability. This property is not used.")] - public string DeviceIDFormat { - get { - return ((string)(curObj["DeviceIDFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDynamicMemoryEnabledNull { - get { - if ((curObj["DynamicMemoryEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Reserved for future use.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool DynamicMemoryEnabled { - get { - if ((curObj["DynamicMemoryEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["DynamicMemoryEnabled"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsVirtualizedNull { - get { - if ((curObj["IsVirtualized"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is always set to True.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsVirtualized { - get { - if ((curObj["IsVirtualized"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsVirtualized"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTargetMemoryBufferNull { - get { - if ((curObj["TargetMemoryBuffer"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint TargetMemoryBuffer { - get { - if ((curObj["TargetMemoryBuffer"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["TargetMemoryBuffer"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDynamicMemoryEnabled() { - if ((this.IsDynamicMemoryEnabledNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIsVirtualized() { - if ((this.IsIsVirtualizedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTargetMemoryBuffer() { - if ((this.IsTargetMemoryBufferNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_MemorySettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static MemorySettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static MemorySettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static MemorySettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_MemorySettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new MemorySettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_MemorySettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new MemorySettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static MemorySettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new MemorySettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class MemorySettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public MemorySettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new MemorySettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new MemorySettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class MemorySettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public MemorySettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new MemorySettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_MemorySettingData + public class MemorySettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_MemorySettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public MemorySettingData() { + this.InitializeObject(null, null, null); + } + + public MemorySettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public MemorySettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public MemorySettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public MemorySettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDynamicMemoryEnabledNull { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if dynamic memory is enabled.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DynamicMemoryEnabled { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DynamicMemoryEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsVirtualizedNull { + get { + if ((curObj["IsVirtualized"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is always set to True.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsVirtualized { + get { + if ((curObj["IsVirtualized"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsVirtualized"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxMemoryBlocksPerNumaNodeNull { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum amount of memory that can be observed within the VM as belonging to a" + + " single NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxMemoryBlocksPerNumaNode { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxMemoryBlocksPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTargetMemoryBufferNull { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint TargetMemoryBuffer { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["TargetMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDynamicMemoryEnabled() { + if ((this.IsDynamicMemoryEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIsVirtualized() { + if ((this.IsIsVirtualizedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxMemoryBlocksPerNumaNode() { + if ((this.IsMaxMemoryBlocksPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTargetMemoryBuffer() { + if ((this.IsTargetMemoryBufferNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_MemorySettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static MemorySettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static MemorySettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static MemorySettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_MemorySettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new MemorySettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_MemorySettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new MemorySettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static MemorySettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new MemorySettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class MemorySettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public MemorySettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new MemorySettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new MemorySettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class MemorySettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public MemorySettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new MemorySettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ProcessorSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs old mode 100644 new mode 100755 similarity index 88% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ProcessorSettingData.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs index 1b229318cee..e087cd10ef3 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ProcessorSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs @@ -1,1190 +1,1117 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_ProcessorSettingData - public class ProcessorSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_ProcessorSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ProcessorSettingData() { - this.InitializeObject(null, null, null); - } - - public ProcessorSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); - } - - public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ProcessorSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ProcessorSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ProcessorSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Address or other identifying information to uniquely name the logical device.\n Th" + - "is property is always set to \"Microsoft:GUID\".")] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The format of the corresponding device ID, or the supported device IDs when used " + - "to represent a capability.\nThis property is not used.")] - public string DeviceIDFormat { - get { - return ((string)(curObj["DeviceIDFormat"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsVirtualizedNull { - get { - if ((curObj["IsVirtualized"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is set to True.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsVirtualized { - get { - if ((curObj["IsVirtualized"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsVirtualized"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitCPUIDNull { - get { - if ((curObj["LimitCPUID"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether the virtual machine should lower the CPU identifier. Some older operating systems may require you to limit processor functionality in this way in order to run. -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool LimitCPUID { - get { - if ((curObj["LimitCPUID"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["LimitCPUID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitProcessorFeaturesNull { - get { - if ((curObj["LimitProcessorFeatures"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether the VM should limit the CPU features exposed to the operating system. Limiting the processor features enables the VM to be migrated to different host computer systems with different processors. Migrating VMs between computers with processors from different vendors is not supported. -Windows Server 2008: The LimitProcessorFeatures property is not supported until Windows Server 2008 R2.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool LimitProcessorFeatures { - get { - if ((curObj["LimitProcessorFeatures"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["LimitProcessorFeatures"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProcessorsPerSocketNull { - get { - if ((curObj["ProcessorsPerSocket"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The number of processors, or cores, configured for each socket in the virtual sys" + - "tem.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProcessorsPerSocket { - get { - if ((curObj["ProcessorsPerSocket"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProcessorsPerSocket"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSocketCountNull { - get { - if ((curObj["SocketCount"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The number of processor sockets in the virtual machine. The total number of proce" + - "ssors is the value of this property times the value of the ProcessorsPerSocket p" + - "roperty.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort SocketCount { - get { - if ((curObj["SocketCount"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["SocketCount"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsThreadsEnabledNull { - get { - if ((curObj["ThreadsEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether hardware threads should be visible to the virtual system. If th" + - "e physical processor does not support hardware threads, this value has no effect" + - " in the virtual system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ThreadsEnabled { - get { - if ((curObj["ThreadsEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ThreadsEnabled"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIsVirtualized() { - if ((this.IsIsVirtualizedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimitCPUID() { - if ((this.IsLimitCPUIDNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimitProcessorFeatures() { - if ((this.IsLimitProcessorFeaturesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProcessorsPerSocket() { - if ((this.IsProcessorsPerSocketNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSocketCount() { - if ((this.IsSocketCountNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeThreadsEnabled() { - if ((this.IsThreadsEnabledNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_ProcessorSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ProcessorSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ProcessorSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ProcessorSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ProcessorSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ProcessorSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ProcessorSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ProcessorSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ProcessorSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ProcessorSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class ProcessorSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ProcessorSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ProcessorSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ProcessorSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class ProcessorSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ProcessorSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ProcessorSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_ProcessorSettingData + public class ProcessorSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_ProcessorSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ProcessorSettingData() { + this.InitializeObject(null, null, null); + } + + public ProcessorSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ProcessorSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ProcessorSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ProcessorSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitCPUIDNull { + get { + if ((curObj["LimitCPUID"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the virtual machine should lower the CPU identifier. Some older" + + " operating systems may require you to limit processor functionality in this way " + + "in order to run.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitCPUID { + get { + if ((curObj["LimitCPUID"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitCPUID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitProcessorFeaturesNull { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether the VM should limit the CPU features exposed to the operating system. Limiting the processor features enables the VM to be migrated to different host computer systems with different processors. Migrating VMs between computers with processors from different vendors is not supported.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitProcessorFeatures { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitProcessorFeatures"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxNumaNodesPerSocketNull { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of NUMA nodes that can be observed within the VM as belonging " + + "to a single processor socket.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxNumaNodesPerSocket { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxNumaNodesPerSocket"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxProcessorsPerNumaNodeNull { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of virtual processors that can be observed within the VM as be" + + "longing to a single virtual NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxProcessorsPerNumaNode { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxProcessorsPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitCPUID() { + if ((this.IsLimitCPUIDNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitProcessorFeatures() { + if ((this.IsLimitProcessorFeaturesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxNumaNodesPerSocket() { + if ((this.IsMaxNumaNodesPerSocketNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxProcessorsPerNumaNode() { + if ((this.IsMaxProcessorsPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ProcessorSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ProcessorSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ProcessorSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ProcessorSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ProcessorSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ProcessorSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ProcessorSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ProcessorSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ProcessorSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ProcessorSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ProcessorSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ProcessorSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ProcessorSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ProcessorSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ProcessorSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ProcessorSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ResourceAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs old mode 100644 new mode 100755 similarity index 95% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ResourceAllocationSettingData.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs index 28e76968962..343e0393dec --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_ResourceAllocationSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs @@ -1,976 +1,993 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_ResourceAllocationSettingData - public class ResourceAllocationSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_ResourceAllocationSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ResourceAllocationSettingData() { - this.InitializeObject(null, null, null); - } - - public ResourceAllocationSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ResourceAllocationSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ResourceAllocationSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ResourceAllocationSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"". -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class. -Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")] - public string[] VirtualSystemIdentifiers { - get { - return ((string[])(curObj["VirtualSystemIdentifiers"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_ResourceAllocationSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ResourceAllocationSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ResourceAllocationSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ResourceAllocationSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ResourceAllocationSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class ResourceAllocationSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ResourceAllocationSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ResourceAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_ResourceAllocationSettingData + public class ResourceAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_ResourceAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ResourceAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public ResourceAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ResourceAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ResourceAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"". +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class. +Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ResourceAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ResourceAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ResourceAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ResourceAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ResourceAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ResourceAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ResourceAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ResourceAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs new file mode 100755 index 00000000000..0d0f5506db6 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs @@ -0,0 +1,1197 @@ +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_StorageAllocationSettingData + public class StorageAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_StorageAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public StorageAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public StorageAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public StorageAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public StorageAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAccessNull { + get { + if ((curObj["Access"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Access { + get { + if ((curObj["Access"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Access"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string HostExtentName { + get { + return ((string)(curObj["HostExtentName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameFormatNull { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameFormat { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameNamespaceNull { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameNamespace { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameNamespace"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentStartingAddressNull { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostExtentStartingAddress { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostExtentStartingAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostResourceBlockSizeNull { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostResourceBlockSize { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostResourceBlockSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameFormat { + get { + return ((string)(curObj["OtherHostExtentNameFormat"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameNamespace { + get { + return ((string)(curObj["OtherHostExtentNameNamespace"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualResourceBlockSizeNull { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualResourceBlockSize { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualResourceBlockSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAccess() { + if ((this.IsAccessNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameFormat() { + if ((this.IsHostExtentNameFormatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameNamespace() { + if ((this.IsHostExtentNameNamespaceNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentStartingAddress() { + if ((this.IsHostExtentStartingAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostResourceBlockSize() { + if ((this.IsHostResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualResourceBlockSize() { + if ((this.IsVirtualResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_StorageAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static StorageAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_StorageAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new StorageAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_StorageAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new StorageAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static StorageAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new StorageAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class StorageAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public StorageAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new StorageAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new StorageAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class StorageAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public StorageAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new StorageAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SummaryInformation.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs old mode 100644 new mode 100755 similarity index 77% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SummaryInformation.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs index 8c0df73ea18..1a3a21ab48d --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SummaryInformation.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs @@ -1,1184 +1,1520 @@ -namespace CloudStack.Plugin.AgentShell.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // - // - // - // - // If the embedded property is strongly typed then, to strongly type the property to the type of - // the embedded object, you have to do the following things. - // 1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer. - // 2. Include the namespace of the generated class. - // 3. Change the property get/set functions so as return the instance of the Managed class. - // Below is a sample code. - // - // VB Code - // - // - // - // Property name - // Managed class name of Embedded Property - // - // - // - // - // - // - // C# Code - // - // - // - // Managed class name of Embedded property - // Property name - // - // - // - // - // - // - // - // - // - // - // An Early Bound class generated for the WMI class.Msvm_SummaryInformation - public class SummaryInformation : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_SummaryInformation"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SummaryInformation() { - this.InitializeObject(null, null, null); - } - - public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SummaryInformation(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SummaryInformation(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SummaryInformation(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The identifier of the physical graphics processing unit (GPU) allocated to this v" + - "irtual machine (VM). This property only applies to VMs that use RemoteFX.")] - public string AllocatedGPU { - get { - return ((string)(curObj["AllocatedGPU"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of Msvm_ConcreteJob instances representing any asynchronous operations r" + - "elated to the virtual system which are currently executing. This property is not" + - " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + - "apshot.")] - public System.Management.ManagementBaseObject[] AsynchronousTasks { - get { - return ((System.Management.ManagementBaseObject[])(curObj["AsynchronousTasks"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailableMemoryBufferNull { - get { - if ((curObj["AvailableMemoryBuffer"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The available memory buffer percentage in the virtual system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public int AvailableMemoryBuffer { - get { - if ((curObj["AvailableMemoryBuffer"] == null)) { - return System.Convert.ToInt32(0); - } - return ((int)(curObj["AvailableMemoryBuffer"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCreationTimeNull { - get { - if ((curObj["CreationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time at which the virtual system or snapshot was created.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime CreationTime { - get { - if ((curObj["CreationTime"] != null)) { - return ToDateTime(((string)(curObj["CreationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The friendly name for the virtual system or snapshot.")] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current state of the virtual system or snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The name of the guest operating system, if available. If this information is not " + - "available, the value of this property is NULL. This property is not valid for in" + - "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] - public string GuestOperatingSystem { - get { - return ((string)(curObj["GuestOperatingSystem"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current health state for the virtual system. This property is not valid for i" + - "nstances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHeartbeatNull { - get { - if ((curObj["Heartbeat"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The current heartbeat status for the virtual system. This property may be one of the following values: ""OK""; ""Error""; ""No Contact""; or ""Lost Communication"". For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Heartbeat { - get { - if ((curObj["Heartbeat"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Heartbeat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMemoryAvailableNull { - get { - if ((curObj["MemoryAvailable"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The memory available percentage in the virtual system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public int MemoryAvailable { - get { - if ((curObj["MemoryAvailable"] == null)) { - return System.Convert.ToInt32(0); - } - return ((int)(curObj["MemoryAvailable"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMemoryUsageNull { - get { - if ((curObj["MemoryUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current memory usage of the virtual system. This property is not valid for in" + - "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MemoryUsage { - get { - if ((curObj["MemoryUsage"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MemoryUsage"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The unique name for the virtual system or snapshot.")] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The notes associated with the virtual system or snapshot.")] - public string Notes { - get { - return ((string)(curObj["Notes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumberOfProcessorsNull { - get { - if ((curObj["NumberOfProcessors"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The total number of virtual processors allocated to the virtual system or snapsho" + - "t.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort NumberOfProcessors { - get { - if ((curObj["NumberOfProcessors"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["NumberOfProcessors"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current status of the element.")] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProcessorLoadNull { - get { - if ((curObj["ProcessorLoad"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current processor usage of the virtual system. This property is not valid for" + - " instances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProcessorLoad { - get { - if ((curObj["ProcessorLoad"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProcessorLoad"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of the previous 100 samples of the processor usage for the virtual syste" + - "m. This property is not valid for instances of Msvm_SummaryInformation represent" + - "ing a virtual system snapshot.")] - public ushort[] ProcessorLoadHistory { - get { - return ((ushort[])(curObj["ProcessorLoadHistory"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of Msvm_VirtualSystemSettingData instances representing the snapshots fo" + - "r the virtual system. This property is not valid for instances of Msvm_SummaryIn" + - "formation representing a virtual system snapshot.")] - public System.Management.ManagementBaseObject[] Snapshots { - get { - return ((System.Management.ManagementBaseObject[])(curObj["Snapshots"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Strings that describe the various OperationalStatus array values.")] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array containing a small, thumbnail-sized image of the desktop for the virtual" + - " system or snapshot in RGB565 format.")] - public byte[] ThumbnailImage { - get { - return ((byte[])(curObj["ThumbnailImage"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUpTimeNull { - get { - if ((curObj["UpTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The amount of time since the virtual system was last booted. This property is not" + - " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + - "apshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong UpTime { - get { - if ((curObj["UpTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["UpTime"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAvailableMemoryBuffer() { - if ((this.IsAvailableMemoryBufferNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeCreationTime() { - if ((this.IsCreationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHeartbeat() { - if ((this.IsHeartbeatNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMemoryAvailable() { - if ((this.IsMemoryAvailableNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMemoryUsage() { - if ((this.IsMemoryUsageNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumberOfProcessors() { - if ((this.IsNumberOfProcessorsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProcessorLoad() { - if ((this.IsProcessorLoadNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUpTime() { - if ((this.IsUpTimeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath() { - string strPath = "ROOT\\virtualization:Msvm_SummaryInformation"; - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SummaryInformationCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SummaryInformationCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SummaryInformationCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SummaryInformation"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SummaryInformationCollection(clsObject.GetInstances(enumOptions)); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SummaryInformation", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SummaryInformationCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SummaryInformation CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SummaryInformation(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class SummaryInformationCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SummaryInformationCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SummaryInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SummaryInformationEnumerator(privColObj.GetEnumerator()); - } - - public class SummaryInformationEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SummaryInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SummaryInformation(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // + // + // + // + // If the embedded property is strongly typed then, to strongly type the property to the type of + // the embedded object, you have to do the following things. + // 1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer. + // 2. Include the namespace of the generated class. + // 3. Change the property get/set functions so as return the instance of the Managed class. + // Below is a sample code. + // + // VB Code + // + // + // + // Property name + // Managed class name of Embedded Property + // + // + // + // + // + // + // C# Code + // + // + // + // Managed class name of Embedded property + // Property name + // + // + // + // + // + // + // + // + // + // + // An Early Bound class generated for the WMI class.Msvm_SummaryInformation + public class SummaryInformation : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_SummaryInformation"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public SummaryInformation() { + this.InitializeObject(null, null, null); + } + + public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SummaryInformation(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SummaryInformation(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public SummaryInformation(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The identifier of the physical graphics processing unit (GPU) allocated to this v" + + "irtual machine (VM). This property only applies to VMs that use RemoteFX.")] + public string AllocatedGPU { + get { + return ((string)(curObj["AllocatedGPU"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsApplicationHealthNull { + get { + if ((curObj["ApplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current application health status for the virtual system. This property may be one of the following values: ""OK""; ""Application Critical""; ""Disabled"".For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ApplicationHealthValues ApplicationHealth { + get { + if ((curObj["ApplicationHealth"] == null)) { + return ((ApplicationHealthValues)(System.Convert.ToInt32(0))); + } + return ((ApplicationHealthValues)(System.Convert.ToInt32(curObj["ApplicationHealth"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_ConcreteJob instances representing any asynchronous operations r" + + "elated to the virtual system which are currently executing. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + public System.Management.ManagementBaseObject[] AsynchronousTasks { + get { + return ((System.Management.ManagementBaseObject[])(curObj["AsynchronousTasks"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailableMemoryBufferNull { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The available memory buffer percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int AvailableMemoryBuffer { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["AvailableMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCreationTimeNull { + get { + if ((curObj["CreationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the virtual system or snapshot was created.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime CreationTime { + get { + if ((curObj["CreationTime"] != null)) { + return ToDateTime(((string)(curObj["CreationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The friendly name for the virtual system or snapshot.")] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current state of the virtual system or snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The name of the guest operating system, if available. If this information is not " + + "available, the value of this property is NULL. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + public string GuestOperatingSystem { + get { + return ((string)(curObj["GuestOperatingSystem"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current health state for the virtual system. This property is not valid for i" + + "nstances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHeartbeatNull { + get { + if ((curObj["Heartbeat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current heartbeat status for the virtual system. This property may be one of the following values: ""OK""; ""Error""; ""No Contact""; or ""Lost Communication"". For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Heartbeat { + get { + if ((curObj["Heartbeat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Heartbeat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIntegrationServicesVersionStateNull { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Whether or not the integration services installed in the virtual machine are up t" + + "o date")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public IntegrationServicesVersionStateValues IntegrationServicesVersionState { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(3))); + } + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(curObj["IntegrationServicesVersionState"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryAvailableNull { + get { + if ((curObj["MemoryAvailable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The memory available percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int MemoryAvailable { + get { + if ((curObj["MemoryAvailable"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["MemoryAvailable"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemorySpansPhysicalNumaNodesNull { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether or not the memory of the one or more of the virtual non-uniform" + + " memory access (NUMA) nodes of the virtual machine spans multiple physical NUMA " + + "nodes of the hosting computer system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool MemorySpansPhysicalNumaNodes { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["MemorySpansPhysicalNumaNodes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryUsageNull { + get { + if ((curObj["MemoryUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current memory usage of the virtual system. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MemoryUsage { + get { + if ((curObj["MemoryUsage"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MemoryUsage"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The unique name for the virtual system or snapshot.")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The notes associated with the virtual system or snapshot.")] + public string Notes { + get { + return ((string)(curObj["Notes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfProcessorsNull { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total number of virtual processors allocated to the virtual system or snapsho" + + "t.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NumberOfProcessors { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NumberOfProcessors"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current status of the element.")] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A string that describes the enabled or disabled state of the element when the Ena" + + "bledState property is set to 1 (\"Other\"). This property must be set to null when" + + " EnabledState is any value other than 1.")] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorLoadNull { + get { + if ((curObj["ProcessorLoad"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current processor usage of the virtual system. This property is not valid for" + + " instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProcessorLoad { + get { + if ((curObj["ProcessorLoad"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProcessorLoad"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of the previous 100 samples of the processor usage for the virtual syste" + + "m. This property is not valid for instances of Msvm_SummaryInformation represent" + + "ing a virtual system snapshot.")] + public ushort[] ProcessorLoadHistory { + get { + return ((ushort[])(curObj["ProcessorLoadHistory"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationHealthNull { + get { + if ((curObj["ReplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication health for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationHealthValues ReplicationHealth { + get { + if ((curObj["ReplicationHealth"] == null)) { + return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationModeNull { + get { + if ((curObj["ReplicationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Identifies replication type for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationModeValues ReplicationMode { + get { + if ((curObj["ReplicationMode"] == null)) { + return ((ReplicationModeValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationStateNull { + get { + if ((curObj["ReplicationState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication state for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationStateValues ReplicationState { + get { + if ((curObj["ReplicationState"] == null)) { + return ((ReplicationStateValues)(System.Convert.ToInt32(12))); + } + return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_VirtualSystemSettingData instances representing the snapshots fo" + + "r the virtual system. This property is not valid for instances of Msvm_SummaryIn" + + "formation representing a virtual system snapshot.")] + public System.Management.ManagementBaseObject[] Snapshots { + get { + return ((System.Management.ManagementBaseObject[])(curObj["Snapshots"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Strings that describe the various OperationalStatus array values.")] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indecates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reference to the CIM_ComputerSystem instance representing the test replica virtua" + + "l system for the virtual machine. This property is not valid for instances of Ms" + + "vm_SummaryInformation representing a virtual system snapshot.")] + public System.Management.ManagementPath TestReplicaSystem { + get { + if ((curObj["TestReplicaSystem"] != null)) { + return new System.Management.ManagementPath(curObj["TestReplicaSystem"].ToString()); + } + return null; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array containing a small, thumbnail-sized image of the desktop for the virtual" + + " system or snapshot in RGB565 format.")] + public byte[] ThumbnailImage { + get { + return ((byte[])(curObj["ThumbnailImage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUpTimeNull { + get { + if ((curObj["UpTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The amount of time since the virtual system was last booted. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong UpTime { + get { + if ((curObj["UpTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["UpTime"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeApplicationHealth() { + if ((this.IsApplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailableMemoryBuffer() { + if ((this.IsAvailableMemoryBufferNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeCreationTime() { + if ((this.IsCreationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHeartbeat() { + if ((this.IsHeartbeatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIntegrationServicesVersionState() { + if ((this.IsIntegrationServicesVersionStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryAvailable() { + if ((this.IsMemoryAvailableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemorySpansPhysicalNumaNodes() { + if ((this.IsMemorySpansPhysicalNumaNodesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryUsage() { + if ((this.IsMemoryUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfProcessors() { + if ((this.IsNumberOfProcessorsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorLoad() { + if ((this.IsProcessorLoadNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationHealth() { + if ((this.IsReplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationMode() { + if ((this.IsReplicationModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationState() { + if ((this.IsReplicationStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUpTime() { + if ((this.IsUpTimeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath() { + string strPath = "ROOT\\virtualization\\v2:Msvm_SummaryInformation"; + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static SummaryInformationCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SummaryInformationCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SummaryInformationCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_SummaryInformation"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new SummaryInformationCollection(clsObject.GetInstances(enumOptions)); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SummaryInformation", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SummaryInformationCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SummaryInformation CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new SummaryInformation(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum ApplicationHealthValues { + + OK = 2, + + Application_Critical = 32782, + + Disabled = 32896, + + NULL_ENUM_VALUE = 0, + } + + public enum IntegrationServicesVersionStateValues { + + Unknown0 = 0, + + UpToDate = 1, + + Mismatch = 2, + + NULL_ENUM_VALUE = 3, + } + + public enum ReplicationHealthValues { + + Not_applicable = 0, + + Ok = 1, + + Warning = 2, + + Critical = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationModeValues { + + None = 0, + + Primary = 1, + + Recovery = 2, + + Test_Replica = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationStateValues { + + Disabled = 0, + + Ready_for_replication = 1, + + Waiting_to_complete_initial_replication = 2, + + Replicating = 3, + + Synced_replication_complete = 4, + + Recovered = 5, + + Committed = 6, + + Suspended = 7, + + Critical = 8, + + Waiting_to_start_resynchronization = 9, + + Resynchronizing = 10, + + Resynchronization_suspended = 11, + + NULL_ENUM_VALUE = 12, + } + + // Enumerator implementation for enumerating instances of the class. + public class SummaryInformationCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SummaryInformationCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new SummaryInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SummaryInformationEnumerator(privColObj.GetEnumerator()); + } + + public class SummaryInformationEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SummaryInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SummaryInformation(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPortSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs old mode 100644 new mode 100755 similarity index 92% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPortSettingData.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs index 6edc7bddbb4..b208067e2c8 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_SyntheticEthernetPortSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs @@ -1,1010 +1,1066 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_SyntheticEthernetPortSettingData - public class SyntheticEthernetPortSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_SyntheticEthernetPortSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SyntheticEthernetPortSettingData() { - this.InitializeObject(null, null, null); - } - - public SyntheticEthernetPortSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStaticMacAddressNull { - get { - if ((curObj["StaticMacAddress"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates a static MAC address.\nThis is a read-only property, but it can be chang" + - "ed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManage" + - "mentService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool StaticMacAddress { - get { - if ((curObj["StaticMacAddress"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["StaticMacAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_SyntheticEthernetPortSettingData + public class SyntheticEthernetPortSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_SyntheticEthernetPortSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public SyntheticEthernetPortSettingData() { + this.InitializeObject(null, null, null); + } + + public SyntheticEthernetPortSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStaticMacAddressNull { + get { + if ((curObj["StaticMacAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates a static MAC address.\nThis is a read-only property, but it can be chang" + + "ed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManage" + + "mentService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool StaticMacAddress { + get { + if ((curObj["StaticMacAddress"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["StaticMacAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. The indexes and values per index are defined on a per resource basis (that is, for each enumerated ResourceType value). This property is set to ""GUID"". -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the sd class.")] - public string[] VirtualSystemIdentifiers { - get { - return ((string[])(curObj["VirtualSystemIdentifiers"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStaticMacAddress() { - if ((this.IsStaticMacAddressNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization:Msvm_SyntheticEthernetPortSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SyntheticEthernetPortSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SyntheticEthernetPortSettingData"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SyntheticEthernetPortSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class SyntheticEthernetPortSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SyntheticEthernetPortSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SyntheticEthernetPortSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class SyntheticEthernetPortSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SyntheticEthernetPortSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the sd class.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStaticMacAddress() { + if ((this.IsStaticMacAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_SyntheticEthernetPortSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static SyntheticEthernetPortSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_SyntheticEthernetPortSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SyntheticEthernetPortSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class SyntheticEthernetPortSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SyntheticEthernetPortSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SyntheticEthernetPortSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class SyntheticEthernetPortSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SyntheticEthernetPortSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitch.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs old mode 100644 new mode 100755 similarity index 80% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitch.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs index 4d5644553fd..3fb5e3c087a --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_VirtualSwitch.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs @@ -1,1305 +1,1369 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSwitch - public class VirtualSwitch : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualSwitch"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSwitch() { - this.InitializeObject(null, null, null); - } - - public VirtualSwitch(string keyCreationClassName, string keyName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSwitch.ConstructPath(keyCreationClassName, keyName)), null); - } - - public VirtualSwitch(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSwitch.ConstructPath(keyCreationClassName, keyName)), null); - } - - public VirtualSwitch(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSwitch(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSwitch(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSwitch(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Dedicated { - get { - return ((ushort[])(curObj["Dedicated"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxChimneyOffloadsNull { - get { - if ((curObj["MaxChimneyOffloads"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of Chimney offloads allowed for a port on this switch.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxChimneyOffloads { - get { - if ((curObj["MaxChimneyOffloads"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxChimneyOffloads"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxVMQOffloadsNull { - get { - if ((curObj["MaxVMQOffloads"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of VM queue (VMQ) offloads allowed for a port on this switch.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxVMQOffloads { - get { - if ((curObj["MaxVMQOffloads"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxVMQOffloads"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumLearnableAddressesNull { - get { - if ((curObj["NumLearnableAddresses"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The number of learnable addresses for this switch.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint NumLearnableAddresses { - get { - if ((curObj["NumLearnableAddresses"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["NumLearnableAddresses"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherDedicatedDescriptions { - get { - return ((string[])(curObj["OtherDedicatedDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResetCapabilityNull { - get { - if ((curObj["ResetCapability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResetCapability { - get { - if ((curObj["ResetCapability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResetCapability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Roles { - get { - return ((string[])(curObj["Roles"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The authorization manager scope for the switch service.")] - public string ScopeOfResidence { - get { - return ((string)(curObj["ScopeOfResidence"])); - } - set { - curObj["ScopeOfResidence"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxChimneyOffloads() { - if ((this.IsMaxChimneyOffloadsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxVMQOffloads() { - if ((this.IsMaxVMQOffloadsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumLearnableAddresses() { - if ((this.IsNumLearnableAddressesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResetCapability() { - if ((this.IsResetCapabilityNull == false)) { - return true; - } - return false; - } - - private void ResetScopeOfResidence() { - curObj["ScopeOfResidence"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName) { - string strPath = "ROOT\\virtualization:Msvm_VirtualSwitch"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSwitchCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSwitchCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSwitchCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSwitchCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSwitch"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSwitchCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSwitch", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSwitchCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSwitch CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSwitch(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(uint PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((uint)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSwitchCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSwitchCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSwitch(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSwitchEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSwitchEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSwitchEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSwitch(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitch + public class VirtualEthernetSwitch : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualEthernetSwitch"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualEthernetSwitch() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitch(string keyCreationClassName, string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitch(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualEthernetSwitch(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Dedicated { + get { + return ((ushort[])(curObj["Dedicated"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxIOVOffloadsNull { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of SR-IOV Virtual Function offloads available on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxIOVOffloads { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxIOVOffloads"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxVMQOffloadsNull { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of VMQ offloads allowed for a port on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxVMQOffloads { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxVMQOffloads"])); + } + set { + curObj["MaxVMQOffloads"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherDedicatedDescriptions { + get { + return ((string[])(curObj["OtherDedicatedDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResetCapabilityNull { + get { + if ((curObj["ResetCapability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResetCapability { + get { + if ((curObj["ResetCapability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResetCapability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Roles { + get { + return ((string[])(curObj["Roles"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxIOVOffloads() { + if ((this.IsMaxIOVOffloadsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxVMQOffloads() { + if ((this.IsMaxVMQOffloadsNull == false)) { + return true; + } + return false; + } + + private void ResetMaxVMQOffloads() { + curObj["MaxVMQOffloads"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResetCapability() { + if ((this.IsResetCapabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitch"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualEthernetSwitchCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualEthernetSwitch"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualEthernetSwitchCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitch", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitch CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualEthernetSwitch(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(uint PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((uint)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualEthernetSwitchCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualEthernetSwitch(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitch(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_IDEController.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs old mode 100644 new mode 100755 similarity index 68% rename from plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_IDEController.cs rename to plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs index 1264906847b..63b21e323c9 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.Msvm_IDEController.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs @@ -1,1610 +1,1498 @@ -namespace ServerResource.Tests.ROOT.VIRTUALIZATION { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_IDEController - public class IDEController : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_IDEController"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public IDEController() { - this.InitializeObject(null, null, null); - } - - public IDEController(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(IDEController.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public IDEController(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(IDEController.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public IDEController(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public IDEController(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public IDEController(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public IDEController(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public IDEController(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public IDEController(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLocationIndicatorNull { - get { - if ((curObj["LocationIndicator"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LocationIndicator { - get { - if ((curObj["LocationIndicator"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LocationIndicator"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxNumberControlledNull { - get { - if ((curObj["MaxNumberControlled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxNumberControlled { - get { - if ((curObj["MaxNumberControlled"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxNumberControlled"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ProtocolDescription { - get { - return ((string)(curObj["ProtocolDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolSupportedNull { - get { - if ((curObj["ProtocolSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolSupported { - get { - if ((curObj["ProtocolSupported"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastResetNull { - get { - if ((curObj["TimeOfLastReset"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastReset { - get { - if ((curObj["TimeOfLastReset"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastReset"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLocationIndicator() { - if ((this.IsLocationIndicatorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxNumberControlled() { - if ((this.IsMaxNumberControlledNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolSupported() { - if ((this.IsProtocolSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastReset() { - if ((this.IsTimeOfLastResetNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization:Msvm_IDEController"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static IDEControllerCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static IDEControllerCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static IDEControllerCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static IDEControllerCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static IDEControllerCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_IDEController"; - pathObj.NamespacePath = "root\\virtualization"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new IDEControllerCollection(clsObject.GetInstances(enumOptions)); - } - - public static IDEControllerCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static IDEControllerCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static IDEControllerCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_IDEController", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new IDEControllerCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static IDEController CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new IDEController(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class IDEControllerCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public IDEControllerCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new IDEController(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new IDEControllerEnumerator(privColObj.GetEnumerator()); - } - - public class IDEControllerEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public IDEControllerEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new IDEController(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitchManagementService + public class VirtualEthernetSwitchManagementService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_VirtualEthernetSwitchManagementService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualEthernetSwitchManagementService() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitchManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitchManagementService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualEthernetSwitchManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualEthernetSwitchManagementService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualEthernetSwitchManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitchManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitchManagementService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualEthernetSwitchManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DefineSystem(System.Management.ManagementPath ReferenceConfiguration, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); + inParams["ReferenceConfiguration"] = ((System.Management.ManagementPath)(ReferenceConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null)) { + ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); + inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); + if ((FeatureSettings != null)) { + int len = ((System.Array)(FeatureSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; + } + inParams["FeatureSettings"] = arrProp; + } + else { + inParams["FeatureSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); + if ((ResourceSettings != null)) { + int len = ((System.Array)(ResourceSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; + } + inParams["ResourceSettings"] = arrProp; + } + else { + inParams["ResourceSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualEthernetSwitchManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchManagementServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs new file mode 100755 index 00000000000..38760cf00d1 --- /dev/null +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs @@ -0,0 +1,1034 @@ +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_VirtualHardDiskSettingData + public class VirtualHardDiskSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_VirtualHardDiskSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualHardDiskSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualHardDiskSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualHardDiskSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualHardDiskSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsBlockSizeNull { + get { + if ((curObj["BlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The block size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint BlockSize { + get { + if ((curObj["BlockSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["BlockSize"])); + } + set { + curObj["BlockSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + set { + curObj["Caption"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + set { + curObj["Description"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + set { + curObj["ElementName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFormatNull { + get { + if ((curObj["Format"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The format for the virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FormatValues Format { + get { + if ((curObj["Format"] == null)) { + return ((FormatValues)(System.Convert.ToInt32(0))); + } + return ((FormatValues)(System.Convert.ToInt32(curObj["Format"]))); + } + set { + if ((FormatValues.NULL_ENUM_VALUE == value)) { + curObj["Format"] = null; + } + else { + curObj["Format"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + set { + curObj["InstanceID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLogicalSectorSizeNull { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The logical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LogicalSectorSize { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LogicalSectorSize"])); + } + set { + curObj["LogicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxInternalSizeNull { + get { + if ((curObj["MaxInternalSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum size of the virtual hard disk as viewable by the virtual machine, in " + + "bytes. The specified size will be rounded up to the next largest multiple of the" + + " sector size.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxInternalSize { + get { + if ((curObj["MaxInternalSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxInternalSize"])); + } + set { + curObj["MaxInternalSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The parent of the virtual hard disk. If the virtual hard disk does not have a par" + + "ent, then this field is empty.")] + public string ParentPath { + get { + return ((string)(curObj["ParentPath"])); + } + set { + curObj["ParentPath"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The path of the virtual hard disk.")] + public string Path0 { + get { + return ((string)(curObj["Path"])); + } + set { + curObj["Path"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPhysicalSectorSizeNull { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The physical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PhysicalSectorSize { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PhysicalSectorSize"])); + } + set { + curObj["PhysicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTypeNull { + get { + if ((curObj["Type"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The type of virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public TypeValues Type { + get { + if ((curObj["Type"] == null)) { + return ((TypeValues)(System.Convert.ToInt32(0))); + } + return ((TypeValues)(System.Convert.ToInt32(curObj["Type"]))); + } + set { + if ((TypeValues.NULL_ENUM_VALUE == value)) { + curObj["Type"] = null; + } + else { + curObj["Type"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeBlockSize() { + if ((this.IsBlockSizeNull == false)) { + return true; + } + return false; + } + + private void ResetBlockSize() { + curObj["BlockSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetCaption() { + curObj["Caption"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetDescription() { + curObj["Description"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetElementName() { + curObj["ElementName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeFormat() { + if ((this.IsFormatNull == false)) { + return true; + } + return false; + } + + private void ResetFormat() { + curObj["Format"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeLogicalSectorSize() { + if ((this.IsLogicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetLogicalSectorSize() { + curObj["LogicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeMaxInternalSize() { + if ((this.IsMaxInternalSizeNull == false)) { + return true; + } + return false; + } + + private void ResetMaxInternalSize() { + curObj["MaxInternalSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetParentPath() { + curObj["ParentPath"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPath0() { + curObj["Path"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePhysicalSectorSize() { + if ((this.IsPhysicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetPhysicalSectorSize() { + curObj["PhysicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeType() { + if ((this.IsTypeNull == false)) { + return true; + } + return false; + } + + private void ResetType() { + curObj["Type"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualHardDiskSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualHardDiskSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualHardDiskSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualHardDiskSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualHardDiskSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualHardDiskSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualHardDiskSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualHardDiskSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum FormatValues { + + VHD = 2, + + VHDX = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum TypeValues { + + Fixed = 2, + + Dynamic = 3, + + Differencing = 4, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualHardDiskSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualHardDiskSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualHardDiskSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualHardDiskSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualHardDiskSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualHardDiskSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualHardDiskSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs index b5da7f6c724..72a7b90a0d1 100755 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs @@ -1006,13 +1006,13 @@ inParams["FeatureSettings"] = ((string[])(FeatureSettings)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { @@ -1052,11 +1052,9 @@ inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddKvpItems", inParams, null); Job = null; -// if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { -// Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1074,13 +1072,13 @@ inParams["ResourceSettings"] = ((string[])(ResourceSettings)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null)) { + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { @@ -1097,23 +1095,23 @@ } } - public uint DefineSystem(System.Management.ManagementPath ReferenceConfiguration, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + public uint DefineSystem(string ReferenceConfigurationPath, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); - inParams["ReferenceConfiguration"] = ((System.Management.ManagementPath)(ReferenceConfiguration)).Path; - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - inParams["SystemSettings"] = ((string)(SystemSettings)); + inParams["ReferenceConfiguration"] = ReferenceConfigurationPath; + inParams["ResourceSettings"] = ResourceSettings; + inParams["SystemSettings"] = SystemSettings; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingSystem = null; - if ((outParams.Properties["ResultingSystem"] != null)) { - ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + if ((outParams.Properties["ResultingSystem"] != null && outParams.Properties["ResultingSystem"].Value != null)) + { + ResultingSystem = new System.Management.ManagementPath((string)outParams.Properties["ResultingSystem"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1131,10 +1129,9 @@ inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1153,11 +1150,11 @@ inParams["ExportSettingData"] = ((string)(ExportSettingData)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportSystemDefinition", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { @@ -1290,7 +1287,8 @@ inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSnapshotDefinitions", inParams, null); ImportedSnapshots = null; - if ((outParams.Properties["ImportedSnapshots"] != null)) { + if ((outParams.Properties["ImportedSnapshots"] != null && outParams.Properties["ImportedSnapshots"].Value != null)) + { int len = ((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).Length; System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { @@ -1299,10 +1297,9 @@ ImportedSnapshots = arrToRet; } Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1322,15 +1319,16 @@ inParams["SystemDefinitionFile"] = ((string)(SystemDefinitionFile)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSystemDefinition", inParams, null); ImportedSystem = null; - if ((outParams.Properties["ImportedSystem"] != null)) { + if ((outParams.Properties["ImportedSystem"] != null && outParams.Properties["ImportedSystem"].Value != null)) + { ImportedSystem = new System.Management.ManagementPath(outParams.Properties["ImportedSystem"].ToString()); } Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { @@ -1347,10 +1345,9 @@ inParams["SettingData"] = ((string)(SettingData)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyDiskMergeSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1367,13 +1364,13 @@ inParams["FeatureSettings"] = ((string[])(FeatureSettings)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { @@ -1398,10 +1395,9 @@ inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyKvpItems", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1418,13 +1414,13 @@ inParams["ResourceSettings"] = ((string[])(ResourceSettings)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null)) { + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { @@ -1448,10 +1444,9 @@ inParams["SettingData"] = ((string)(SettingData)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1468,10 +1463,9 @@ inParams["SystemSettings"] = ((string)(SystemSettings)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1488,10 +1482,9 @@ inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RealizePlannedSystem", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } ResultingSystem = null; if ((outParams.Properties["ResultingSystem"] != null)) { @@ -1523,10 +1516,9 @@ } System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1557,11 +1549,9 @@ inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveKvpItems", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1588,11 +1578,9 @@ } System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1610,11 +1598,9 @@ inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1632,11 +1618,9 @@ inParams["NetworkConfiguration"] = ((string[])(NetworkConfiguration)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetGuestNetworkAdapterConfiguration", inParams, null); Job = null; - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) - // if (outParams.Properties["Job"] != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } @@ -1675,10 +1659,9 @@ inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidatePlannedSystem", inParams, null); Job = null; - // if (outParams.Properties["Job"] != null) - if (outParams.Properties["Job"] != null || outParams.Properties["Job"].Value != null) + if ((outParams.Properties["Job"] != null)) { - // Job = new System.Management.ManagementPath(outParams.Properties["Job"].ToString()); + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); } return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs index 72f343250df..abc56818339 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs @@ -1,791 +1,792 @@ -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData - public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemManagementServiceSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemManagementServiceSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string BiosLockString { - get { - return ((string)(curObj["BiosLockString"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The WorldWideNodeName address for dynamically generated WorldWideName addresses u" + - "sed for Synthetic HBAs.\nThis is a read-only property, but it can be changed usin" + - "g the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService cl" + - "ass.")] - public string CurrentWWNNAddress { - get { - return ((string)(curObj["CurrentWWNNAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + - "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + - "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultExternalDataRoot { - get { - return ((string)(curObj["DefaultExternalDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + - "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + - "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultVirtualHardDiskPath { - get { - return ((string)(curObj["DefaultVirtualHardDiskPath"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHbaLunTimeoutNull { - get { - if ((curObj["HbaLunTimeout"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"This property describes the amount of time that the Synthetic FC virtual device will wait for a LUN to appear before starting a virtual machine. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint HbaLunTimeout { - get { - if ((curObj["HbaLunTimeout"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["HbaLunTimeout"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MaximumMacAddress { - get { - return ((string)(curObj["MaximumMacAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum WorldWidePortName address for dynamically generated WorldWideName add" + - "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + - "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + - "rvice class.")] - public string MaximumWWPNAddress { - get { - return ((string)(curObj["MaximumWWPNAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MinimumMacAddress { - get { - return ((string)(curObj["MinimumMacAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The minimum WorldWidePortName address for dynamically generated WorldWideName add" + - "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + - "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + - "rvice class.")] - public string MinimumWWPNAddress { - get { - return ((string)(curObj["MinimumWWPNAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumaSpanningEnabledNull { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Reserved for future use.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool NumaSpanningEnabled { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["NumaSpanningEnabled"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + - "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + - "ttings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeHbaLunTimeout() { - if ((this.IsHbaLunTimeoutNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumaSpanningEnabled() { - if ((this.IsNumaSpanningEnabledNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementServiceSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemManagementServiceSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemManagementServiceSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData + public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemManagementServiceSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemManagementServiceSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string BiosLockString { + get { + return ((string)(curObj["BiosLockString"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The WorldWideNodeName address for dynamically generated WorldWideName addresses u" + + "sed for Synthetic HBAs.\nThis is a read-only property, but it can be changed usin" + + "g the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService cl" + + "ass.")] + public string CurrentWWNNAddress { + get { + return ((string)(curObj["CurrentWWNNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + + "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + + "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultExternalDataRoot { + get { + return ((string)(curObj["DefaultExternalDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + + "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + + "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultVirtualHardDiskPath { + get { + return ((string)(curObj["DefaultVirtualHardDiskPath"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHbaLunTimeoutNull { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"This property describes the amount of time that the Synthetic FC virtual device will wait for a LUN to appear before starting a virtual machine. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint HbaLunTimeout { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["HbaLunTimeout"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MaximumMacAddress { + get { + return ((string)(curObj["MaximumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MaximumWWPNAddress { + get { + return ((string)(curObj["MaximumWWPNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MinimumMacAddress { + get { + return ((string)(curObj["MinimumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MinimumWWPNAddress { + get { + return ((string)(curObj["MinimumWWPNAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumaSpanningEnabledNull { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reserved for future use.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool NumaSpanningEnabled { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["NumaSpanningEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + + "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + + "ttings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeHbaLunTimeout() { + if ((this.IsHbaLunTimeoutNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumaSpanningEnabled() { + if ((this.IsNumaSpanningEnabledNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementServiceSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemManagementServiceSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemManagementServiceSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj index ad6245e6d74..da0c0d6ce7c 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/WmiWrappers.csproj @@ -1,193 +1,175 @@ - - - - - Debug - AnyCPU - {DB824727-BDC3-437C-A364-7A811D8A160F} - Library - Properties - CloudStack.Plugin.WmiWrappers - WmiWrappers - v4.5 - 512 - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\NoUnitTestsDebug\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\NoUnitTests\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll - - - ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll - - - ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll - - - ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll - - - ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll - - - - - - - - - - - ..\packages\xunit.1.9.2\lib\net20\xunit.dll - - - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - - - - - - - - - - + + + + + Debug + AnyCPU + {DB824727-BDC3-437C-A364-7A811D8A160F} + Library + Properties + CloudStack.Plugin.WmiWrappers + WmiWrappers + v4.5 + 512 + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\NoUnitTestsDebug\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\NoUnitTests\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll + + + ..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + ..\packages\log4net.2.0.0\lib\net40-full\log4net.dll + + + ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll + + + ..\packages\NSubstitute.1.6.1.0\lib\NET40\NSubstitute.dll + + + + + + + + + + + ..\packages\xunit.1.9.2\lib\net20\xunit.dll + + + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + + + + + + + + + +