Exemplo n.º 1
0
        public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
            {
                throw new InvalidOperationException();
            }
            else
            {
                this.Initialize(true);
                if (watcher != null)
                {
                    if (options != null)
                    {
                        enumerationOption = (EnumerationOptions)options.Clone();
                    }
                    else
                    {
                        enumerationOption = new EnumerationOptions();
                    }
                    EnumerationOptions enumerationOption1 = enumerationOption;
                    enumerationOption1.EnumerateDeep     = true;
                    enumerationOption1.ReturnImmediately = false;
                    if (watcher.HaveListenersForProgress)
                    {
                        enumerationOption1.SendStatus = true;
                    }
                    WmiEventSink       newSink            = watcher.GetNewSink(base.Scope, enumerationOption1.Context);
                    RelatedObjectQuery relatedObjectQuery = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
                    SecurityHandler    securityHandler    = base.Scope.GetSecurityHandler();
                    int num = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(relatedObjectQuery.QueryLanguage, relatedObjectQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), newSink.Stub);
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                    if (num < 0)
                    {
                        watcher.RemoveSink(newSink);
                        if (((long)num & (long)-4096) != (long)-2147217408)
                        {
                            Marshal.ThrowExceptionForHR(num);
                        }
                        else
                        {
                            ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                            return;
                        }
                    }
                    return;
                }
                else
                {
                    throw new ArgumentNullException("watcher");
                }
            }
        }
Exemplo n.º 2
0
        public ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
            {
                throw new InvalidOperationException();
            }
            else
            {
                this.Initialize(false);
                IEnumWbemClassObject enumWbemClassObject = null;
                if (options != null)
                {
                    enumerationOption = (EnumerationOptions)options.Clone();
                }
                else
                {
                    enumerationOption = new EnumerationOptions();
                }
                EnumerationOptions enumerationOption1 = enumerationOption;
                enumerationOption1.EnumerateDeep = true;
                RelatedObjectQuery relatedObjectQuery = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
                SecurityHandler    securityHandler    = null;
                int num = 0;
                try
                {
                    securityHandler = base.Scope.GetSecurityHandler();
                    num             = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(relatedObjectQuery.QueryLanguage, relatedObjectQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), ref enumWbemClassObject);
                }
                finally
                {
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                }
                if (num < 0)
                {
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
                return(new ManagementObjectCollection(base.Scope, enumerationOption1, enumWbemClassObject));
            }
        }
Exemplo n.º 3
0
        public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            this.Initialize(true);
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            EnumerationOptions options2 = (options != null) ? ((EnumerationOptions)options.Clone()) : new EnumerationOptions();

            options2.EnumerateDeep     = true;
            options2.ReturnImmediately = false;
            if (watcher.HaveListenersForProgress)
            {
                options2.SendStatus = true;
            }
            WmiEventSink       newSink         = watcher.GetNewSink(base.Scope, options2.Context);
            RelatedObjectQuery query           = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
            SecurityHandler    securityHandler = null;
            int errorCode = 0;

            securityHandler = base.Scope.GetSecurityHandler();
            errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), newSink.Stub);
            if (securityHandler != null)
            {
                securityHandler.Reset();
            }
            if (errorCode < 0)
            {
                watcher.RemoveSink(newSink);
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
        }
Exemplo n.º 4
0
        public ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            this.Initialize(false);
            IEnumWbemClassObject ppEnum   = null;
            EnumerationOptions   options2 = (options != null) ? ((EnumerationOptions)options.Clone()) : new EnumerationOptions();

            options2.EnumerateDeep = true;
            RelatedObjectQuery query           = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
            SecurityHandler    securityHandler = null;
            int errorCode = 0;

            try
            {
                securityHandler = base.Scope.GetSecurityHandler();
                errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), ref ppEnum);
            }
            finally
            {
                if (securityHandler != null)
                {
                    securityHandler.Reset();
                }
            }
            if (errorCode < 0)
            {
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
            return(new ManagementObjectCollection(base.Scope, options2, ppEnum));
        }
Exemplo n.º 5
0
        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<SyntheticEthernetPortSettingData> results = new List<SyntheticEthernetPortSettingData>(wmiObjCollection.Count);
            foreach (SyntheticEthernetPortSettingData item in wmiObjCollection)
            {
                results.Add(item);
            }

            return results.ToArray();
        }
Exemplo n.º 6
0
        /// <summary>
        /// This method retrieves the dates and times of the
        /// file getting replicated by the server
        /// </summary>
        /// <param name="directoryName">
        /// Path of the directory where the file
        /// resides in the server.
        /// </param>
        /// <param name="fileName">
        /// Name of the file being replicated at present.
        /// The name should be without file extension.
        /// </param>
        /// <param name="computername">
        /// The IP address of the server.
        /// </param>
        /// <param name="domainname">
        /// Domain name in which client and server resides.
        /// </param>
        /// <param name="username">
        /// username to log onto the server.
        /// </param>
        /// <param name="password">
        /// password to log onto to the server.
        /// </param>
        /// <param name="dtType">
        /// This enum specifies which type of date-time
        /// property is to be retrieved.
        /// </param>
        /// <returns>
        /// It returns DateTime structure with only
        /// year-month-day-hour-minute-second filled.
        /// </returns>
        public DateTime GetDateTime(string directoryName,
                                    string fileName,
                                    string computername,
                                    string domainname,
                                    string username,
                                    string password,
                                    fileDateTimeType dtType,
                                    ref fileCheck fileChk)
        {
            string sql = "ASSOCIATORS OF " +
                         "{Win32_Directory='" + directoryName + "'} " +
                         "WHERE " +
                         "AssocClass=CIM_DirectoryContainsFile " +
                         "ResultClass=CIM_DataFile " +
                         "ResultRole=PartComponent " +
                         "Role=GroupComponent";

            string            path  = "\\root\\cimv2";
            ConnectionOptions oConn = new ConnectionOptions();

            oConn.Username = domainname + @"\" + username;
            oConn.Password = password;

            //ManagementScope scope = new System.Management.ManagementScope("root\\cimv2");
            ManagementScope scope = new System.Management.ManagementScope("\\\\" + computername + path, oConn);

            System.Management.RelatedObjectQuery oQuery    = new System.Management.RelatedObjectQuery(sql);
            ManagementObjectSearcher             oSearcher = new ManagementObjectSearcher(scope, oQuery);
            ManagementObjectCollection           oFiles    = oSearcher.Get();

            DateTime dt    = new DateTime();
            int      count = 0;

            foreach (ManagementObject oFile in oFiles)
            {
                string fileInDirectory = Convert.ToString(oFile["FileName"]);
                if (fileInDirectory.ToUpper() == fileName.ToUpper())
                {
                    count++;
                    switch (dtType)
                    {
                    case fileDateTimeType.CreationDate:
                        string creationTime = Convert.ToString(oFile["CreationDate"]);
                        dt = FillDateTimeStructure(creationTime);
                        break;

                    case fileDateTimeType.LastAccessed:
                        string lastAccessedTime = Convert.ToString(oFile["LastAccessed"]);
                        dt = FillDateTimeStructure(lastAccessedTime);
                        break;

                    case fileDateTimeType.LastModified:
                        string lastModifiedTime = Convert.ToString(oFile["LastModified"]);
                        dt = FillDateTimeStructure(lastModifiedTime);
                        break;
                    }
                }
            }

            if (count == 0)
            {
                fileChk = fileCheck.FileNotPresent;
            }

            return(dt);
        }
Exemplo n.º 7
0
        public List<StorageDTOResponse> GetStorageInfo()
        {
            List<StorageDTOResponse> storage = new List<StorageDTOResponse>();

            try
            {
                SelectQuery diskDrivesQuery = new SelectQuery("select Caption, DeviceID, SerialNumber from Win32_DiskDrive");
                ManagementObjectSearcher diskDrivesSearcher = new ManagementObjectSearcher(diskDrivesQuery);

                foreach (ManagementObject diskDrive in diskDrivesSearcher.Get())
                {
                    RelatedObjectQuery diskPartitionsQuery = new RelatedObjectQuery(
                        "associators of {Win32_DiskDrive.DeviceID='" +
                        GetValueAsString(diskDrive, "DeviceID") +
                        "'} where AssocClass=Win32_DiskDriveToDiskPartition"
                    );
                    ManagementObjectSearcher diskPartitionsSearcher = new ManagementObjectSearcher(diskPartitionsQuery);

                    foreach (ManagementObject diskPartition in diskPartitionsSearcher.Get())
                    {
                        RelatedObjectQuery logicalDisksQuery = new RelatedObjectQuery(
                            "associators of {Win32_DiskPartition.DeviceID='" +
                            GetValueAsString(diskPartition, "DeviceID") +
                            "'} where AssocClass=Win32_LogicalDiskToPartition"
                        );
                        ManagementObjectSearcher logicalDisksSearcher = new ManagementObjectSearcher(logicalDisksQuery);

                        foreach (ManagementObject logicalDisk in logicalDisksSearcher.Get())
                        {
                            StorageDTOResponse disk = new StorageDTOResponse();
                            disk.Label = GetValueAsString(diskDrive, "Caption");
                            disk.MountPoint = GetValueAsString(logicalDisk, "Caption");
                            try
                            {
                                disk.Size = ConvertSizeToMiB(Int64.Parse(logicalDisk["Size"].ToString()), SizeUnits.B).ToString();
                            }
                            catch (Exception e)
                            {
                                Logger.Instance.LogError(e.ToString());
                            }
                            disk.Sn = GetValueAsString(diskDrive, "SerialNumber");

                            storage.Add(disk);
                        }
                    }
                }
            }
            catch (ManagementException e)
            {
                Logger.Instance.LogError(e.ToString());
            }

            return storage;
        }
Exemplo n.º 8
0
		public List<StorageDTOResponse> GetStorageInfo()
		{
			List<StorageDTOResponse> storage = new List<StorageDTOResponse>();

			try
			{
				// In Windows <= Windows Server 2003 Win32_DiskDrive doesn't have SerialNumber field.
				string query;
				if (osVersionNumber < 6)
				{
					query = "select Caption, DeviceID, Model from Win32_DiskDrive";
				}
				else
				{
					query = "select Caption, DeviceID, SerialNumber, Model from Win32_DiskDrive";
				}
				
				SelectQuery diskDrivesQuery = new SelectQuery(query);
				ManagementObjectSearcher diskDrivesSearcher = new ManagementObjectSearcher(diskDrivesQuery);
				
				foreach (ManagementObject diskDrive in diskDrivesSearcher.Get())
				{
					string sn = "";
					if (osVersionNumber < 6)
					{
						// In Windows <= Windows Server 2003 we can find SerialNumber in Win32_PhysicalMedia.
						SelectQuery snQuery = new SelectQuery("select SerialNumber from Win32_PhysicalMedia where tag='" + GetValueAsString(diskDrive, "DeviceID").Replace(@"\", @"\\") + "'");
						ManagementObjectSearcher snSearcher = new ManagementObjectSearcher(snQuery);
						
						foreach (ManagementObject snObj in snSearcher.Get())
						{
							sn = GetValueAsString(snObj, "SerialNumber");
							break;
						}
					}
					else
					{
						sn = GetValueAsString(diskDrive, "SerialNumber");
					}
					
					if (sn.Length == 0 ||
						sn.StartsWith("QM000") ||
					    Blacklists.IsDiscVendorInBlacklist(GetValueAsString(diskDrive, "Caption").ToLower()) ||
					    Blacklists.IsDiskProductInBlacklist(GetValueAsString(diskDrive, "Model").ToLower())
					)
					{
						continue;
					}
					
					RelatedObjectQuery diskPartitionsQuery = new RelatedObjectQuery(
						"associators of {Win32_DiskDrive.DeviceID='" +
						GetValueAsString(diskDrive, "DeviceID") +
						"'} where AssocClass=Win32_DiskDriveToDiskPartition"
					);
					ManagementObjectSearcher diskPartitionsSearcher = new ManagementObjectSearcher(diskPartitionsQuery);
					
					foreach (ManagementObject diskPartition in diskPartitionsSearcher.Get())
					{
						RelatedObjectQuery logicalDisksQuery = new RelatedObjectQuery(
							"associators of {Win32_DiskPartition.DeviceID='" +
							GetValueAsString(diskPartition, "DeviceID") +
							"'} where AssocClass=Win32_LogicalDiskToPartition"
						);
						ManagementObjectSearcher logicalDisksSearcher = new ManagementObjectSearcher(logicalDisksQuery);
						
						foreach (ManagementObject logicalDisk in logicalDisksSearcher.Get())
						{
							StorageDTOResponse disk = new StorageDTOResponse();
							disk.Label = GetValueAsString(diskDrive, "Caption");
							disk.MountPoint = GetValueAsString(diskDrive, "DeviceID");
							try
							{
								disk.Size = ConvertSizeToMiB(Int64.Parse(logicalDisk["Size"].ToString()), SizeUnits.B).ToString();
							}
							catch (Exception e)
							{
								Logger.Instance.LogError(e.ToString());
							}
							disk.SerialNumber = sn;
							disk.Family = GetValueAsString(diskDrive, "Model");
							
							storage.Add(disk);
						}
					}
				}
			}
			catch (ManagementException e)
			{
				Logger.Instance.LogError(e.ToString());
			}
			
			return storage;
		}
Exemplo n.º 9
0
		private static DateTime? GetUsersLogonTimestamp( DprCurrentUsers user ) {
			if( string.IsNullOrEmpty( user.UserName ) || string.IsNullOrEmpty( user.Domain ) || Win32.WellKnownSids.ContainsKey( user.Sid ) ) {
				return null;
			}
			WmiHelpers.ForEachWithScope( user.ComputerName, @"SELECT * FROM Win32_LogonSession", ( obj, scope ) => {
				try {
					var roq = new RelatedObjectQuery( string.Format( @"associators of {{Win32_LogonSession.LogonId='{0}'}} WHERE AssocClass = Win32_LoggedOnUser", WmiHelpers.GetString( obj, @"LogonId" ) ) );
					using( var searcher = new ManagementObjectSearcher( scope, roq ) ) {
						foreach( var mobObj in searcher.Get( ) ) {
							Helpers.AssertNotNull( mobObj, @"WMI Error, null value returned." );
							var mob = (ManagementObject)mobObj;
							var name = WmiHelpers.GetString( mob, @"Name" );
							var domain = WmiHelpers.GetString( mob, @"Domain" );
							if( !name.Equals( user.UserName ) || !domain.Equals( user.Domain ) ) {
								continue;
							}
							user.LastLogon = WmiHelpers.GetNullableDate( obj, @"StartTime" );
							return false; // Found, stop loop
						}
					}
				} catch( ManagementException ex ) {
					GlobalLogging.WriteLine( Logging.LogSeverity.Error, @"Error finding last logon on {0} for {1}\{2}\n{3}", user.ComputerName, user.Domain, user.UserName, ex.Message );
				}
				return true;
			}, false, false );
			return user.LastLogon;
		}
Exemplo n.º 10
0
		public void GetRelated(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, EnumerationOptions options)
		{
			EnumerationOptions enumerationOption;
			if (this.path == null || this.path.Path.Length == 0)
			{
				throw new InvalidOperationException();
			}
			else
			{
				this.Initialize(true);
				if (watcher != null)
				{
					if (options != null)
					{
						enumerationOption = (EnumerationOptions)options.Clone();
					}
					else
					{
						enumerationOption = new EnumerationOptions();
					}
					EnumerationOptions enumerationOption1 = enumerationOption;
					enumerationOption1.ReturnImmediately = false;
					if (watcher.HaveListenersForProgress)
					{
						enumerationOption1.SendStatus = true;
					}
					WmiEventSink newSink = watcher.GetNewSink(this.scope, enumerationOption1.Context);
					RelatedObjectQuery relatedObjectQuery = new RelatedObjectQuery(this.path.Path, relatedClass, relationshipClass, relationshipQualifier, relatedQualifier, relatedRole, thisRole, classDefinitionsOnly);
					enumerationOption1.EnumerateDeep = true;
					SecurityHandler securityHandler = this.scope.GetSecurityHandler();
					int num = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).ExecQueryAsync_(relatedObjectQuery.QueryLanguage, relatedObjectQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), newSink.Stub);
					securityHandler.Reset();
					if (num < 0)
					{
						watcher.RemoveSink(newSink);
						if (((long)num & (long)-4096) != (long)-2147217408)
						{
							Marshal.ThrowExceptionForHR(num);
						}
						else
						{
							ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
							return;
						}
					}
					return;
				}
				else
				{
					throw new ArgumentNullException("watcher");
				}
			}
		}
Exemplo n.º 11
0
        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;
        }
Exemplo n.º 12
0
        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.VirtualSystemType == "Microsoft:Hyper-V:System:Realized" ||
                    wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Planned")
                {
                    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;
        }
Exemplo n.º 13
0
        public static 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<VLANEndpoint>().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<VLANEndpointSettingData>().First();
            return vlanEndpointSettings;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Deprecated
        /// </summary>
        /// <param name="nic"></param>
        /// <returns></returns>
        public static 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<VmLANEndpoint>().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<SwitchPort>().First();

            return switchPort;
        }
Exemplo n.º 15
0
		/// <summary>
		///    <para> Retrieves classes related to the 
		///       WMI class, asynchronously, using the specified options.</para>
		/// </summary>
		/// <param name='watcher'>Handler for progress and results of the asynchronous operation.</param>
		/// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param>
		/// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param>
		/// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param>
		/// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param>
		/// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param>
		/// <param name=' thisRole'>The source class must have this role in the relationship.</param>
		/// <param name=' options'>The options for retrieving the resulting classes.</param>
		public void GetRelatedClasses(
			ManagementOperationObserver watcher, 
			string relatedClass,
			string relationshipClass,
			string relationshipQualifier,
			string relatedQualifier,
			string relatedRole,
			string thisRole,
			EnumerationOptions options)
		{
			if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
				throw new InvalidOperationException();

			Initialize ( true ) ;

			if (null == watcher)
				throw new ArgumentNullException("watcher");
			else
			{
				EnumerationOptions o = (null != options) 
								? (EnumerationOptions)options.Clone() : new EnumerationOptions();

				//Ensure EnumerateDeep flag bit is turned off as it's invalid for queries
				o.EnumerateDeep = true;

				// Ensure we switch off ReturnImmediately as this is invalid for async calls
				o.ReturnImmediately = false;

				// If someone has registered for progress, make sure we flag it
				if (watcher.HaveListenersForProgress)
					o.SendStatus = true;
			
				WmiEventSink sink = watcher.GetNewSink(
					Scope, 
					o.Context);

				RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path, 
																relatedClass, relationshipClass, 
																relatedQualifier, relationshipQualifier, 
																relatedRole, thisRole);
            
				SecurityHandler securityHandler = null;
				int status						= (int)ManagementStatus.NoError;

				securityHandler = Scope.GetSecurityHandler();

                            status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).ExecQueryAsync_(
						q.QueryLanguage, 
						q.QueryString, 
						o.Flags, 
						o.GetContext(), 
						sink.Stub);


				if (securityHandler != null)
					securityHandler.Reset();

				if (status < 0)
				{
					watcher.RemoveSink(sink);
					if ((status & 0xfffff000) == 0x80041000)
						ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
					else
						Marshal.ThrowExceptionForHR(status);
				}
			}
		}
Exemplo n.º 16
0
		/// <summary>
		///    <para> Retrieves classes related to the WMI class based on the specified 
		///       options.</para>
		/// </summary>
		/// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param>
		/// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param>
		/// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param>
		/// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param>
		/// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param>
		/// <param name=' thisRole'>The source class must have this role in the relationship.</param>
		/// <param name=' options'>The options for retrieving the resulting classes.</param>
		/// <returns>
		///    <para>A collection of classes related to
		///       this class.</para>
		/// </returns>
		public ManagementObjectCollection GetRelatedClasses(
											string relatedClass,
											string relationshipClass,
											string relationshipQualifier,
											string relatedQualifier,
											string relatedRole,
											string thisRole,
											EnumerationOptions options)
		{
			if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
				throw new InvalidOperationException();

			Initialize ( false ) ;

			IEnumWbemClassObject enumWbem = null;

			EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions();
			//Ensure EnumerateDeep flag bit is turned off as it's invalid for queries
			o.EnumerateDeep = true;

			RelatedObjectQuery q = new RelatedObjectQuery(true,	Path.Path, 
															relatedClass,
															relationshipClass, 
															relatedQualifier,
															relationshipQualifier, 
															relatedRole, thisRole);

			SecurityHandler securityHandler = null;
			int status						= (int)ManagementStatus.NoError;

    		try
			{
				securityHandler = Scope.GetSecurityHandler();
				status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).ExecQuery_(
					q.QueryLanguage, 
					q.QueryString, 
					o.Flags, 
					o.GetContext(), 
					ref enumWbem);

			}
			finally
			{
				if (securityHandler != null)
					securityHandler.Reset();
			}
			
			if (status < 0)
			{
				if ((status & 0xfffff000) == 0x80041000)
					ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
				else
					Marshal.ThrowExceptionForHR(status);
			}

			//Create collection object
			return new ManagementObjectCollection(Scope, o, enumWbem);
		}
Exemplo n.º 17
0
        public bool IsUserLoggedIn(String userName)
        {
            ManagementScope scope = new ManagementScope("\\\\.\\root\\cimv2");

            //String query = "Select * from Win32_LogonSession Where LogonType = 2 OR LogonType = 10";
            String query = "Select * from Win32_LogonSession Where LogonType<>3 AND LogonType<>5 AND LogonType<>8 AND LogonType<>9 AND LogonType<>4";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection userList = searcher.Get();

            foreach (ManagementObject obj in userList)
            {
                string logonID = obj["LogonId"].ToString();

                RelatedObjectQuery s2 = new RelatedObjectQuery("Associators of " + "{Win32_LogonSession.LogonId=" + logonID + "} " + "Where AssocClass=Win32_LoggedOnUser Role=Dependent");
                ManagementObjectSearcher userQuery = new ManagementObjectSearcher(scope, s2);
                ManagementObjectCollection users = userQuery.Get();
                foreach (ManagementObject user in users)
                {
                    String name = (String)user["Domain"] + "\\" + (String)user["Name"];
                    if (userName.Equals(name))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Exemplo n.º 18
0
        /// <summary>
        /// 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
        /// </summary>
        /// <param name="vmSettings"></param>
        /// <returns></returns>
        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 ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
 {
     if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
     {
         throw new InvalidOperationException();
     }
     this.Initialize(false);
     IEnumWbemClassObject ppEnum = null;
     EnumerationOptions options2 = (options != null) ? ((EnumerationOptions) options.Clone()) : new EnumerationOptions();
     options2.EnumerateDeep = true;
     RelatedObjectQuery query = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
     SecurityHandler securityHandler = null;
     int errorCode = 0;
     try
     {
         securityHandler = base.Scope.GetSecurityHandler();
         errorCode = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), ref ppEnum);
     }
     finally
     {
         if (securityHandler != null)
         {
             securityHandler.Reset();
         }
     }
     if (errorCode < 0)
     {
         if ((errorCode & 0xfffff000L) == 0x80041000L)
         {
             ManagementException.ThrowWithExtendedInfo((ManagementStatus) errorCode);
         }
         else
         {
             Marshal.ThrowExceptionForHR(errorCode);
         }
     }
     return new ManagementObjectCollection(base.Scope, options2, ppEnum);
 }
Exemplo n.º 20
0
        public StorageAllocationSettingData[] GetStorageSettings(ComputerSystem vm)
        {
            // ComputerSystem -> VirtualSystemSettingData -> EthernetPortAllocationSettingData
            VirtualSystemSettingData vmSettings = GetVmSettings(vm);

            var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, StorageAllocationSettingData.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 StorageAllocationSettingData.StorageAllocationSettingDataCollection(wmiObjectSearch.Get());

            var result = new List<StorageAllocationSettingData>(wmiObjCollection.Count);
            foreach (StorageAllocationSettingData item in wmiObjCollection)
            {
                result.Add(item);
            }
            return result.ToArray();
        }
 public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
 {
     if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
     {
         throw new InvalidOperationException();
     }
     this.Initialize(true);
     if (watcher == null)
     {
         throw new ArgumentNullException("watcher");
     }
     EnumerationOptions options2 = (options != null) ? ((EnumerationOptions) options.Clone()) : new EnumerationOptions();
     options2.EnumerateDeep = true;
     options2.ReturnImmediately = false;
     if (watcher.HaveListenersForProgress)
     {
         options2.SendStatus = true;
     }
     WmiEventSink newSink = watcher.GetNewSink(base.Scope, options2.Context);
     RelatedObjectQuery query = new RelatedObjectQuery(true, this.Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole);
     SecurityHandler securityHandler = null;
     int errorCode = 0;
     securityHandler = base.Scope.GetSecurityHandler();
     errorCode = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), newSink.Stub);
     if (securityHandler != null)
     {
         securityHandler.Reset();
     }
     if (errorCode < 0)
     {
         watcher.RemoveSink(newSink);
         if ((errorCode & 0xfffff000L) == 0x80041000L)
         {
             ManagementException.ThrowWithExtendedInfo((ManagementStatus) errorCode);
         }
         else
         {
             Marshal.ThrowExceptionForHR(errorCode);
         }
     }
 }
Exemplo n.º 22
0
        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<EthernetSwitchPortVlanSettingData>().First();
        }
Exemplo n.º 23
0
		public ManagementObjectCollection GetRelated(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, EnumerationOptions options)
		{
			EnumerationOptions enumerationOption;
			if (this.path == null || this.path.Path.Length == 0)
			{
				throw new InvalidOperationException();
			}
			else
			{
				this.Initialize(false);
				IEnumWbemClassObject enumWbemClassObject = null;
				if (options != null)
				{
					enumerationOption = options;
				}
				else
				{
					enumerationOption = new EnumerationOptions();
				}
				EnumerationOptions enumerationOption1 = enumerationOption;
				RelatedObjectQuery relatedObjectQuery = new RelatedObjectQuery(this.path.Path, relatedClass, relationshipClass, relationshipQualifier, relatedQualifier, relatedRole, thisRole, classDefinitionsOnly);
				enumerationOption1.EnumerateDeep = true;
				SecurityHandler securityHandler = null;
				try
				{
					securityHandler = this.scope.GetSecurityHandler();
					int num = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).ExecQuery_(relatedObjectQuery.QueryLanguage, relatedObjectQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), ref enumWbemClassObject);
					if (num < 0)
					{
						if (((long)num & (long)-4096) != (long)-2147217408)
						{
							Marshal.ThrowExceptionForHR(num);
						}
						else
						{
							ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
						}
					}
				}
				finally
				{
					if (securityHandler != null)
					{
						securityHandler.Reset();
					}
				}
				return new ManagementObjectCollection(this.scope, enumerationOption1, enumWbemClassObject);
			}
		}
Exemplo n.º 24
0
        /// <summary>
        /// External VSwitch has an external NIC, and we assume there is only one external NIC and one external vswitch.
        /// </summary>
        /// <param name="vmSettings"></param>
        /// <returns></returns>
        /// <throw>Throws if there is no vswitch</throw>
        /// <remarks>
        /// 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
        /// </remarks>
        public static VirtualEthernetSwitch GetExternalVirtSwitch(String vSwitchName)
        {
            // Work back from the first *bound* external NIC we find.
            var externNICs = ExternalEthernetPort.GetInstances("IsBound = TRUE");
            VirtualEthernetSwitch vSwitch = null;
            // Assert
            if (externNICs.Count == 0 )
            {
                var errMsg = "No ExternalEthernetPort available to Hyper-V";
                var ex = new WmiException(errMsg);
                logger.Error(errMsg, ex);
                throw ex;
            }
            foreach(ExternalEthernetPort externNIC in externNICs.OfType<ExternalEthernetPort>()) {
            // 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<LANEndpoint>().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<LANEndpoint>().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<EthernetSwitchPort>().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;
            }
            vSwitch = vSwitchCollection.OfType<VirtualEthernetSwitch>().First();
            if (vSwitch.ElementName.Equals(vSwitchName) == true)
            {
                return vSwitch;
            }
            }
            return vSwitch;
        }
        //******************************************************
        //GetRelated 
        //****************************************************
        /// <summary>
        ///    <para>Gets a collection of objects related to the object (associators).</para>
        /// </summary>
        /// <param name='relatedClass'>The class of the related objects. </param>
        /// <param name='relationshipClass'>The relationship class of interest. </param>
        /// <param name='relationshipQualifier'>The qualifier required to be present on the relationship class. </param>
        /// <param name='relatedQualifier'>The qualifier required to be present on the related class. </param>
        /// <param name='relatedRole'>The role that the related class is playing in the relationship. </param>
        /// <param name='thisRole'>The role that this class is playing in the relationship. </param>
        /// <param name='classDefinitionsOnly'>When this method returns, it contains only class definitions for the instances that match the query. </param>
        /// <param name='options'>Extended options for how to execute the query. </param>
        /// <returns>
        ///    A <see cref='System.Management.ManagementObjectCollection'/> containing the related objects.
        /// </returns>
        /// <remarks>
        ///    <para>This operation is equivalent to an ASSOCIATORS OF query where ResultClass = &lt;relatedClass&gt;.</para>
        /// </remarks>
        public ManagementObjectCollection GetRelated(
            string relatedClass,
            string relationshipClass,
            string relationshipQualifier,
            string relatedQualifier,
            string relatedRole,
            string thisRole,
            bool classDefinitionsOnly,
            EnumerationOptions options)
        {
            if ((null == path) || (path.Path.Length==0))
                throw new InvalidOperationException();
            
            Initialize ( false ) ;

            IEnumWbemClassObject enumWbem = null;
            EnumerationOptions o = (null != options) ? options : new EnumerationOptions();
            RelatedObjectQuery q = new RelatedObjectQuery(
                path.Path, 
                relatedClass,
                relationshipClass, 
                relationshipQualifier,
                relatedQualifier, relatedRole, 
                thisRole, classDefinitionsOnly);
            

            //Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
            o.EnumerateDeep = true; //note this turns the FLAG to 0 !!

            SecurityHandler securityHandler = null;
            int status                        = (int)ManagementStatus.NoError;

            try
            {
                securityHandler = scope.GetSecurityHandler();

                status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
                                                        q.QueryLanguage, 
                                                        q.QueryString, 
                                                        o.Flags, 
                                                        o.GetContext(), 
                                                        ref enumWbem);


                if (status < 0)
                {
                    if ((status & 0xfffff000) == 0x80041000)
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    else
                        Marshal.ThrowExceptionForHR(status);
                }

            }
            finally
            {
                if (securityHandler != null)
                    securityHandler.Reset();
            }

            //Create collection object
            return new ManagementObjectCollection(scope, o, enumWbem);
        }