private static bool _IsClass(IWbemClassObjectFreeThreaded wbemObject) { object val = null; int dummy1 = 0, dummy2 = 0; int status = wbemObject.Get_("__GENUS", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } return((int)val == (int)tag_WBEM_GENUS_TYPE.WBEM_GENUS_CLASS); }
/// <summary> /// <para>Removes a <see cref='System.Management.PropertyData'/> from the <see cref='System.Management.PropertyDataCollection'/>.</para> /// </summary> /// <param name='propertyName'>The name of the property to be removed.</param> /// <remarks> /// <para> Properties can only be removed from class definitions, /// not from instances. This method is only valid when invoked on a property /// collection in a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("MyClass"); /// c.Properties.Remove("PropThatIDontWantOnThisClass"); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("MyClass") /// c.Properties.Remove("PropThatIDontWantOnThisClass") /// </code> /// </example> public virtual void Remove(string propertyName) { // On instances, reset the property to the default value for the class. if (parent.GetType() == typeof(ManagementObject)) { ManagementClass cls = new ManagementClass(parent.ClassPath); parent.SetPropertyValue(propertyName, cls.GetPropertyValue(propertyName)); } else { int status = parent.wbemObject.Delete_(propertyName); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } }
public int Clone_(out IWbemClassObjectFreeThreaded ppCopy) { IntPtr ptr; if (this.pWbemClassObject == IntPtr.Zero) { throw new ObjectDisposedException(name); } int num = WmiNetUtilsHelper.Clone_f(12, this.pWbemClassObject, out ptr); if (num < 0) { ppCopy = null; } else { ppCopy = new IWbemClassObjectFreeThreaded(ptr); } GC.KeepAlive(this); return(num); }
public int SpawnInstance_(int lFlags, out IWbemClassObjectFreeThreaded ppNewInstance) { IntPtr ptr; if (this.pWbemClassObject == IntPtr.Zero) { throw new ObjectDisposedException(name); } int num = WmiNetUtilsHelper.SpawnInstance_f(15, this.pWbemClassObject, lFlags, out ptr); if (num < 0) { ppNewInstance = null; } else { ppNewInstance = new IWbemClassObjectFreeThreaded(ptr); } GC.KeepAlive(this); return(num); }
public int GetQualifierSet_(out IWbemQualifierSetFreeThreaded ppQualSet) { IntPtr ptr; if (this.pWbemClassObject == IntPtr.Zero) { throw new ObjectDisposedException(name); } int num = WmiNetUtilsHelper.GetQualifierSet_f(3, this.pWbemClassObject, out ptr); if (num < 0) { ppQualSet = null; } else { ppQualSet = new IWbemQualifierSetFreeThreaded(ptr); } GC.KeepAlive(this); return(num); }
//This private function is used to refresh the information from the Wmi object before returning the requested data private void RefreshMethodInfo() { int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.GetMethod_(methodName, 0, out wmiInParams, out wmiOutParams); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } }
//internal factory /// <summary> /// Internal static "factory" method for making a new ManagementPath /// from the system property of a WMI object /// </summary> /// <param name="wbemObject">The WMI object whose __PATH property will /// be used to supply the returned object</param> internal static string GetManagementPath( IWbemClassObjectFreeThreaded wbemObject) { string path = null; int status = (int)ManagementStatus.Failed; if (null != wbemObject) { int dummy1 = 0, dummy2 = 0; object val = null; status = wbemObject.Get_("__PATH", 0, ref val, ref dummy1, ref dummy2); if ((status < 0) || (val == System.DBNull.Value)) { //try to get the relpath instead status = wbemObject.Get_("__RELPATH", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } if (System.DBNull.Value == val) { path = null; } else { path = (string)val; } } return(path); }
/// <summary> /// <para>Adds a <see cref='System.Management.QualifierData'/> to the <see cref='System.Management.QualifierDataCollection'/>. This overload /// specifies all property values for a <see cref='System.Management.QualifierData'/> object.</para> /// </summary> /// <param name='qualifierName'>The qualifier name. </param> /// <param name='qualifierValue'>The qualifier value. </param> /// <param name='isAmended'><see langword='true'/> to specify that this qualifier is amended (flavor); otherwise, <see langword='false'/>. </param> /// <param name='propagatesToInstance'><see langword='true'/> to propagate this qualifier to instances; otherwise, <see langword='false'/>. </param> /// <param name='propagatesToSubclass'><see langword='true'/> to propagate this qualifier to subclasses; otherwise, <see langword='false'/>. </param> /// <param name='isOverridable'><see langword='true'/> to specify that this qualifier's value is overridable in instances of subclasses; otherwise, <see langword='false'/>. </param> public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable) { //Build the flavors bitmask and call the internal Add that takes a bitmask int qualFlavor = 0; if (isAmended) { qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED); } if (propagatesToInstance) { qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE); } if (propagatesToSubclass) { qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS); } // Note we use the NOT condition here since WBEM_FLAVOR_OVERRIDABLE == 0 if (!isOverridable) { qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_NOT_OVERRIDABLE); } //Try to add the qualifier to the WMI object int status = GetTypeQualifierSet().Put_(qualifierName, ref qualifierValue, qualFlavor); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } }
protected WmiEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, string path, string className) { try { this.context = context; this.watcher = watcher; this.className = className; this.isLocal = false; if (null != path) { this.path = new ManagementPath(path); if ((0 == string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) || (0 == string.Compare(this.path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase))) { this.isLocal = true; } } if (null != scope) { this.scope = (ManagementScope)scope.Clone(); if (null == path) // use scope to see if sink is local { if ((0 == string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) || (0 == string.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase))) { this.isLocal = true; } } } WmiNetUtilsHelper.GetDemultiplexedStub_f(this, this.isLocal, out stub); hash = Threading.Interlocked.Increment(ref s_hash); } catch {} }
private void ClearKeys(bool setAsSingleton) { // Test/utilize isWbemPathShared *only* on public + internal members! int status = (int)ManagementStatus.NoError; try { if (null != wmiPath) { IWbemPathKeyList keyList = null; status = wmiPath.GetKeyList_(out keyList); if (null != keyList) { status = keyList.RemoveAllKeys_(0); if ((status & 0x80000000) == 0) { sbyte bSingleton = (setAsSingleton) ? (sbyte)(-1) : (sbyte)0; status = keyList.MakeSingleton_(bSingleton); FireIdentifierChanged(); } } } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } }
//This variant takes the full information, i.e. the method name and in & out param objects /// <summary> /// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>. This overload will add a new method with the /// specified parameter objects to the collection.</para> /// </summary> /// <param name='methodName'>The name of the method to add.</param> /// <param name=' inParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the input parameters to the method.</param> /// <param name=' outParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the output parameters to the method.</param> /// <remarks> /// <para> Adding <see cref='System.Management.MethodData'/> objects to the <see cref='System.Management.MethodDataCollection'/> can only be /// done when the class has no instances. Any other case will result in an /// exception.</para> /// </remarks> public virtual void Add(string methodName, ManagementBaseObject inParameters, ManagementBaseObject outParameters) { IWbemClassObjectFreeThreaded wbemIn = null, wbemOut = null; if (parent.GetType() == typeof(ManagementObject)) //can't add methods to instance { throw new InvalidOperationException(); } if (inParameters != null) { wbemIn = inParameters.wbemObject; } if (outParameters != null) { wbemOut = outParameters.wbemObject; } int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.PutMethod_(methodName, 0, wbemIn, wbemOut); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } }
public int Clone_(out IWbemClassObjectFreeThreaded ppCopy) { IntPtr intPtr; if (this.pWbemClassObject != IntPtr.Zero) { int cloneF = WmiNetUtilsHelper.Clone_f(12, this.pWbemClassObject, out intPtr); if (cloneF >= 0) { ppCopy = new IWbemClassObjectFreeThreaded(intPtr); } else { ppCopy = null; } GC.KeepAlive(this); return(cloneF); } else { throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name); } }
public int SpawnDerivedClass_(int lFlags, out IWbemClassObjectFreeThreaded ppNewClass) { IntPtr intPtr; if (this.pWbemClassObject != IntPtr.Zero) { int num = WmiNetUtilsHelper.SpawnDerivedClass_f(14, this.pWbemClassObject, lFlags, out intPtr); if (num >= 0) { ppNewClass = new IWbemClassObjectFreeThreaded(intPtr); } else { ppNewClass = null; } GC.KeepAlive(this); return(num); } else { throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name); } }
public int GetQualifierSet_(out IWbemQualifierSetFreeThreaded ppQualSet) { IntPtr intPtr; if (this.pWbemClassObject != IntPtr.Zero) { int getQualifierSetF = WmiNetUtilsHelper.GetQualifierSet_f(3, this.pWbemClassObject, out intPtr); if (getQualifierSetF >= 0) { ppQualSet = new IWbemQualifierSetFreeThreaded(intPtr); } else { ppQualSet = null; } GC.KeepAlive(this); return(getQualifierSetF); } else { throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name); } }
public int GetPropertyQualifierSet_(string wszProperty, out IWbemQualifierSetFreeThreaded ppQualSet) { IntPtr intPtr; if (this.pWbemClassObject != IntPtr.Zero) { int num = WmiNetUtilsHelper.GetPropertyQualifierSet_f(11, this.pWbemClassObject, wszProperty, out intPtr); if (num >= 0) { ppQualSet = new IWbemQualifierSetFreeThreaded(intPtr); } else { ppQualSet = null; } GC.KeepAlive(this); return(num); } else { throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name); } }
internal PropertyDataEnumerator(ManagementBaseObject parent, bool isSystem) { this.parent = parent; propertyNames = null; index = -1; int flag; object qualVal = null; if (isSystem) flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_SYSTEM_ONLY; else flag = (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_NONSYSTEM_ONLY; flag |= (int)tag_WBEM_CONDITION_FLAG_TYPE.WBEM_FLAG_ALWAYS; int status = parent.wbemObject.GetNames_(null, flag, ref qualVal, out propertyNames); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } }
/// <summary> /// <para>Adds a new <see cref='System.Management.PropertyData'/> with the specified value and CIM type.</para> /// </summary> /// <param name='propertyName'>The name of the property.</param> /// <param name='propertyValue'>The value of the property (which can be null).</param> /// <param name='propertyType'>The CIM type of the property.</param> /// <remarks> /// <para> Properties can only be added to class definitions, not /// to instances. This method is only valid when invoked on a <see cref='System.Management.PropertyDataCollection'/> /// in /// a <see cref='System.Management.ManagementClass'/>.</para> /// </remarks> public void Add(string propertyName, object propertyValue, CimType propertyType) { if (null == propertyName) { throw new ArgumentNullException(nameof(propertyName)); } if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance { throw new InvalidOperationException(); } int wmiCimType = (int)propertyType; bool isArray = false; if ((null != propertyValue) && propertyValue.GetType().IsArray) { isArray = true; wmiCimType |= (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY; } object wmiValue = PropertyData.MapValueToWmiValue(propertyValue, propertyType, isArray); int status = parent.wbemObject.Put_(propertyName, 0, ref wmiValue, wmiCimType); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } }
/// <summary> /// Return the qualifier set associated with its type /// </summary> private IWbemQualifierSetFreeThreaded GetTypeQualifierSet(QualifierType qualifierSetType) { IWbemQualifierSetFreeThreaded qualifierSet = null; int status = (int)ManagementStatus.NoError; switch (qualifierSetType) { case QualifierType.ObjectQualifier: status = parent.wbemObject.GetQualifierSet_(out qualifierSet); break; case QualifierType.PropertyQualifier: status = parent.wbemObject.GetPropertyQualifierSet_(propertyOrMethodName, out qualifierSet); break; case QualifierType.MethodQualifier: status = parent.wbemObject.GetMethodQualifierSet_(propertyOrMethodName, out qualifierSet); break; default: throw new ManagementException(ManagementStatus.Unexpected, null, null); // Is this the best fit error ?? } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } return(qualifierSet); }
//****************************************************** //GetText //****************************************************** /// <summary> /// <para>Returns a textual representation of the object in the specified format.</para> /// </summary> /// <param name='format'>The requested textual format. </param> /// <returns> /// <para>The textual representation of the /// object in the specified format.</para> /// </returns> public string GetText(TextFormat format) { string objText = null; int status = (int)ManagementStatus.NoError; // // Removed Initialize call since wbemObject is a property that will call Initialize ( true ) on // its getter. // switch (format) { case TextFormat.Mof: status = wbemObject.GetObjectText_(0, out objText); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } return(objText); case TextFormat.CimDtd20: case TextFormat.WmiDtd20: //This may throw on non-XP platforms... - should we catch ? IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc) new WbemObjectTextSrc(); IWbemContext ctx = (IWbemContext) new WbemContext(); object v = (bool)true; ctx.SetValue_("IncludeQualifiers", 0, ref v); ctx.SetValue_("IncludeClassOrigin", 0, ref v); if (wbemTextSrc != null) { status = wbemTextSrc.GetText_(0, (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)), (uint)format, //note: this assumes the format enum has the same values as the underlying WMI enum !! ctx, out objText); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } return(objText); default: return(null); } }
static WmiNetUtilsHelper() { if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix) { WmiNetUtilsHelper.ResetSecurity_f = UnixWmiNetUtils.ResetSecurity; WmiNetUtilsHelper.SetSecurity_f = UnixWmiNetUtils.SetSecurity; WmiNetUtilsHelper.BlessIWbemServices_f = UnixWmiNetUtils.BlessIWbemServices; WmiNetUtilsHelper.BlessIWbemServicesObject_f = UnixWmiNetUtils.BlessIWbemServicesObject; WmiNetUtilsHelper.GetPropertyHandle_f27 = UnixWmiNetUtils.GetPropertyHandle; WmiNetUtilsHelper.WritePropertyValue_f28 = UnixWmiNetUtils.WritePropertyValue; WmiNetUtilsHelper.Clone_f12 = UnixWmiNetUtils.Clone; WmiNetUtilsHelper.VerifyClientKey_f = UnixWmiNetUtils.VerifyClientKey; WmiNetUtilsHelper.GetQualifierSet_f = UnixWmiNetUtils.GetQualifierSet; WmiNetUtilsHelper.Get_f = UnixWmiNetUtils.Get; WmiNetUtilsHelper.Put_f = UnixWmiNetUtils.Put; WmiNetUtilsHelper.Delete_f = UnixWmiNetUtils.Delete; WmiNetUtilsHelper.GetNames_f = UnixWmiNetUtils.GetNames; WmiNetUtilsHelper.BeginEnumeration_f = UnixWmiNetUtils.BeginEnumeration; WmiNetUtilsHelper.Next_f = UnixWmiNetUtils.Next; WmiNetUtilsHelper.EndEnumeration_f = UnixWmiNetUtils.EndEnumeration; WmiNetUtilsHelper.GetPropertyQualifierSet_f = UnixWmiNetUtils.GetPropertyQualifierSet; WmiNetUtilsHelper.Clone_f = UnixWmiNetUtils.Clone; WmiNetUtilsHelper.GetObjectText_f = UnixWmiNetUtils.GetObjectText; WmiNetUtilsHelper.SpawnDerivedClass_f = UnixWmiNetUtils.SpawnDerivedClass; WmiNetUtilsHelper.SpawnInstance_f = UnixWmiNetUtils.SpawnInstance; WmiNetUtilsHelper.CompareTo_f = UnixWmiNetUtils.CompareTo; WmiNetUtilsHelper.GetPropertyOrigin_f = UnixWmiNetUtils.GetPropertyOrigin; WmiNetUtilsHelper.InheritsFrom_f = UnixWmiNetUtils.InheritsFrom; WmiNetUtilsHelper.GetMethod_f = UnixWmiNetUtils.GetMethod; WmiNetUtilsHelper.PutMethod_f = UnixWmiNetUtils.PutMethod; WmiNetUtilsHelper.DeleteMethod_f = UnixWmiNetUtils.DeleteMethod; WmiNetUtilsHelper.BeginMethodEnumeration_f = UnixWmiNetUtils.BeginMethodEnumeration; WmiNetUtilsHelper.NextMethod_f = UnixWmiNetUtils.NextMethod; WmiNetUtilsHelper.EndMethodEnumeration_f = UnixWmiNetUtils.EndMethodEnumeration; WmiNetUtilsHelper.GetMethodQualifierSet_f = UnixWmiNetUtils.GetMethodQualifierSet; WmiNetUtilsHelper.GetMethodOrigin_f = UnixWmiNetUtils.GetMethodOrigin; WmiNetUtilsHelper.QualifierGet_f = UnixWmiNetUtils.QualifierSet_Get; WmiNetUtilsHelper.QualifierPut_f = UnixWmiNetUtils.QualifierSet_Put; WmiNetUtilsHelper.QualifierDelete_f = UnixWmiNetUtils.QualifierSet_Delete; WmiNetUtilsHelper.QualifierGetNames_f = UnixWmiNetUtils.QualifierSet_GetNames; WmiNetUtilsHelper.QualifierBeginEnumeration_f = UnixWmiNetUtils.QualifierSet_BeginEnumeration; WmiNetUtilsHelper.QualifierNext_f = UnixWmiNetUtils.QualifierSet_Next; WmiNetUtilsHelper.QualifierEndEnumeration_f = UnixWmiNetUtils.QualifierSet_EndEnumeration; WmiNetUtilsHelper.GetCurrentApartmentType_f = UnixWmiNetUtils.GetCurrentApartmentType; WmiNetUtilsHelper.GetDemultiplexedStub_f = UnixWmiNetUtils.GetDemultiplexedStub; WmiNetUtilsHelper.CreateInstanceEnumWmi_f = UnixWmiNetUtils.CreateInstanceEnumWmi; WmiNetUtilsHelper.CreateClassEnumWmi_f = UnixWmiNetUtils.CreateClassEnumWmi; WmiNetUtilsHelper.ExecQueryWmi_f = UnixWmiNetUtils.ExecQueryWmi; WmiNetUtilsHelper.ExecNotificationQueryWmi_f = UnixWmiNetUtils.ExecNotificationQueryWmi; WmiNetUtilsHelper.PutInstanceWmi_f = UnixWmiNetUtils.PutInstanceWmi; WmiNetUtilsHelper.PutClassWmi_f = UnixWmiNetUtils.PutClassWmi; WmiNetUtilsHelper.CloneEnumWbemClassObject_f = UnixWmiNetUtils.CloneEnumWbemClassObject; WmiNetUtilsHelper.ConnectServerWmi_f = UnixWmiNetUtils.ConnectServerWmi; } else { WmiNetUtilsHelper.myDllPath = string.Concat(RuntimeEnvironment.GetRuntimeDirectory(), "\\wminet_utils.dll"); IntPtr intPtr = WmiNetUtilsHelper.LoadLibrary(WmiNetUtilsHelper.myDllPath); if (intPtr != IntPtr.Zero) { IntPtr procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ResetSecurity"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ResetSecurity_f = (WmiNetUtilsHelper.ResetSecurity)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ResetSecurity)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SetSecurity"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SetSecurity_f = (WmiNetUtilsHelper.SetSecurity)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SetSecurity)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BlessIWbemServices"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BlessIWbemServices_f = (WmiNetUtilsHelper.BlessIWbemServices)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BlessIWbemServices)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BlessIWbemServicesObject"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BlessIWbemServicesObject_f = (WmiNetUtilsHelper.BlessIWbemServicesObject)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BlessIWbemServicesObject)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyHandle"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyHandle_f27 = (WmiNetUtilsHelper.GetPropertyHandle)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyHandle)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "WritePropertyValue"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.WritePropertyValue_f28 = (WmiNetUtilsHelper.WritePropertyValue)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.WritePropertyValue)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Clone"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Clone_f12 = (WmiNetUtilsHelper.Clone)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Clone)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "VerifyClientKey"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.VerifyClientKey_f = (WmiNetUtilsHelper.VerifyClientKey)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.VerifyClientKey)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetQualifierSet_f = (WmiNetUtilsHelper.GetQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Get"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Get_f = (WmiNetUtilsHelper.Get)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Get)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Put"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Put_f = (WmiNetUtilsHelper.Put)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Put)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Delete"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Delete_f = (WmiNetUtilsHelper.Delete)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Delete)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetNames"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetNames_f = (WmiNetUtilsHelper.GetNames)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetNames)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BeginEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BeginEnumeration_f = (WmiNetUtilsHelper.BeginEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BeginEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Next"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Next_f = (WmiNetUtilsHelper.Next)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Next)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "EndEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.EndEnumeration_f = (WmiNetUtilsHelper.EndEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.EndEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyQualifierSet_f = (WmiNetUtilsHelper.GetPropertyQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Clone"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Clone_f = (WmiNetUtilsHelper.Clone)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Clone)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetObjectText"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetObjectText_f = (WmiNetUtilsHelper.GetObjectText)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetObjectText)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SpawnDerivedClass"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SpawnDerivedClass_f = (WmiNetUtilsHelper.SpawnDerivedClass)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SpawnDerivedClass)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SpawnInstance"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SpawnInstance_f = (WmiNetUtilsHelper.SpawnInstance)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SpawnInstance)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CompareTo"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CompareTo_f = (WmiNetUtilsHelper.CompareTo)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CompareTo)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyOrigin"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyOrigin_f = (WmiNetUtilsHelper.GetPropertyOrigin)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyOrigin)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "InheritsFrom"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.InheritsFrom_f = (WmiNetUtilsHelper.InheritsFrom)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.InheritsFrom)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethod_f = (WmiNetUtilsHelper.GetMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutMethod_f = (WmiNetUtilsHelper.PutMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "DeleteMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.DeleteMethod_f = (WmiNetUtilsHelper.DeleteMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.DeleteMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BeginMethodEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BeginMethodEnumeration_f = (WmiNetUtilsHelper.BeginMethodEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BeginMethodEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "NextMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.NextMethod_f = (WmiNetUtilsHelper.NextMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.NextMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "EndMethodEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.EndMethodEnumeration_f = (WmiNetUtilsHelper.EndMethodEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.EndMethodEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethodQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethodQualifierSet_f = (WmiNetUtilsHelper.GetMethodQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethodQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethodOrigin"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethodOrigin_f = (WmiNetUtilsHelper.GetMethodOrigin)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethodOrigin)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Get"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierGet_f = (WmiNetUtilsHelper.QualifierSet_Get)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Get)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Put"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierPut_f = (WmiNetUtilsHelper.QualifierSet_Put)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Put)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Delete"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierDelete_f = (WmiNetUtilsHelper.QualifierSet_Delete)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Delete)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_GetNames"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierGetNames_f = (WmiNetUtilsHelper.QualifierSet_GetNames)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_GetNames)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_BeginEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierBeginEnumeration_f = (WmiNetUtilsHelper.QualifierSet_BeginEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_BeginEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Next"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierNext_f = (WmiNetUtilsHelper.QualifierSet_Next)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Next)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_EndEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierEndEnumeration_f = (WmiNetUtilsHelper.QualifierSet_EndEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_EndEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetCurrentApartmentType"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetCurrentApartmentType_f = (WmiNetUtilsHelper.GetCurrentApartmentType)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetCurrentApartmentType)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetDemultiplexedStub"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetDemultiplexedStub_f = (WmiNetUtilsHelper.GetDemultiplexedStub)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetDemultiplexedStub)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CreateInstanceEnumWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CreateInstanceEnumWmi_f = (WmiNetUtilsHelper.CreateInstanceEnumWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CreateInstanceEnumWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CreateClassEnumWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CreateClassEnumWmi_f = (WmiNetUtilsHelper.CreateClassEnumWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CreateClassEnumWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ExecQueryWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ExecQueryWmi_f = (WmiNetUtilsHelper.ExecQueryWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ExecQueryWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ExecNotificationQueryWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ExecNotificationQueryWmi_f = (WmiNetUtilsHelper.ExecNotificationQueryWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ExecNotificationQueryWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutInstanceWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutInstanceWmi_f = (WmiNetUtilsHelper.PutInstanceWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutInstanceWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutClassWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutClassWmi_f = (WmiNetUtilsHelper.PutClassWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutClassWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CloneEnumWbemClassObject"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CloneEnumWbemClassObject_f = (WmiNetUtilsHelper.CloneEnumWbemClassObject)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CloneEnumWbemClassObject)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ConnectServerWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ConnectServerWmi_f = (WmiNetUtilsHelper.ConnectServerWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ConnectServerWmi)); } } } }
/// <summary> /// <para>Waits for the next event that matches the specified query to arrive, and /// then returns it.</para> /// </summary> /// <returns> /// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the /// newly arrived event.</para> /// </returns> /// <remarks> /// <para>If the event watcher object contains options with /// a specified timeout, the API will wait for the next event only for the specified /// amount of time; otherwise, the API will be blocked until the next event occurs.</para> /// </remarks> public ManagementBaseObject WaitForNextEvent() { ManagementBaseObject obj = null; Initialize(); #pragma warning disable CA2002 lock (this) #pragma warning restore CA2002 { SecurityHandler securityHandler = Scope.GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { if (null == enumWbem) //don't have an enumerator yet - get it { //Execute the query status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_( query.QueryLanguage, query.QueryString, options.Flags, options.GetContext(), ref enumWbem); } if (status >= 0) { if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { //Because Interop doesn't support custom marshalling for arrays, we have to use //the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded" //counterparts afterwards. IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize]; int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)options.Timeout.TotalMilliseconds; status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount); cacheIndex = 0; if (status >= 0) { //Convert results and put them in cache. Note that we may have timed out //in which case we might not have all the objects. If no object can be returned //we throw a timeout exception. if (cachedCount == 0) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); } for (int i = 0; i < cachedCount; i++) { cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i])); } } } if (status >= 0) { obj = new ManagementBaseObject(cachedObjects[cacheIndex]); cacheIndex++; } } } finally { securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } return(obj); }
// //IEnumerable methods // //**************************************** //GetEnumerator //**************************************** /// <summary> /// <para>Returns the enumerator for the collection. If the collection was retrieved from an operation that /// specified the EnumerationOptions.Rewindable = false only one iteration through this enumerator is allowed. /// Note that this applies to using the Count property of the collection as well since an iteration over the collection /// is required. Due to this, code using the Count property should never specify EnumerationOptions.Rewindable = false. /// </para> /// </summary> /// <returns> /// An <see cref='System.Collections.IEnumerator'/>that can be used to iterate through the /// collection. /// </returns> public ManagementObjectEnumerator GetEnumerator() { if (isDisposed) { throw new ObjectDisposedException(name); } // // We do not clone the enumerator if its the first enumerator. // If it is the first enumerator we pass the reference // to the enumerator implementation rather than a clone. If the enumerator is used // from within a foreach statement in the client code, the foreach statement will // dec the ref count on the reference which also happens to be the reference to the // original enumerator causing subsequent uses of the collection to fail. // To prevent this we always clone the enumerator (assuming its a rewindable enumerator) // to avoid invalidating the collection. // // If its a forward only enumerator we simply pass back the original enumerator (i.e. // not cloned) and if it gets disposed we end up throwing the next time its used. Essentially, // the enumerator becomes the collection. // // Unless this is the first enumerator, we have // to clone. This may throw if we are non-rewindable. if (this.options.Rewindable == true) { IEnumWbemClassObject enumWbemClone = null; int status = (int)ManagementStatus.NoError; try { status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Clone_(ref enumWbemClone); if ((status & 0x80000000) == 0) { //since the original enumerator might not be reset, we need //to reset the new one. status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone).Reset_(); } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return(new ManagementObjectEnumerator(this, enumWbemClone)); } else { // // Notice that we use the original enumerator and hence enum position is retained. // For example, if the client code manually walked half the collection and then // used a foreach statement, the foreach statement would continue from where the // manual walk ended. // return(new ManagementObjectEnumerator(this, enumWbem)); } }
internal string SetNamespacePath(string nsPath, out bool bChange) { int status = (int)ManagementStatus.NoError; string nsOrg = null; string nsNew = null; IWbemPath wmiPathTmp = null; bChange = false; Debug.Assert(nsPath != null); //Do some validation on the path to make sure it is a valid namespace path (at least syntactically) if (!IsValidNamespaceSyntax(nsPath)) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)tag_WBEMSTATUS.WBEM_E_INVALID_NAMESPACE); } wmiPathTmp = CreateWbemPath(nsPath); if (wmiPath == null) { wmiPath = this.CreateWbemPath(""); } else if (isWbemPathShared) { // Check if this IWbemPath is shared among multiple managed objects. // With this write, it will have to maintain its own copy. wmiPath = CreateWbemPath(this.GetWbemPath()); isWbemPathShared = false; } nsOrg = GetNamespacePath(wmiPath, (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY); nsNew = GetNamespacePath(wmiPathTmp, (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY); if (!string.Equals(nsOrg, nsNew, StringComparison.OrdinalIgnoreCase)) { wmiPath.RemoveAllNamespaces_(); // Out with the old... Ignore status code. // Add the new ones in bChange = true; // Now dirty from above. uint nCount = 0; status = wmiPathTmp.GetNamespaceCount_(out nCount); if (status >= 0) { for (uint i = 0; i < nCount; i++) { uint uLen = 0; status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, null); if (status >= 0) { char[] space = new char[(int)uLen]; status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, space); if (status >= 0) { status = wmiPath.SetNamespaceAt_(i, space); if (status < 0) { break; } } else { break; } } else { break; } } } } else { ; } // Continue on. Could have different server name, same ns specified. // // Update Server property if specified in the namespace. // eg: "\\MyServer\root\cimv2". // if (status >= 0 && nsPath.Length > 1 && (nsPath[0] == '\\' && nsPath[1] == '\\' || nsPath[0] == '/' && nsPath[1] == '/')) { uint uLen = 0; status = wmiPathTmp.GetServer_(ref uLen, null); if (status >= 0 && uLen > 0) { char[] newServerChars = new char[(int)uLen]; status = wmiPathTmp.GetServer_(ref uLen, newServerChars); string serverNew = new string(newServerChars, 0, Array.IndexOf(newServerChars, '\0')); if (status >= 0) { // Compare server name on this object, if specified, to the caller's. // Update this object if different or unspecified. uLen = 0; status = wmiPath.GetServer_(ref uLen, null); // NB: Cannot use property get since it may throw. if (status >= 0) { char[] orgServerChars = new char[(int)uLen]; status = wmiPath.GetServer_(ref uLen, orgServerChars); string serverOrg = new string(orgServerChars, 0, Array.IndexOf(orgServerChars, '\0')); if (status >= 0 && !string.Equals(serverOrg, serverNew, StringComparison.OrdinalIgnoreCase)) { status = wmiPath.SetServer_(serverNew); } } else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE) { status = wmiPath.SetServer_(serverNew); if (status >= 0) { bChange = true; } } } } else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE) // No caller-supplied server name; { status = (int)ManagementStatus.NoError; // Ignore error. } } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } return(nsNew); }
//**************************************** //MoveNext //**************************************** /// <summary> /// Indicates whether the enumerator has moved to /// the next object in the enumeration. /// </summary> /// <returns> /// <para><see langword='true'/>, if the enumerator was /// successfully advanced to the next element; <see langword='false'/> if the enumerator has /// passed the end of the collection.</para> /// </returns> public bool MoveNext() { if (isDisposed) { throw new ObjectDisposedException(name); } //If there are no more objects in the collection return false if (atEndOfCollection) { return(false); } //Look for the next object cacheIndex++; if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { //If the timeout is set to infinite, need to use the WMI infinite constant int timeout = (collectionObject.options.Timeout.Ticks == long.MaxValue) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)collectionObject.options.Timeout.TotalMilliseconds; //Get the next [BLockSize] objects within the specified timeout SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler(); //Because Interop doesn't support custom marshalling for arrays, we have to use //the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded" //counterparts afterwards. IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[collectionObject.options.BlockSize]; int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)collectionObject.options.BlockSize, tempArray, ref cachedCount); securityHandler.Reset(); if (status >= 0) { //Convert results and put them in cache. for (int i = 0; i < cachedCount; i++) { cachedObjects[i] = new IWbemClassObjectFreeThreaded ( Marshal.GetIUnknownForObject(tempArray[i]) ); } } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } else { //If there was a timeout and no object can be returned we throw a timeout exception... if ((status == (int)tag_WBEMSTATUS.WBEM_S_TIMEDOUT) && (cachedCount == 0)) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } //If not timeout and no objects were returned - we're at the end of the collection if ((status == (int)tag_WBEMSTATUS.WBEM_S_FALSE) && (cachedCount == 0)) { atEndOfCollection = true; cacheIndex--; //back to last object /* This call to Dispose is being removed as per discussion with URT people and the newly supported * Dispose() call in the foreach implementation itself. * * //Release the COM object (so that the user doesn't have to) * Dispose(); */ return(false); } } cacheIndex = 0; } return(true); }
public static bool IsNoContextMTA() { WmiNetUtilsHelper.APTTYPE aPTTYPE = WmiNetUtilsHelper.APTTYPE.APTTYPE_STA; bool flag; if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA) { if (MTAHelper.CanCallCoGetObjectContext) { IntPtr zero = IntPtr.Zero; IntPtr intPtr = IntPtr.Zero; try { if (MTAHelper.CoGetObjectContext(ref MTAHelper.IID_IComThreadingInfo, out zero) == 0) { if (WmiNetUtilsHelper.GetCurrentApartmentType_f(3, zero, out aPTTYPE) == 0) { if (aPTTYPE == WmiNetUtilsHelper.APTTYPE.APTTYPE_MTA) { if (Marshal.QueryInterface(zero, ref MTAHelper.IID_IObjectContext, out intPtr) != 0) { return(true); } else { flag = false; } } else { flag = false; } } else { flag = false; } } else { flag = false; } } finally { if (zero != IntPtr.Zero) { Marshal.Release(zero); } if (intPtr != IntPtr.Zero) { Marshal.Release(intPtr); } } return(flag); } else { return(true); } } else { return(false); } }
internal static int GetCurrentApartmentType(int vFunc, IntPtr pComThreadingInfo, out WmiNetUtilsHelper.APTTYPE aptType) { aptType = WmiNetUtilsHelper.APTTYPE.APTTYPE_CURRENT; return 0; }
}//Get() //******************************************** //Get() asynchronous //******************************************** /// <summary> /// <para>Invokes the WMI query, asynchronously, and binds to a watcher to deliver the results.</para> /// </summary> /// <param name='watcher'>The watcher that raises events triggered by the operation. </param> public void Get(ManagementOperationObserver watcher) { if (null == watcher) { throw new ArgumentNullException(nameof(watcher)); } Initialize(); IWbemServices wbemServices = scope.GetIWbemServices(); EnumerationOptions enumOptions = (EnumerationOptions)options.Clone(); // Ensure we switch off ReturnImmediately as this is invalid for async calls enumOptions.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) { enumOptions.SendStatus = true; } WmiEventSink sink = watcher.GetNewSink(scope, enumOptions.Context); SecurityHandler securityHandler = scope.GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { //If this is a simple SelectQuery (className only), and the enumerateDeep is set, we have //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/ //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration. if ((query.GetType() == typeof(SelectQuery)) && (((SelectQuery)query).Condition == null) && (((SelectQuery)query).SelectedProperties == null) && (options.EnumerateDeep == true)) { //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags not valid for enumerations are EnsureLocatable & PrototypeOnly. enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false; if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration { status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateInstanceEnumAsync_(((SelectQuery)query).ClassName, enumOptions.Flags, enumOptions.GetContext(), sink.Stub); } else { status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateClassEnumAsync_(((SelectQuery)query).ClassName, enumOptions.Flags, enumOptions.GetContext(), sink.Stub); } } else //we can use ExecQuery { //Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries enumOptions.EnumerateDeep = true; status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecQueryAsync_( query.QueryLanguage, query.QueryString, enumOptions.Flags, enumOptions.GetContext(), sink.Stub); } } catch (COMException e) { watcher.RemoveSink(sink); ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } }
//******************************************** //Get() //******************************************** /// <overload> /// Invokes the specified WMI query and returns the resulting collection. /// </overload> /// <summary> /// <para>Invokes the specified WMI query and returns the /// resulting collection.</para> /// </summary> /// <returns> /// <para>A <see cref='System.Management.ManagementObjectCollection'/> containing the objects that match the /// specified query.</para> /// </returns> public ManagementObjectCollection Get() { Initialize(); IEnumWbemClassObject ew = null; SecurityHandler securityHandler = scope.GetSecurityHandler(); EnumerationOptions enumOptions = (EnumerationOptions)options.Clone(); int status = (int)ManagementStatus.NoError; try { //If this is a simple SelectQuery (className only), and the enumerateDeep is set, we have //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/ //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration. if ((query.GetType() == typeof(SelectQuery)) && (((SelectQuery)query).Condition == null) && (((SelectQuery)query).SelectedProperties == null) && (options.EnumerateDeep == true)) { //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags not valid for enumerations are EnsureLocatable & PrototypeOnly. enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false; if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration { status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateInstanceEnum_( ((SelectQuery)query).ClassName, enumOptions.Flags, enumOptions.GetContext(), ref ew); } else //deep class enumeration { status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateClassEnum_(((SelectQuery)query).ClassName, enumOptions.Flags, enumOptions.GetContext(), ref ew); } } else //we can use ExecQuery { //Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries enumOptions.EnumerateDeep = true; status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQuery_( query.QueryLanguage, query.QueryString, enumOptions.Flags, enumOptions.GetContext(), ref ew); } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Create a new collection object for the results return(new ManagementObjectCollection(scope, options, ew)); }//Get()