本文整理汇总了C#中System.Management.RelatedObjectQuery类的典型用法代码示例。如果您正苦于以下问题:C# RelatedObjectQuery类的具体用法?C# RelatedObjectQuery怎么用?C# RelatedObjectQuery使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RelatedObjectQuery类属于System.Management命名空间,在下文中一共展示了RelatedObjectQuery类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetStorageSettings
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();
}
示例2: GetEthernetPortSettings
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();
}
示例3: GetResourceAllocationSettings
/// <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;
}
示例4: GetStorageInfo
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;
}
示例5: GetStorageInfo
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;
}
示例6: GetVmSettings
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;
}
示例7: GetRelatedClasses
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);
}
示例8: GetRelatedClasses
/// <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);
}
}
}
示例9: GetVlanEndpointSettings
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;
}
示例10: IsUserLoggedIn
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;
}
示例11: GetRelated
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");
}
}
}
示例12: GetSyntheticEthernetPortSettings
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;
}
示例13: GetSwitchPort
/// <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;
}
示例14: GetVlanSettings
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();
}
示例15: GetUsersLogonTimestamp
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;
}