Example #1
0
        public ManagementBaseObject WaitForNextEvent()
        {
            ManagementBaseObject obj2 = null;

            this.Initialize();
            lock (this)
            {
                SecurityHandler securityHandler = this.Scope.GetSecurityHandler();
                int             errorCode       = 0;
                try
                {
                    if (this.enumWbem == null)
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(this.Scope.GetIWbemServices()).ExecNotificationQuery_(this.query.QueryLanguage, this.query.QueryString, this.options.Flags, this.options.GetContext(), ref this.enumWbem);
                    }
                    if (errorCode >= 0)
                    {
                        if ((this.cachedCount - this.cacheIndex) == 0)
                        {
                            IWbemClassObject_DoNotMarshal[] ppOutParams = new IWbemClassObject_DoNotMarshal[this.options.BlockSize];
                            int lTimeout = (ManagementOptions.InfiniteTimeout == this.options.Timeout) ? -1 : ((int)this.options.Timeout.TotalMilliseconds);
                            errorCode       = this.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Next_(lTimeout, (uint)this.options.BlockSize, ppOutParams, ref this.cachedCount);
                            this.cacheIndex = 0;
                            if (errorCode >= 0)
                            {
                                if (this.cachedCount == 0)
                                {
                                    ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout);
                                }
                                for (int i = 0; i < this.cachedCount; i++)
                                {
                                    this.cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(ppOutParams[i]));
                                }
                            }
                        }
                        if (errorCode >= 0)
                        {
                            obj2 = new ManagementBaseObject(this.cachedObjects[this.cacheIndex]);
                            this.cacheIndex++;
                        }
                    }
                }
                finally
                {
                    securityHandler.Reset();
                }
                if (errorCode >= 0)
                {
                    return(obj2);
                }
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                    return(obj2);
                }
                Marshal.ThrowExceptionForHR(errorCode);
            }
            return(obj2);
        }
Example #2
0
        public void Get(ManagementOperationObserver watcher)
        {
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            this.Initialize();
            IWbemServices      iWbemServices = this.scope.GetIWbemServices();
            EnumerationOptions options       = (EnumerationOptions)this.options.Clone();

            options.ReturnImmediately = false;
            if (watcher.HaveListenersForProgress)
            {
                options.SendStatus = true;
            }
            WmiEventSink    newSink         = watcher.GetNewSink(this.scope, options.Context);
            SecurityHandler securityHandler = this.scope.GetSecurityHandler();
            int             errorCode       = 0;

            try
            {
                if (((this.query.GetType() == typeof(SelectQuery)) && (((SelectQuery)this.query).Condition == null)) && ((((SelectQuery)this.query).SelectedProperties == null) && this.options.EnumerateDeep))
                {
                    options.EnsureLocatable = false;
                    options.PrototypeOnly   = false;
                    if (!((SelectQuery)this.query).IsSchemaQuery)
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).CreateInstanceEnumAsync_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), newSink.Stub);
                    }
                    else
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).CreateClassEnumAsync_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), newSink.Stub);
                    }
                }
                else
                {
                    options.EnumerateDeep = true;
                    errorCode             = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).ExecQueryAsync_(this.query.QueryLanguage, this.query.QueryString, options.Flags, options.GetContext(), newSink.Stub);
                }
            }
            catch (COMException exception)
            {
                watcher.RemoveSink(newSink);
                ManagementException.ThrowWithExtendedInfo(exception);
            }
            finally
            {
                securityHandler.Reset();
            }
            if ((errorCode & 0xfffff000L) == 0x80041000L)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
            }
            else if ((errorCode & 0x80000000L) != 0L)
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
        }
Example #3
0
        public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (watcher != null)
            {
                if (this.Path != null)
                {
                    this.Initialize(false);
                    if (options == null)
                    {
                        enumerationOption = new EnumerationOptions();
                    }
                    else
                    {
                        enumerationOption = (EnumerationOptions)options.Clone();
                    }
                    EnumerationOptions enumerationOption1 = enumerationOption;
                    enumerationOption1.EnsureLocatable   = false;
                    enumerationOption1.PrototypeOnly     = false;
                    enumerationOption1.ReturnImmediately = false;
                    if (watcher.HaveListenersForProgress)
                    {
                        enumerationOption1.SendStatus = true;
                    }
                    WmiEventSink    newSink         = watcher.GetNewSink(base.Scope, enumerationOption1.Context);
                    SecurityHandler securityHandler = base.Scope.GetSecurityHandler();
                    int             num             = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).CreateClassEnumAsync_(base.ClassName, enumerationOption1.Flags, enumerationOption1.GetContext(), newSink.Stub);
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                    if (num < 0)
                    {
                        watcher.RemoveSink(newSink);
                        if (((long)num & (long)-4096) != (long)-2147217408)
                        {
                            Marshal.ThrowExceptionForHR(num);
                        }
                        else
                        {
                            ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                            return;
                        }
                    }
                    return;
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
            else
            {
                throw new ArgumentNullException("watcher");
            }
        }
Example #4
0
        public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

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

            try
            {
                try
                {
                    if (!(this.query.GetType() == typeof(SelectQuery)) || ((SelectQuery)this.query).Condition != null || ((SelectQuery)this.query).SelectedProperties != null || !this.options.EnumerateDeep)
                    {
                        enumerationOption.EnumerateDeep = true;
                        num = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).ExecQuery_(this.query.QueryLanguage, this.query.QueryString, enumerationOption.Flags, enumerationOption.GetContext(), ref enumWbemClassObject);
                    }
                    else
                    {
                        enumerationOption.EnsureLocatable = false;
                        enumerationOption.PrototypeOnly   = false;
                        if (((SelectQuery)this.query).IsSchemaQuery)
                        {
                            num = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).CreateClassEnum_(((SelectQuery)this.query).ClassName, enumerationOption.Flags, enumerationOption.GetContext(), ref enumWbemClassObject);
                        }
                        else
                        {
                            num = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).CreateInstanceEnum_(((SelectQuery)this.query).ClassName, enumerationOption.Flags, enumerationOption.GetContext(), ref enumWbemClassObject);
                        }
                    }
                }
                catch (COMException cOMException1)
                {
                    COMException cOMException = cOMException1;
                    ManagementException.ThrowWithExtendedInfo(cOMException);
                }
            }
            finally
            {
                securityHandler.Reset();
            }
            if (((long)num & (long)-4096) != (long)-2147217408)
            {
                if (((long)num & (long)-2147483648) != (long)0)
                {
                    Marshal.ThrowExceptionForHR(num);
                }
            }
            else
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
            }
            return(new ManagementObjectCollection(this.scope, this.options, enumWbemClassObject));
        }
Example #6
0
 public bool MoveNext()
 {
     if (this.isDisposed)
     {
         throw new ObjectDisposedException(name);
     }
     if (this.atEndOfCollection)
     {
         return(false);
     }
     this.cacheIndex++;
     if ((this.cachedCount - this.cacheIndex) == 0L)
     {
         int             lTimeout                    = (this.collectionObject.options.Timeout.Ticks == 0x7fffffffffffffffL) ? -1 : ((int)this.collectionObject.options.Timeout.TotalMilliseconds);
         SecurityHandler securityHandler             = this.collectionObject.scope.GetSecurityHandler();
         IWbemClassObject_DoNotMarshal[] ppOutParams = new IWbemClassObject_DoNotMarshal[this.collectionObject.options.BlockSize];
         int errorCode = this.collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Next_(lTimeout, (uint)this.collectionObject.options.BlockSize, ppOutParams, ref this.cachedCount);
         securityHandler.Reset();
         if (errorCode >= 0)
         {
             for (int i = 0; i < this.cachedCount; i++)
             {
                 this.cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(ppOutParams[i]));
             }
         }
         if (errorCode < 0)
         {
             if ((errorCode & 0xfffff000L) == 0x80041000L)
             {
                 ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
             }
             else
             {
                 Marshal.ThrowExceptionForHR(errorCode);
             }
         }
         else
         {
             if ((errorCode == 0x40004) && (this.cachedCount == 0))
             {
                 ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
             }
             if ((errorCode == 1) && (this.cachedCount == 0))
             {
                 this.atEndOfCollection = true;
                 this.cacheIndex--;
                 return(false);
             }
         }
         this.cacheIndex = 0;
     }
     return(true);
 }
Example #7
0
            //****************************************
            //Reset
            //****************************************
            /// <summary>
            ///    <para>Resets the enumerator to the beginning of the collection.</para>
            /// </summary>
            public void Reset()
            {
                if (isDisposed)
                {
                    throw new ObjectDisposedException(name);
                }

                //If the collection is not rewindable you can't do this
                if (!collectionObject.options.Rewindable)
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    //Reset the WMI enumerator
                    SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler();
                    int             status          = (int)ManagementStatus.NoError;

                    try
                    {
                        status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Reset_();
                    }
                    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);
                    }

                    //Flush the current enumeration cache
                    for (int i = (cacheIndex >= 0 ? cacheIndex : 0); i < cachedCount; i++)
                    {
                        Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(cachedObjects[i])));
                    }

                    cachedCount       = 0;
                    cacheIndex        = -1;
                    atEndOfCollection = false;
                }
            }
        //********************************************
        //Start
        //********************************************
        /// <summary>
        ///    <para>Subscribes to events with the given query and delivers
        ///       them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
        /// </summary>
        public void Start()
        {
            Initialize();

            // Cancel any current event query
            Stop();

            // Submit a new query
            SecurityHandler securityHandler = Scope.GetSecurityHandler();
            IWbemServices   wbemServices    = scope.GetIWbemServices();

            try
            {
                sink = new SinkForEventQuery(this, options.Context, wbemServices);
                if (sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(sink.Status, WmiNetUtilsHelper.GetErrorInfo_f());
                }

                // For async event queries we should ensure 0 flags as this is
                // the only legal value
                int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(
                    query.QueryLanguage,
                    query.QueryString,
                    0,
                    options.GetContext(),
                    sink.Stub);


                if (status < 0)
                {
                    if (sink != null)
                    {
                        sink.ReleaseStub();
                        sink = null;
                    }

                    if ((status & 0xfffff000) == 0x80041000)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #9
0
        public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path != null)
            {
                this.Initialize(false);
                IEnumWbemClassObject enumWbemClassObject = null;
                if (options == null)
                {
                    enumerationOption = new EnumerationOptions();
                }
                else
                {
                    enumerationOption = (EnumerationOptions)options.Clone();
                }
                EnumerationOptions enumerationOption1 = enumerationOption;
                enumerationOption1.EnsureLocatable = false;
                enumerationOption1.PrototypeOnly   = false;
                SecurityHandler securityHandler = null;
                int             num             = 0;
                try
                {
                    securityHandler = base.Scope.GetSecurityHandler();
                    num             = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).CreateClassEnum_(base.ClassName, enumerationOption1.Flags, enumerationOption1.GetContext(), ref enumWbemClassObject);
                }
                finally
                {
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                }
                if (num < 0)
                {
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
                return(new ManagementObjectCollection(base.Scope, enumerationOption1, enumWbemClassObject));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Example #10
0
        public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
            {
                throw new InvalidOperationException();
            }
            else
            {
                this.Initialize(false);
                IEnumWbemClassObject enumWbemClassObject = null;
                if (options != null)
                {
                    enumerationOption = options;
                }
                else
                {
                    enumerationOption = new EnumerationOptions();
                }
                EnumerationOptions enumerationOption1 = enumerationOption;
                enumerationOption1.EnumerateDeep = true;
                RelationshipQuery relationshipQuery = new RelationshipQuery(true, this.Path.Path, relationshipClass, relationshipQualifier, thisRole);
                SecurityHandler   securityHandler   = null;
                int num = 0;
                try
                {
                    securityHandler = base.Scope.GetSecurityHandler();
                    num             = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(relationshipQuery.QueryLanguage, relationshipQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), ref enumWbemClassObject);
                }
                finally
                {
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                }
                if (num < 0)
                {
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
                return(new ManagementObjectCollection(base.Scope, enumerationOption1, enumWbemClassObject));
            }
        }
Example #11
0
        public ManagementObjectCollection Get()
        {
            this.Initialize();
            IEnumWbemClassObject ppEnum          = null;
            SecurityHandler      securityHandler = this.scope.GetSecurityHandler();
            EnumerationOptions   options         = (EnumerationOptions)this.options.Clone();
            int errorCode = 0;

            try
            {
                if (((this.query.GetType() == typeof(SelectQuery)) && (((SelectQuery)this.query).Condition == null)) && ((((SelectQuery)this.query).SelectedProperties == null) && this.options.EnumerateDeep))
                {
                    options.EnsureLocatable = false;
                    options.PrototypeOnly   = false;
                    if (!((SelectQuery)this.query).IsSchemaQuery)
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).CreateInstanceEnum_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), ref ppEnum);
                    }
                    else
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).CreateClassEnum_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), ref ppEnum);
                    }
                }
                else
                {
                    options.EnumerateDeep = true;
                    errorCode             = this.scope.GetSecuredIWbemServicesHandler(this.scope.GetIWbemServices()).ExecQuery_(this.query.QueryLanguage, this.query.QueryString, options.Flags, options.GetContext(), ref ppEnum);
                }
            }
            catch (COMException exception)
            {
                ManagementException.ThrowWithExtendedInfo(exception);
            }
            finally
            {
                securityHandler.Reset();
            }
            if ((errorCode & 0xfffff000L) == 0x80041000L)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
            }
            else if ((errorCode & 0x80000000L) != 0L)
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
            return(new ManagementObjectCollection(this.scope, this.options, ppEnum));
        }
        //********************************************
        //Start
        //********************************************
        /// <summary>
        ///    <para>Subscribes for events with the given query and delivers them asynchronously, through the EventArrived event.</para>
        /// </summary>
        public void Start()
        {
            Initialize();

            // Cancel any current event query
            Stop();

            SecurityHandler securityHandler = Scope.GetSecurityHandler();

            int status = (int)ManagementStatus.NoError;

            // Submit a new query
            try
            {
                IWbemServices wbemServices = scope.GetIWbemServices();
                sink = new SinkForEventQuery(this, options.GetContext(), wbemServices);

                // For async event queries we should ensure 0 flags as this is
                // the only legal value
                status = wbemServices.ExecNotificationQueryAsync_(
                    query.QueryLanguage,
                    query.QueryString,
                    0,
                    options.GetContext(),
                    sink.Stub);
            } catch (Exception e) {
                // BUGBUG : securityHandler.Reset()?
                if (sink != null)                               // BUGBUG : This looks dangerous
                {
                    sink.ReleaseStub();
                    sink = null;
                }
                ManagementException.ThrowWithExtendedInfo(e);
            } finally {
                securityHandler.Reset();
            }

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
            }
            else if ((status & 0x80000000) != 0)
            {
                Marshal.ThrowExceptionForHR(status);
            }
        }
Example #13
0
        public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options)
        {
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            if (this.Path == null)
            {
                throw new InvalidOperationException();
            }
            this.Initialize(false);
            EnumerationOptions options2 = (options == null) ? new EnumerationOptions() : ((EnumerationOptions)options.Clone());

            options2.EnsureLocatable   = false;
            options2.PrototypeOnly     = false;
            options2.ReturnImmediately = false;
            if (watcher.HaveListenersForProgress)
            {
                options2.SendStatus = true;
            }
            WmiEventSink    newSink         = watcher.GetNewSink(base.Scope, options2.Context);
            SecurityHandler securityHandler = null;
            int             errorCode       = 0;

            securityHandler = base.Scope.GetSecurityHandler();
            errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).CreateClassEnumAsync_(base.ClassName, options2.Flags, options2.GetContext(), newSink.Stub);
            if (securityHandler != null)
            {
                securityHandler.Reset();
            }
            if (errorCode < 0)
            {
                watcher.RemoveSink(newSink);
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
        }
Example #14
0
        public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            this.Initialize(true);
            EnumerationOptions options2 = (options != null) ? ((EnumerationOptions)options.Clone()) : new EnumerationOptions();

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

            securityHandler = base.Scope.GetSecurityHandler();
            errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), newSink.Stub);
            if (securityHandler != null)
            {
                securityHandler.Reset();
            }
            if (errorCode < 0)
            {
                watcher.RemoveSink(newSink);
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
        }
Example #15
0
            public void Reset()
            {
                if (this.isDisposed)
                {
                    throw new ObjectDisposedException(name);
                }
                if (!this.collectionObject.options.Rewindable)
                {
                    throw new InvalidOperationException();
                }
                SecurityHandler securityHandler = this.collectionObject.scope.GetSecurityHandler();
                int             errorCode       = 0;

                try
                {
                    errorCode = this.collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Reset_();
                }
                catch (COMException exception)
                {
                    ManagementException.ThrowWithExtendedInfo(exception);
                }
                finally
                {
                    securityHandler.Reset();
                }
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else if ((errorCode & 0x80000000L) != 0L)
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
                for (int i = (this.cacheIndex >= 0) ? this.cacheIndex : 0; i < this.cachedCount; i++)
                {
                    Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)Marshal.GetObjectForIUnknown((IntPtr)this.cachedObjects[i]));
                }
                this.cachedCount       = 0;
                this.cacheIndex        = -1;
                this.atEndOfCollection = false;
            }
Example #16
0
        public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            this.Initialize(false);
            IEnumWbemClassObject ppEnum   = null;
            EnumerationOptions   options2 = (options != null) ? options : new EnumerationOptions();

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

            try
            {
                securityHandler = base.Scope.GetSecurityHandler();
                errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), ref ppEnum);
            }
            finally
            {
                if (securityHandler != null)
                {
                    securityHandler.Reset();
                }
            }
            if (errorCode < 0)
            {
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
            return(new ManagementObjectCollection(base.Scope, options2, ppEnum));
        }
Example #17
0
        public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
        {
            if (this.Path == null)
            {
                throw new InvalidOperationException();
            }
            this.Initialize(false);
            IEnumWbemClassObject ppEnum   = null;
            EnumerationOptions   options2 = (options == null) ? new EnumerationOptions() : ((EnumerationOptions)options.Clone());

            options2.EnsureLocatable = false;
            options2.PrototypeOnly   = false;
            SecurityHandler securityHandler = null;
            int             errorCode       = 0;

            try
            {
                securityHandler = base.Scope.GetSecurityHandler();
                errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).CreateClassEnum_(base.ClassName, options2.Flags, options2.GetContext(), ref ppEnum);
            }
            finally
            {
                if (securityHandler != null)
                {
                    securityHandler.Reset();
                }
            }
            if (errorCode < 0)
            {
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
            return(new ManagementObjectCollection(base.Scope, options2, ppEnum));
        }
Example #18
0
        public void Start()
        {
            this.Initialize();
            this.Stop();
            SecurityHandler securityHandler = this.Scope.GetSecurityHandler();
            IWbemServices   wbemServices    = this.scope.GetIWbemServices();

            try
            {
                this.sink = new SinkForEventQuery(this, this.options.Context, wbemServices);
                if (this.sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(this.sink.Status);
                }
                int num = this.scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(this.query.QueryLanguage, this.query.QueryString, 0, this.options.GetContext(), this.sink.Stub);
                if (num < 0)
                {
                    if (this.sink != null)
                    {
                        this.sink.ReleaseStub();
                        this.sink = null;
                    }
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #19
0
        public void Start()
        {
            this.Initialize();
            this.Stop();
            SecurityHandler securityHandler = this.Scope.GetSecurityHandler();
            IWbemServices   iWbemServices   = this.scope.GetIWbemServices();

            try
            {
                this.sink = new SinkForEventQuery(this, this.options.Context, iWbemServices);
                if (this.sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(this.sink.Status);
                }
                int errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).ExecNotificationQueryAsync_(this.query.QueryLanguage, this.query.QueryString, 0, this.options.GetContext(), this.sink.Stub);
                if (errorCode < 0)
                {
                    if (this.sink != null)
                    {
                        this.sink.ReleaseStub();
                        this.sink = null;
                    }
                    if ((errorCode & 0xfffff000L) == 0x80041000L)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(errorCode);
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #20
0
            //****************************************
            //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);
            }
        /// <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);
        }
Example #22
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());
            }
        }
Example #23
0
        //********************************************
        //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()
            //****************************************
            //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);
                }
            }
        /// <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);
        }
Example #27
0
 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);
     }
 }
Example #28
0
        //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 void Get(ManagementOperationObserver watcher)
 {
     if (watcher != null)
     {
         this.Initialize();
         IWbemServices      wbemServices      = this.scope.GetIWbemServices();
         EnumerationOptions enumerationOption = (EnumerationOptions)this.options.Clone();
         enumerationOption.ReturnImmediately = false;
         if (watcher.HaveListenersForProgress)
         {
             enumerationOption.SendStatus = true;
         }
         WmiEventSink    newSink         = watcher.GetNewSink(this.scope, enumerationOption.Context);
         SecurityHandler securityHandler = this.scope.GetSecurityHandler();
         int             num             = 0;
         try
         {
             try
             {
                 if (!(this.query.GetType() == typeof(SelectQuery)) || ((SelectQuery)this.query).Condition != null || ((SelectQuery)this.query).SelectedProperties != null || !this.options.EnumerateDeep)
                 {
                     enumerationOption.EnumerateDeep = true;
                     num = this.scope.GetSecuredIWbemServicesHandler(wbemServices).ExecQueryAsync_(this.query.QueryLanguage, this.query.QueryString, enumerationOption.Flags, enumerationOption.GetContext(), newSink.Stub);
                 }
                 else
                 {
                     enumerationOption.EnsureLocatable = false;
                     enumerationOption.PrototypeOnly   = false;
                     if (((SelectQuery)this.query).IsSchemaQuery)
                     {
                         num = this.scope.GetSecuredIWbemServicesHandler(wbemServices).CreateClassEnumAsync_(((SelectQuery)this.query).ClassName, enumerationOption.Flags, enumerationOption.GetContext(), newSink.Stub);
                     }
                     else
                     {
                         num = this.scope.GetSecuredIWbemServicesHandler(wbemServices).CreateInstanceEnumAsync_(((SelectQuery)this.query).ClassName, enumerationOption.Flags, enumerationOption.GetContext(), newSink.Stub);
                     }
                 }
             }
             catch (COMException cOMException1)
             {
                 COMException cOMException = cOMException1;
                 watcher.RemoveSink(newSink);
                 ManagementException.ThrowWithExtendedInfo(cOMException);
             }
         }
         finally
         {
             securityHandler.Reset();
         }
         if (((long)num & (long)-4096) != (long)-2147217408)
         {
             if (((long)num & (long)-2147483648) != (long)0)
             {
                 Marshal.ThrowExceptionForHR(num);
             }
             return;
         }
         else
         {
             ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
             return;
         }
     }
     else
     {
         throw new ArgumentNullException("watcher");
     }
 }
            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);
                }
            }