/// <summary> /// Parses the ManagementException.ErrorInformation. /// </summary> /// <param name="ex"></param> /// <returns></returns> private static string GetExceptionText(ManagementException ex) { //get exception xml var exceptionxml = ex.ErrorInformation.GetText(System.Management.TextFormat.CimDtd20); var errormessage = ""; //parse exception var doc = XDocument.Parse(exceptionxml); var descriptionelement = doc.XPathSelectElements(".//PROPERTY[@NAME='Description']").FirstOrDefault(); if (descriptionelement != null) { var valueelement = descriptionelement.Element("VALUE"); if (valueelement != null) errormessage = valueelement.Value; } //if we have a description, use it if (errormessage != "") return errormessage; //otherwise, return the whole message var exceptiontext = ex.ErrorInformation.GetText(System.Management.TextFormat.Mof); return exceptiontext; }
public void CopyTo(Array array, int index) { if (array != null) { if (index < array.GetLowerBound(0) || index > array.GetUpperBound(0)) { throw new ArgumentOutOfRangeException("index"); } else { string[] strArrays = null; object obj = null; int num = 0; if (!this.isSystem) { num = num | 64; } else { num = num | 48; } //num = num; int names_ = this.parent.wbemObject.GetNames_(null, num, ref obj, out strArrays); if (names_ >= 0) { if (index + (int)strArrays.Length <= array.Length) { string[] strArrays1 = strArrays; for (int i = 0; i < (int)strArrays1.Length; i++) { string str = strArrays1[i]; int num1 = index; index = num1 + 1; array.SetValue(new PropertyData(this.parent, str), num1); } } else { throw new ArgumentException(null, "index"); } } if (names_ < 0) { if (((long)names_ & (long)-4096) != (long)-2147217408) { Marshal.ThrowExceptionForHR(names_); } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)names_); return; } } return; } } else { throw new ArgumentNullException("array"); } }
internal string SetNamespacePath(string nsPath, out bool bChange) { int errorCode = 0; string strA = null; string strB = null; IWbemPath wbemPath = null; bChange = false; if (!IsValidNamespaceSyntax(nsPath)) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.InvalidNamespace); } wbemPath = this.CreateWbemPath(nsPath); if (this.wmiPath == null) { this.wmiPath = this.CreateWbemPath(""); } else if (this.isWbemPathShared) { this.wmiPath = this.CreateWbemPath(this.GetWbemPath()); this.isWbemPathShared = false; } strA = GetNamespacePath(this.wmiPath, 0x10); strB = GetNamespacePath(wbemPath, 0x10); if (string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) != 0) { this.wmiPath.RemoveAllNamespaces_(); bChange = true; uint puCount = 0; errorCode = wbemPath.GetNamespaceCount_(out puCount); if (errorCode >= 0) { for (uint i = 0; i < puCount; i++) { uint puNameBufLength = 0; errorCode = wbemPath.GetNamespaceAt_(i, ref puNameBufLength, null); if (errorCode < 0) { break; } string pName = new string('0', ((int)puNameBufLength) - 1); errorCode = wbemPath.GetNamespaceAt_(i, ref puNameBufLength, pName); if (errorCode < 0) { break; } errorCode = this.wmiPath.SetNamespaceAt_(i, pName); if (errorCode < 0) { break; } } } } if (((errorCode >= 0) && (nsPath.Length > 1)) && (((nsPath[0] == '\\') && (nsPath[1] == '\\')) || ((nsPath[0] == '/') && (nsPath[1] == '/')))) { uint num5 = 0; errorCode = wbemPath.GetServer_(ref num5, null); if ((errorCode >= 0) && (num5 > 0)) { string str4 = new string('0', ((int)num5) - 1); errorCode = wbemPath.GetServer_(ref num5, str4); if (errorCode >= 0) { num5 = 0; errorCode = this.wmiPath.GetServer_(ref num5, null); if (errorCode >= 0) { string str5 = new string('0', ((int)num5) - 1); errorCode = this.wmiPath.GetServer_(ref num5, str5); if ((errorCode >= 0) && (string.Compare(str5, str4, StringComparison.OrdinalIgnoreCase) != 0)) { errorCode = this.wmiPath.SetServer_(str4); } } else if (errorCode == -2147217399) { errorCode = this.wmiPath.SetServer_(str4); if (errorCode >= 0) { bChange = true; } } } } else if (errorCode == -2147217399) { errorCode = 0; } } if (errorCode < 0) { if ((errorCode & 0xfffff000L) == 0x80041000L) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode); return(strB); } Marshal.ThrowExceptionForHR(errorCode); } return(strB); }
}//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("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); } }
internal void Initialize() { //If the path is not set yet we can't do it if (null == path) { throw new InvalidOperationException(); } /* * If we're not connected yet, this is the time to do it... We lock * the state to prevent 2 threads simultaneously doing the same * connection. To avoid taking the lock unnecessarily we examine * isConnected first */ if (!IsConnected) { lock (this) { if (!IsConnected) { IWbemLocator loc = (IWbemLocator) new WbemLocator(); if (null == options) { Options = new ConnectionOptions(); } string nsPath = path.NamespacePath; // If no namespace specified, fill in the default one if ((null == nsPath) || (0 == nsPath.Length)) { // NB: we use a special method to set the namespace // path here as we do NOT want to trigger an // IdentifierChanged event as a result of this set path.SetNamespacePath(ManagementPath.DefaultPath.Path); } // If we have privileges to enable, now is the time SecurityHandler securityHandler = GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { status = loc.ConnectServer_( path.NamespacePath, options.Username, options.GetPassword(), options.Locale, options.Flags, options.Authority, options.GetContext(), out wbemServices); //Set security on services pointer Secure(wbemServices); } catch (Exception e) { // BUGBUG : securityHandler.Reset()? ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } } } } }
/// <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); }
//**************************************** //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 void Reset() { int num; if (!this.isDisposed) { if (this.collectionObject.options.Rewindable) { SecurityHandler securityHandler = this.collectionObject.scope.GetSecurityHandler(); int num1 = 0; try { try { num1 = this.collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Reset_(); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ManagementException.ThrowWithExtendedInfo(cOMException); } } finally { securityHandler.Reset(); } if (((long)num1 & (long)-4096) != (long)-2147217408) { if (((long)num1 & (long)-2147483648) != (long)0) { Marshal.ThrowExceptionForHR(num1); } } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)num1); } if (this.cacheIndex >= 0) { num = this.cacheIndex; } else { num = 0; } for (int i = num; (long)i < (long)this.cachedCount; i++) { Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)Marshal.GetObjectForIUnknown(this.cachedObjects[i])); } this.cachedCount = 0; this.cacheIndex = -1; this.atEndOfCollection = false; return; } else { throw new InvalidOperationException(); } } else { throw new ObjectDisposedException(ManagementObjectCollection.ManagementObjectEnumerator.name); } }
public ManagementBaseObject WaitForNextEvent() { unsafe { int totalMilliseconds; ManagementBaseObject managementBaseObject = null; this.Initialize(); lock (this) { SecurityHandler securityHandler = this.Scope.GetSecurityHandler(); int num = 0; try { if (this.enumWbem == null) { num = this.scope.GetSecuredIWbemServicesHandler(this.Scope.GetIWbemServices()).ExecNotificationQuery_(this.query.QueryLanguage, this.query.QueryString, this.options.Flags, this.options.GetContext(), ref this.enumWbem); } if (num >= 0) { if (this.cachedCount - this.cacheIndex == 0) { IWbemClassObject_DoNotMarshal[] wbemClassObjectDoNotMarshalArray = new IWbemClassObject_DoNotMarshal[this.options.BlockSize]; if (ManagementOptions.InfiniteTimeout == this.options.Timeout) { totalMilliseconds = -1; } else { TimeSpan timeout = this.options.Timeout; totalMilliseconds = (int)timeout.TotalMilliseconds; } int num1 = totalMilliseconds; num = this.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Next_(num1, this.options.BlockSize, wbemClassObjectDoNotMarshalArray, ref this.cachedCount); this.cacheIndex = 0; if (num >= 0) { if (this.cachedCount == 0) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); } for (int i = 0; (long)i < (long)this.cachedCount; i++) { this.cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(wbemClassObjectDoNotMarshalArray[i].NativeObject)); } } } if (num >= 0) { ManagementEventWatcher managementEventWatcher = this; managementEventWatcher.cacheIndex = managementEventWatcher.cacheIndex + 1; } } } finally { securityHandler.Reset(); } if (num < 0) { if (((long)num & (long)-4096) != (long)-2147217408) { Marshal.ThrowExceptionForHR(num); } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)num); } } } return(managementBaseObject); } }
/// <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(); lock (this) { 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.GetIWbemServices().ExecNotificationQuery_( query.QueryLanguage, query.QueryString, options.Flags, options.GetContext(), out enumWbem); //Set security on enumerator if (status >= 0) { securityHandler.Secure(enumWbem); } } if (status >= 0) { if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { #if true //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 = enumWbem.Next_(timeout, (uint)options.BlockSize, tempArray, out 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... - TODO: what should happen if there was a timeout //but at least some objects were returned ?? if (cachedCount == 0) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); } for (int i = 0; i < cachedCount; i++) { cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i])); } } #else //This was workaround when using TLBIMP we couldn't pass in arrays... IWbemClassObjectFreeThreaded cachedObject = cachedObjects[0]; int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)options.Timeout.TotalMilliseconds; status = enumWbem.Next_(timeout, 1, out cachedObjects, out cachedCount); cacheIndex = 0; if (status >= 0) { //Create ManagementObject for result. Note that we may have timed out //in which case we won't have an object if (null == cachedObject) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); } cachedObjects[0] = cachedObject; } #endif } 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); } } } return(obj); }
//**************************************** //MoveNext //**************************************** /// <summary> /// Moves to the next object in the enumeration /// </summary> public bool MoveNext() { if (isDisposed) { throw new ObjectDisposedException("ManagementObjectEnumerator"); } //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 == Int64.MaxValue) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)collectionObject.options.Timeout.TotalMilliseconds; //Get the next [BLockSize] objects within the specified timeout // TODO - cannot use arrays of IWbemClassObject with a TLBIMP // generated wrapper SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler(); int status = (int)ManagementStatus.NoError; #if false status = enumWbem.Next(timeout, collectionObject.options.BlockSize, out cachedObjects, out cachedCount); #else IWbemClassObjectFreeThreaded obj = null; try { status = enumWbem.Next_(timeout, 1, out obj, out cachedCount); } catch (Exception e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } cachedObjects[0] = obj; #endif // BUGBUG : Review this //Check the return code - might be failure, timeout or WBEM_S_FALSE... if (status != 0) //not success { //If it's anything but WBEM_S_FALSE (which means end of collection) - we need to throw if (status != (int)tag_WBEMSTATUS.WBEM_S_FALSE) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } //if we got less objects than we wanted, need to check why... if (cachedCount < collectionObject.options.BlockSize) { //If no objects were returned we're at the very end if (cachedCount == 0) { atEndOfCollection = true; cacheIndex--; //back to last object //Release the COM object (so that the user doesn't have to) Dispose(); return(false); } } } cacheIndex = 0; securityHandler.Reset(); } else { //Advance the index to the next cacheIndex++; } return(true); }
public WMIException(ManagementException ex) : base(GetExceptionText(ex),ex) { }
//int statusFromMTA; void InitializeGuts(object o) { ManagementScope threadParam = (ManagementScope)o; IWbemLocator loc = (IWbemLocator) new WbemLocator(); if (null == options) { threadParam.Options = new ConnectionOptions(); } string nsPath = threadParam.prvpath.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); // If no namespace specified, fill in the default one if ((null == nsPath) || (0 == nsPath.Length)) { // NB: we use a special method to set the namespace // path here as we do NOT want to trigger an // IdentifierChanged event as a result of this set bool bUnused; nsPath = threadParam.prvpath.SetNamespacePath(ManagementPath.DefaultPath.Path, out bUnused); } // If we have privileges to enable, now is the time SecurityHandler securityHandler = GetSecurityHandler(); int status = (int)ManagementStatus.NoError; //If we're on XP or higher, always use the "max_wait" flag to avoid hanging if ((Environment.OSVersion.Platform == PlatformID.Win32NT) && (Environment.OSVersion.Version.Major >= 5) && (Environment.OSVersion.Version.Minor >= 1)) { threadParam.options.Flags |= (int)tag_WBEM_CONNECT_OPTIONS.WBEM_FLAG_CONNECT_USE_MAX_WAIT; } try { status = loc.ConnectServer_( nsPath, threadParam.options.Username, threadParam.options.GetPassword(), threadParam.options.Locale, threadParam.options.Flags, threadParam.options.Authority, threadParam.options.GetContext(), out threadParam.wbemServices); //Set security on services pointer GetSecurityHandler().Secure(threadParam.wbemServices); // // RAID: 127453 [marioh] // Make sure we enable RPC garbage collection to avoid tons // of useless idle connections not being recycled. This only // has impact on Win2k and below since XP has this enabled by // default. // if (rpcGarbageCollectionEnabled == false) { RpcMgmtEnableIdleCleanup( ); rpcGarbageCollectionEnabled = true; } Marshal.ReleaseComObject(loc); loc = null; } catch (Exception e) { // BUGBUG : securityHandler.Reset()? ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } //statusFromMTA = status; if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } }
public static bool HandleManagementException(ManagementException manex) { if ((manex.ErrorCode == ManagementStatus.InvalidObject) || (manex.ErrorCode == ManagementStatus.InvalidClass)) { return true; } return false; }
internal void SetNamespacePath(string nsPath) { int status = (int)ManagementStatus.NoError; ManagementPath newPath = new ManagementPath(nsPath); if (null == newPath.wmiPath) { newPath.wmiPath = (IWbemPath) new WbemDefPath(); } // Remove all existing namespaces from the current path if (null != wmiPath) { status = wmiPath.RemoveAllNamespaces_(); } else { wmiPath = (IWbemPath) new WbemDefPath(); } // Add the new ones in uint nCount = 0; status = newPath.wmiPath.GetNamespaceCount_(out nCount); if (status >= 0) { for (uint i = 0; i < nCount; i++) { uint uLen = 0; status = newPath.wmiPath.GetNamespaceAt_(i, ref uLen, null); if (status >= 0) { string nSpace = new String('0', (int)uLen - 1); status = newPath.wmiPath.GetNamespaceAt_(i, ref uLen, nSpace); if (status >= 0) { status = wmiPath.SetNamespaceAt_(i, nSpace); if (status < 0) { break; } } else { break; } } else { break; } } } // // Update Server property if specified in the namespace. // if (status >= 0 && nCount > 0) // Successfully set namespace. { uint bufLen = 0; status = newPath.wmiPath.GetServer_(ref bufLen, null); if (status >= 0 && bufLen > 0) { String server = new String('0', (int)bufLen - 1); status = newPath.wmiPath.GetServer_(ref bufLen, server); if (status >= 0) // Can't use property set since it will do a get. { status = wmiPath.SetServer_(server); } } } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else { Marshal.ThrowExceptionForHR(status); } } }
public bool MoveNext() { int totalMilliseconds; if (!this.isDisposed) { if (!this.atEndOfCollection) { ManagementObjectCollection.ManagementObjectEnumerator managementObjectEnumerator = this; managementObjectEnumerator.cacheIndex = managementObjectEnumerator.cacheIndex + 1; if ((long)this.cachedCount - (long)this.cacheIndex == (long)0) { TimeSpan timeout = this.collectionObject.options.Timeout; if (timeout.Ticks == 0x7fffffffffffffffL) { totalMilliseconds = -1; } else { TimeSpan timeSpan = this.collectionObject.options.Timeout; totalMilliseconds = (int)timeSpan.TotalMilliseconds; } int num = totalMilliseconds; SecurityHandler securityHandler = this.collectionObject.scope.GetSecurityHandler(); IWbemClassObject_DoNotMarshal[] wbemClassObjectDoNotMarshalArray = new IWbemClassObject_DoNotMarshal[this.collectionObject.options.BlockSize]; int num1 = this.collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Next_(num, this.collectionObject.options.BlockSize, wbemClassObjectDoNotMarshalArray, ref this.cachedCount); securityHandler.Reset(); if (num1 >= 0) { for (int i = 0; (long)i < (long)this.cachedCount; i++) { IntPtr ptr = Marshal.GetIUnknownForObject(wbemClassObjectDoNotMarshalArray[i].NativeObject); this.cachedObjects[i] = new IWbemClassObjectFreeThreaded(ptr); } } if (num1 >= 0) { if (num1 == 0x40004 && this.cachedCount == 0) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)num1); } if (num1 == 1 && this.cachedCount == 0) { this.atEndOfCollection = true; ManagementObjectCollection.ManagementObjectEnumerator managementObjectEnumerator1 = this; managementObjectEnumerator1.cacheIndex = managementObjectEnumerator1.cacheIndex - 1; return(false); } } else { if (((long)num1 & (long)-4096) != (long)-2147217408) { Marshal.ThrowExceptionForHR(num1); } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)num1); } } this.cacheIndex = 0; } return(true); } else { return(false); } } else { throw new ObjectDisposedException(ManagementObjectCollection.ManagementObjectEnumerator.name); } }
public void CopyTo(Array array, int index) { IWbemQualifierSetFreeThreaded typeQualifierSet; if (array != null) { if (index < array.GetLowerBound(0) || index > array.GetUpperBound(0)) { throw new ArgumentOutOfRangeException("index"); } else { string[] strArrays = null; try { typeQualifierSet = this.GetTypeQualifierSet(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (this.qualifierSetType != QualifierType.PropertyQualifier || managementException.ErrorCode != ManagementStatus.SystemProperty) { throw; } else { return; } } int names_ = typeQualifierSet.GetNames_(0, out strArrays); if (names_ < 0) { if (((long)names_ & (long)-4096) != (long)-2147217408) { Marshal.ThrowExceptionForHR(names_); } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)names_); } } if (index + (int)strArrays.Length <= array.Length) { string[] strArrays1 = strArrays; for (int i = 0; i < (int)strArrays1.Length; i++) { string str = strArrays1[i]; int num = index; index = num + 1; array.SetValue(new QualifierData(this.parent, this.propertyOrMethodName, str, this.qualifierSetType), num); } } else { throw new ArgumentException(null, "index"); } return; } } else { throw new ArgumentNullException("array"); } }
// //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)); } }
// 例外がスローされた時に出力に例外内容を表示 public void DispException(ManagementException manageExc) { string exceptionMsg = "エラーコード:" + manageExc.ErrorCode + "エラー内容:" + manageExc.Message + "エラー原因:" + manageExc.Source; Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.WriteLine(exceptionMsg); }
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) { string nSpace = new string('0', (int)uLen - 1); status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, nSpace); if (status >= 0) { status = wmiPath.SetNamespaceAt_(i, nSpace); 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) { string serverNew = new string ('0', (int)uLen - 1); status = wmiPathTmp.GetServer_(ref uLen, serverNew); 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) { string serverOrg = new string('0', (int)uLen - 1); status = wmiPath.GetServer_(ref uLen, serverOrg); 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); }
//******************************************** //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); } //Create a new collection object for the results return(new ManagementObjectCollection(scope, options, ew)); }//Get()
//****************************************************** //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); } }
/// <summary> /// <para>Waits until the next event that matches the specified query arrives, /// and returns it</para> /// </summary> /// <remarks> /// If the event watcher object contains /// options with a specified timeout, this API will wait for the next event only for /// the specified time. If not, the API will block until the next event occurs. /// </remarks> public ManagementBaseObject WaitForNextEvent() { Trace.WriteLine("Entering WaitForNextEvent..."); ManagementBaseObject obj = null; Initialize(); lock (this) { 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.GetIWbemServices().ExecNotificationQuery_( query.QueryLanguage, query.QueryString, options.Flags, options.GetContext(), out enumWbem); //Set security on enumerator if ((status & 0x80000000) == 0) { securityHandler.Secure(enumWbem); } } if ((status & 0x80000000) == 0) { if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { // TODO - due to TLBIMP restrictions IEnumWBemClassObject.Next will // not work with arrays - have to set count to 1 #if false enumWbem.Next((int)options.Timeout.TotalMilliseconds, (uint)options.BlockCount, out cachedObjects, out cachedCount); #else IWbemClassObjectFreeThreaded cachedObject = cachedObjects[0]; int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)options.Timeout.TotalMilliseconds; status = enumWbem.Next_(timeout, 1, out cachedObject, out cachedCount); cacheIndex = 0; if ((status & 0x80000000) == 0) { //Create ManagementObject for result. Note that we may have timed out //in which case we won't have an object if (null == cachedObject) { ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout); } cachedObjects[0] = cachedObject; } #endif } if ((status & 0x80000000) == 0) { obj = new ManagementBaseObject(cachedObjects[cacheIndex]); cacheIndex++; } } } catch (Exception e) { // BUGBUG : securityHandler.Reset()? if (e is ManagementException) { throw; //just let it propagate } ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); Trace.WriteLine("Returning from WaitForNextEvent..."); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } } return(obj); }