本文整理汇总了C#中System.Management.RelatedObjectQuery类的典型用法代码示例。如果您正苦于以下问题:C# RelatedObjectQuery类的具体用法?C# RelatedObjectQuery怎么用?C# RelatedObjectQuery使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RelatedObjectQuery类属于System.Management命名空间,在下文中一共展示了RelatedObjectQuery类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:19,代码来源:WmiCallsV2.cs
示例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();
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:26,代码来源:WmiCallsV2.cs
示例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;
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:32,代码来源:WmiCallsV2.cs
示例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;
}
开发者ID:ReJeCtAll,项目名称:ralph,代码行数:93,代码来源:WMIDetectorSource.cs
示例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;
}
开发者ID:Makdaam,项目名称:ralph,代码行数:54,代码来源:WMIDetectorSource.cs
示例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;
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:30,代码来源:WmiCallsV2.cs
示例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);
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:38,代码来源:ManagementClass.cs
示例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);
}
}
}
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:79,代码来源:ManagementClass.cs
示例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;
}
开发者ID:OrangeChan,项目名称:cshv3,代码行数:35,代码来源:WmiCalls.cs
示例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;
}
开发者ID:CoryBR,项目名称:OverlayFS,代码行数:28,代码来源:OverlayFS.cs
示例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");
}
}
}
开发者ID:nickchal,项目名称:pash,代码行数:53,代码来源:ManagementObject.cs
示例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;
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:26,代码来源:WmiCallsV2.cs
示例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;
}
开发者ID:OrangeChan,项目名称:cshv3,代码行数:46,代码来源:WmiCalls.cs
示例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();
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:30,代码来源:WmiCallsV2.cs
示例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;
}
开发者ID:beached,项目名称:RemoteWinAdmin,代码行数:27,代码来源:DprCurrentUsers.cs
示例16: GetExternalVirtSwitch
/// <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;
}
开发者ID:KadnikovVN,项目名称:cloudstack,代码行数:93,代码来源:WmiCallsV2.cs
示例17: GetRelated
//******************************************************
//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 = <relatedClass>.</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);
}
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:82,代码来源:ManagementObject.cs
注:本文中的System.Management.RelatedObjectQuery类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论