Beispiel #1
0
		protected WmiEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, string path, string className)
		{
			try
			{
				this.context = context;
				this.watcher = watcher;
				this.className = className;
				this.isLocal = false;
				if (path != null)
				{
					this.path = new ManagementPath(path);
					if (string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(this.path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
					{
						this.isLocal = true;
					}
				}
				if (scope != null)
				{
					this.scope = scope.Clone();
					if (path == null && (string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(this.scope.Path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0))
					{
						this.isLocal = true;
					}
				}
				WmiNetUtilsHelper.GetDemultiplexedStub_f(this, this.isLocal, out this.stub);
				this.hash = Interlocked.Increment(ref WmiEventSink.s_hash);
			}
			catch
			{
			}
		}
Beispiel #2
0
 public UsbDeviceEvent()
 {
     this.creationEventWatcher = (ManagementEventWatcher)null;
     ManagementOperationObserver operationObserver = new ManagementOperationObserver();
     ManagementScope scope = new ManagementScope("root\\CIMV2");
     scope.Options.EnablePrivileges = true;
     try
     {
         WqlEventQuery wqlEventQuery = new WqlEventQuery();
         wqlEventQuery.EventClassName = "__InstanceCreationEvent";
         wqlEventQuery.WithinInterval = new TimeSpan(0, 0, 3);
         wqlEventQuery.Condition = "TargetInstance ISA 'Win32_USBControllerDevice'";
         Console.WriteLine(wqlEventQuery.QueryString);
         this.creationEventWatcher = new ManagementEventWatcher(scope, (EventQuery)wqlEventQuery);
         this.creationEventWatcher.EventArrived += new EventArrivedEventHandler(this.creationEventWatcher_EventArrived);
         this.creationEventWatcher.Start();
         wqlEventQuery.EventClassName = "__InstanceDeletionEvent";
         wqlEventQuery.WithinInterval = new TimeSpan(0, 0, 3);
         wqlEventQuery.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
         Console.WriteLine(wqlEventQuery.QueryString);
         this.deletionEventWatcher = new ManagementEventWatcher(scope, (EventQuery)wqlEventQuery);
         this.deletionEventWatcher.EventArrived += new EventArrivedEventHandler(this.deletionEventWatcher_EventArrived);
         this.deletionEventWatcher.Start();
     }
     catch
     {
         this.Dispose();
     }
 }
Beispiel #3
0
        private void findPorts()
        {
            try
            {
                comboBox_Ports.Items.Clear();
                serialItems.Items.Clear();

                ManagementObjectSearcher searcher = new ManagementObjectSearcher( new SelectQuery("WIN32_SerialPort"));
                ManagementOperationObserver results = new ManagementOperationObserver();
                results.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
                results.Completed += new CompletedEventHandler(this.Done);

                // Get availble port names asynchronously
                searcher.Get(results);

                while (!this.Completed)
                {
                    System.Threading.Thread.Sleep(1000);
                }
                this.Reset();

            }
            catch (ManagementException e)
            {
                MessageBox.Show("Failed to run query: " + e.Message);
                throw;
            }

            foreach (object port in serialItems.Items)
            {
                comboBox_Ports.Items.Add(port);
            }
        }
Beispiel #4
0
 /// <summary>
 /// Internal Constructor
 /// </summary>
 /// <param name="childJob">Job associated with this operation</param>
 /// <param name="wmiObject">object associated with this operation</param>
 /// <param name="computerName"> computer on which the operation is invoked </param>
 /// <param name="results"> sink to get wmi objects </param>
 internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results)
 {
     _wmiObject = wmiObject;
     _computerName = computerName;
     _results = results;
     this.State = WmiState.NotStarted;
     _job = childJob;
 }
Beispiel #5
0
        /// <summary>Creates a new process</summary>>
        /// <param name="commandLine">Command line to execute</param>
        /// <param name="currentDirectory">Current drive and directory for the child process</param>
        /// <param name="processStartupInformation">The startup configuration of a Windows process</param>
        /// <param name="processId">Global process identifier that can be used to identify a process</param>
        public void Create(string commandLine, string currentDirectory, Win32_ProcessStartup processStartupInformation,ref uint processId)
        {
            object[] methodArgs = { commandLine, currentDirectory, processStartupInformation, processId };
            ManagementOperationObserver observer = new ManagementOperationObserver();

            this._mc.InvokeMethod(observer, "Create", methodArgs);
            processId = Convert.ToUInt32(methodArgs[3]);
        }
Beispiel #6
0
 public void GetRelationships(ManagementOperationObserver watcher,
                              string relationshipClass,
                              string relationshipQualifier,
                              string thisRole,
                              bool classDefinitionsOnly,
                              EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #7
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");
                }
            }
        }
Beispiel #8
0
        public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (watcher != null)
            {
                if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    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()).CreateInstanceEnumAsync_(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 ArgumentNullException("watcher");
            }
        }
 /// <summary>
 /// Kills the process.
 /// </summary>
 /// <param name="machineName">Name of the machine.</param>
 /// <param name="serviceObj">The service obj.</param>
 /// <param name="observer">The observer.</param>
 public static void KillProcess(string machineName, ManagementObject serviceObj, ManagementOperationObserver observer)
 {
     string str = String.Empty;
     foreach (var prop in serviceObj.Properties)
     {
         str += String.Format("{0} - {1}\r\n", prop.Name, prop.Value);
     }
     var processObj = GetProcess(machineName, serviceObj["ProcessId"].ToString());
     processObj.InvokeMethod(observer, "Terminate", null);
 }
 internal static WmiGetEventSink GetWmiGetEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, ManagementObject managementObject)
 {
     if (MTAHelper.IsNoContextMTA())
     {
         return new WmiGetEventSink(watcher, context, scope, managementObject);
     }
     watcherParameter = watcher;
     contextParameter = context;
     scopeParameter = scope;
     managementObjectParameter = managementObject;
     new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(WmiGetEventSink.HackToCreateWmiGetEventSink)).Start();
     return wmiGetEventSinkNew;
 }
Beispiel #11
0
 internal static WmiGetEventSink GetWmiGetEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, ManagementObject managementObject)
 {
     if (MTAHelper.IsNoContextMTA())
     {
         return(new WmiGetEventSink(watcher, context, scope, managementObject));
     }
     watcherParameter          = watcher;
     contextParameter          = context;
     scopeParameter            = scope;
     managementObjectParameter = managementObject;
     new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(WmiGetEventSink.HackToCreateWmiGetEventSink)).Start();
     return(wmiGetEventSinkNew);
 }
 internal static WmiEventSink GetWmiEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, string path, string className)
 {
     if (MTAHelper.IsNoContextMTA())
     {
         return new WmiEventSink(watcher, context, scope, path, className);
     }
     watcherParameter = watcher;
     contextParameter = context;
     scopeParameter = scope;
     pathParameter = path;
     classNameParameter = className;
     new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(WmiEventSink.HackToCreateWmiEventSink)).Start();
     return wmiEventSinkNew;
 }
Beispiel #13
0
 internal static WmiEventSink GetWmiEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, string path, string className)
 {
     if (MTAHelper.IsNoContextMTA())
     {
         return(new WmiEventSink(watcher, context, scope, path, className));
     }
     watcherParameter   = watcher;
     contextParameter   = context;
     scopeParameter     = scope;
     pathParameter      = path;
     classNameParameter = className;
     new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(WmiEventSink.HackToCreateWmiEventSink)).Start();
     return(wmiEventSinkNew);
 }
Beispiel #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);
                }
            }
        }
Beispiel #15
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);
                }
            }
        }
Beispiel #16
0
		private IObservable<ManagementBaseObject> Factory(ManagementClass mc)
		{
			var src = new ReplaySubject<ManagementBaseObject>();
			var ob = new ManagementOperationObserver();

			Observable.FromEventPattern<ObjectReadyEventHandler, ObjectReadyEventArgs>(
				h => h.Invoke,
				h => ob.ObjectReady += h,
				h => ob.ObjectReady -= h
			).Subscribe(obj => src.OnNext(obj.EventArgs.NewObject));

			Observable.FromEventPattern<CompletedEventHandler, CompletedEventArgs>(
				h => h.Invoke,
				h => ob.Completed += h,
				h => ob.Completed -= h
			).Subscribe(_ => src.OnCompleted());

			mc.GetInstances(ob);
			return src.AsObservable();
		}
Beispiel #17
0
        protected WmiEventSink(ManagementOperationObserver watcher,
                               object context,
                               ManagementScope scope,
                               string path,
                               string className)
        {
            try
            {
                this.context   = context;
                this.watcher   = watcher;
                this.className = className;
                this.isLocal   = false;

                if (null != path)
                {
                    this.path = new ManagementPath(path);
                    if ((0 == string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
                        (0 == string.Compare(this.path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
                    {
                        this.isLocal = true;
                    }
                }

                if (null != scope)
                {
                    this.scope = (ManagementScope)scope.Clone();
                    if (null == path) // use scope to see if sink is local
                    {
                        if ((0 == string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
                            (0 == string.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
                        {
                            this.isLocal = true;
                        }
                    }
                }

                WmiNetUtilsHelper.GetDemultiplexedStub_f(this, this.isLocal, out stub);
                hash = Threading.Interlocked.Increment(ref s_hash);
            }
            catch { }
        }
Beispiel #18
0
		internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager) : base(null, null)
		{
			this.syncObject = new object();
			this.statusMessage = "test";
			base.UsesResultsCollection = true;
			this.computerName = computerName;
			this.throttleManager = throttleManager;
			this.wmiSinkArray = new ArrayList();
			ManagementOperationObserver managementOperationObserver = new ManagementOperationObserver();
			this.wmiSinkArray.Add(managementOperationObserver);
			PSWmiChildJob pSWmiChildJob = this;
			pSWmiChildJob.sinkCompleted = pSWmiChildJob.sinkCompleted + 1;
			managementOperationObserver.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
			managementOperationObserver.Completed += new CompletedEventHandler(this.JobDone);
			this.helper = new WmiAsyncCmdletHelper(this, cmds, computerName, managementOperationObserver);
			this.helper.WmiOperationState += new EventHandler<WmiJobStateEventArgs>(this.HandleWMIState);
			this.helper.ShutdownComplete += new EventHandler<EventArgs>(this.JobDoneForWin32Shutdown);
			base.SetJobState(JobState.NotStarted);
			IThrottleOperation throttleOperation = this.helper;
			throttleOperation.OperationComplete += new EventHandler<OperationStateEventArgs>(this.HandleOperationComplete);
			throttleManager.ThrottleComplete += new EventHandler<EventArgs>(this.HandleThrottleComplete);
			throttleManager.AddOperation(throttleOperation);
		}
Beispiel #19
0
        protected override void OnStart(string[] args)
        {
            WMIEvent we = new WMIEvent();
            ManagementEventWatcher w = null;
            WqlEventQuery q;
            ManagementOperationObserver observer = new
            ManagementOperationObserver();
            // Bind to local machine
            ManagementScope scope = new ManagementScope("root\\CIMV2");
            scope.Options.EnablePrivileges = true; //sets required

            try {
                q = new WqlEventQuery();
                q.EventClassName = "__InstanceOperationEvent";
                q.WithinInterval = new TimeSpan(0, 0, 3);
                q.Condition = @
                "TargetInstance ISA 'Win32_DiskDrive' ";
                //EventLog es una forma de escribir lo que está pasando en
                //el visor de sucesos de windows
                EventLog.WriteEntry(q.QueryString);
                w = new ManagementEventWatcher(q);
                w.EventArrived += new
                EventArrivedEventHandler(we.UsbEventArrived);
                w.Start();

            } catch (Exception e) {
                EventLog.WriteEntry(e.Message);
            }
        }
		public void Put (ManagementOperationObserver watcher, PutOptions options)
		{
			throw new NotImplementedException ();
		}
		public void InvokeMethod (ManagementOperationObserver watcher, string methodName, object [] args)
		{
			throw new NotImplementedException ();
		}
		public void GetRelationships (ManagementOperationObserver watcher, string relationshipClass)
		{
			throw new NotImplementedException ();
		}
		public void Delete (ManagementOperationObserver watcher, DeleteOptions options)
		{
			throw new NotImplementedException ();
		}
 public void Get(ManagementOperationObserver watcher)
 {
     throw new NotImplementedException();
 }
Beispiel #25
0
 public void GetRelationshipClasses(ManagementOperationObserver watcher)
 {
     this.GetRelationshipClasses(watcher, null);
 }
Beispiel #26
0
 public void CopyTo(ManagementOperationObserver watcher, string path, PutOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #27
0
 public void CopyTo(ManagementOperationObserver watcher, ManagementPath path)
 {
     throw new NotImplementedException();
 }
Beispiel #28
0
 void OnEventLogEntryCompleted(object sender, CompletedEventArgs e)
 {
     _eventMessagesObserver = null;
 }
Beispiel #29
0
        private void GetEventLogItemMessages(string machinename, string logname)
        {
            if (_eventMessagesObserver == null)
            {
                ManagementScope messageScope = new ManagementScope(
                             GetStandardPath(machinename)
                 );

                messageScope.Connect();

                StringBuilder query = new StringBuilder();
                query.Append("select Message, InsertionStrings, RecordNumber from Win32_NTLogEvent where LogFile ='");
                query.Append(logname.Replace("'", "''"));
                query.Append("'");

                System.Management.ObjectQuery objectQuery = new System.Management.ObjectQuery(
                    query.ToString()
                );

                EnumerationOptions objectQueryOptions = new EnumerationOptions();
                objectQueryOptions.BlockSize = 100000;

                ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(messageScope, objectQuery);

                _eventMessagesObserver = new ManagementOperationObserver();
                _eventMessagesObserver.ObjectReady += new ObjectReadyEventHandler(OnEventLogEntryReady);
                _eventMessagesObserver.Completed += new CompletedEventHandler(OnEventLogEntryCompleted);
                objectSearcher.Get(_eventMessagesObserver);
            }
        }
Beispiel #30
0
 private WmiGetEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, ManagementObject managementObject) : base(watcher, context, scope, null, null)
 {
     this.managementObject = managementObject;
 }
Beispiel #31
0
 public void GetSubclasses(ManagementOperationObserver watcher)
 {
     this.GetSubclasses(watcher, null);
 }
Beispiel #32
0
 public void Delete(ManagementOperationObserver watcher, DeleteOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #33
0
        /// <summary>
        /// List view context menu click event to invoke terminate process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemTerminate_Click(object sender, System.EventArgs e)
        {
            ManagementObjectCollection queryCollection;
            ListViewItem lvItem;

            //Set up a handler for the asynchronous callback
            ManagementOperationObserver observer = new ManagementOperationObserver();
            completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler();
            observer.ObjectReady  += new ObjectReadyEventHandler(completionHandlerObj.Done);

            queryCollection = getProcessCollection("Select * from Win32_Process Where ProcessID = '" + ProcessID + "'");

            //Status
            updateStatus("Invoking terminate process");

            foreach ( ManagementObject mo in queryCollection)
            {
                //start or stop service
                mo.InvokeMethod(observer, "Terminate", null);
            }

            //wait until invoke method is complete or 5 sec timeout
            int intCount = 0;
            while (!completionHandlerObj.IsComplete)
            {
                if (intCount == 10)
                {
                    MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
                    break;
                }
                //wait 1/2 sec.
                System.Threading.Thread.Sleep(500);

                //increment counter
                intCount++;
            }

            if (intCount != 10)
            {
                //InvokeMethod did not time out
                if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
                {
                    lvItem = ProcessItem;
                    lvItem.Remove();
                }
                else
                {
                    MessageBox.Show("Error terminating process.", "Terminate Process");
                }
            }
            //clean-up objects
            ProcessID = "";
            ProcessItem = null;

            //Status
            updateStatus("Ready");
            this.Update();
        }
Beispiel #34
0
 /// <summary>
 /// Internal Constructor.  This variant takes a count parameter that determines how many times 
 /// the WMI command is executed.
 /// </summary>
 /// <param name="childJob">Job associated with this operation</param>
 /// <param name="wmiObject">Object associated with this operation</param>
 /// <param name="computerName">Computer on which the operation is invoked</param>
 /// <param name="results">Sink to return wmi objects</param>
 /// <param name="count">Number of times the WMI command is executed</param>
 internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results, int count)
     : this(childJob, wmiObject, computerName, results)
 {
     _cmdCount = count;
 }
Beispiel #35
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());
            }
        }
Beispiel #36
0
 internal ManagementOperationObserver GetNewSink()
 {
     ManagementOperationObserver wmiSink = new ManagementOperationObserver();
     _wmiSinkArray.Add(wmiSink);
     lock (_syncObject)
     {
         _sinkCompleted++;
     }
     wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
     wmiSink.Completed += new CompletedEventHandler(this.JobDone);
     return wmiSink;
 }
		public void CopyTo (ManagementOperationObserver watcher, string path, PutOptions options)
		{
			throw new NotImplementedException ();
		}
Beispiel #38
0
 public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
		public void GetRelated (ManagementOperationObserver watcher)
		{
			throw new NotImplementedException ();
		}
Beispiel #40
0
 public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
		public void GetRelationships (ManagementOperationObserver watcher,
					      string relationshipClass,
					      string relationshipQualifier,
					      string thisRole,
					      bool classDefinitionsOnly,
					      EnumerationOptions options)
		{
			throw new NotImplementedException ();
		}
 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);
     }
 }
		public void InvokeMethod (ManagementOperationObserver watcher,
					  string methodName,
					  ManagementBaseObject inParameters,
					  InvokeMethodOptions options)
		{
			throw new NotImplementedException ();
		}
Beispiel #44
0
 public void GetInstances(ManagementOperationObserver watcher)
 {
     this.GetInstances(watcher, null);
 }
		public void CopyTo (ManagementOperationObserver watcher, ManagementPath path)
		{
			throw new NotImplementedException ();
		}
Beispiel #46
0
        /// <summary>
        /// Get processes and populate list view
        /// </summary>
        private void getProcess()
        {
            ManagementObjectCollection queryCollection;
            ManagementObjectCollection queryCollection1;
            ProcessesDictionary.ProcessesDictionary  processesDictionary = new ProcessesDictionary.ProcessesDictionary();
            ProcessesDictionary.ProcessesInfo processInfo;
            ProcessesDictionary.structProcessInfo structProcess;
            ProcessesPerformanceDictionary.Dictionary dictionaryPerformances = new ProcessesPerformanceDictionary.Dictionary();
            ProcessesPerformanceDictionary.structPerformance structProcessPerf;
            ProcessesPerformanceDictionary.ProcessPerf processPerformance;

            //Set up a handler for the asynchronous callback
            ManagementOperationObserver observer = new ManagementOperationObserver();
            completionHandler.MyHandler  completionHandlerObj = new completionHandler.MyHandler();
            observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done);

            string[] lvData =  new string[5];

            //Status
            updateStatus("Getting Services Information");

            //prevent listview update
            listViewProcesses.BeginUpdate();

            try
            {
                //get system processes collection
                queryCollection = getProcessCollection("SELECT * FROM Win32_Process");

                //create dictionary for processes
                foreach ( ManagementObject mo in queryCollection)
                {
                    processInfo = new ProcessesDictionary.ProcessesInfo();
                    structProcess = new ProcessesDictionary.structProcessInfo();

                    structProcess.stringName = mo["Name"].ToString();
                    structProcess.stringProcessID = mo["ProcessID"].ToString();
                    structProcess.stringParentProcessID = mo["ParentProcessID"].ToString();

                    //Status
                    updateStatus("Getting " + structProcess.stringName + " process info...");

                    //Get process owner info
                    mo.InvokeMethod(observer,"GetOwner", null);

                    //wait until call is complete
                    while (!completionHandlerObj.IsComplete)
                    {
                        System.Threading.Thread.Sleep(500);
                    }

                    //check if the call was successful
                    if (completionHandlerObj.ReturnObject["returnValue"].ToString() == "0")
                        //get process user name
                        structProcess.stringUserName = completionHandlerObj.ReturnObject.Properties["User"].Value.ToString();
                    else
                        //failed
                        structProcess.stringUserName = "";

                    processInfo.Value = structProcess;

                    processesDictionary.Add(mo["ProcessID"].ToString(), processInfo);
                }

                //get operating system
                string stringOS = "";
                int intWinXP = 0;

                queryCollection = getProcessCollection("SELECT * FROM Win32_OperatingSystem");
                foreach(ManagementObject mo in queryCollection)
                {
                    //look for Windows 2000 Operating system
                    stringOS = mo["Caption"].ToString();
                    intWinXP = stringOS.LastIndexOf("XP");
                }

                if (intWinXP >= 0)
                {
                    //get process CPU and memory usage for XP machine
                    //(Note: have problem calling this on 2000 and NT machine.)
                    queryCollection1 = getProcessCollection("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");
                }
                else
                {
                    //get process CPU and memory usage for 2000 and NT machine
                    queryCollection1 = getProcessCollection("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
                }

                foreach ( ManagementObject mo1 in queryCollection1)
                {
                    //get process CPU and memory usage
                    processPerformance = new ProcessesPerformanceDictionary.ProcessPerf();
                    structProcessPerf = new ProcessesPerformanceDictionary.structPerformance();

                    structProcessPerf.stringPercentProcessorTime = mo1.Properties["PercentProcessorTime"].Value.ToString();
                    structProcessPerf.stringVirtualBytes = mo1["VirtualBytes"].ToString();

                    processPerformance.Value = structProcessPerf;

                    //add to dictionary
                    dictionaryPerformances.Add(mo1["IDProcess"].ToString(), processPerformance);

                    //cleanup
                    processPerformance = null;
                }

                //populate listview
                foreach (string stringProcessID in processesDictionary)
                {
                    //currentProcessInfo = processesDictionary[stringProcessID].Value;
                    structProcess = processesDictionary[stringProcessID].Value;
                    //create child node for operating system
                    lvData[0] = structProcess.stringName.ToString();
                    //get process id
                    lvData[4] = structProcess.stringProcessID.ToString();

                    //get parent process
                    lvData[1] = structProcess.stringUserName.ToString();

                    try
                    {
                        //get process % processor time
                        lvData[2] = dictionaryPerformances[structProcess.stringProcessID.ToString()].Value.stringPercentProcessorTime.ToString();

                        //get memory usage
                        lvData[3] = dictionaryPerformances[structProcess.stringProcessID.ToString()].Value.stringVirtualBytes.ToString();
                    }
                    catch(NullReferenceException)
                    {
                        //can't find process performance data
                        lvData[2] = "0";
                        lvData[3] = "0";
                    }

                    //create list item
                    ListViewItem lvItem = new ListViewItem(lvData,0);
                    listViewProcesses.Items.Add(lvItem);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error: " + e);
            }

            //do some cleanup
            processesDictionary.Clear();
            processesDictionary = null;
            dictionaryPerformances.Clear();
            dictionaryPerformances = null;

            //update listview
            listViewProcesses.EndUpdate();

            //Status
            updateStatus("Ready");
            this.Update();
        }
Beispiel #47
0
        void SetupDriveWatcher()
        {
            try
            {
                ManagementEventWatcher w = null;
                WqlEventQuery q;
                ManagementOperationObserver observer = new ManagementOperationObserver();
                // Bind to local machine
                ManagementScope scope = new ManagementScope("root\\CIMV2");
                scope.Options.EnablePrivileges = true; //sets required privilege

                q = new WqlEventQuery();
                q.EventClassName = "__InstanceOperationEvent";
                q.WithinInterval = new TimeSpan(0, 0, 3);
                q.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";

                //Console.WriteLine(q.QueryString);
                w = new ManagementEventWatcher(scope, q);

                w.EventArrived += new EventArrivedEventHandler(UsbEventArrived);
                w.Start();
                // Console.ReadLine(); // block main thread for test purposes
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #48
0
 public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass)
 {
     this.GetRelationshipClasses(watcher, relationshipClass, null, null, null);
 }
Beispiel #49
0
 /// <summary>
 /// Internal constructor for initializing WMI jobs, where WMI command is executed a variable
 /// number of times.
 /// </summary>
 internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager, int count)
     : base(null, null)
 {
     UsesResultsCollection = true;
     Location = computerName;
     _throttleManager = throttleManager;
     _wmiSinkArray = new ArrayList();
     ManagementOperationObserver wmiSink = new ManagementOperationObserver();
     _wmiSinkArray.Add(wmiSink);
     _sinkCompleted += count;
     wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
     wmiSink.Completed += new CompletedEventHandler(this.JobDone);
     _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count);
     _helper.WmiOperationState += new EventHandler<WmiJobStateEventArgs>(HandleWMIState);
     _helper.ShutdownComplete += new EventHandler<EventArgs>(JobDoneForWin32Shutdown);
     SetJobState(JobState.NotStarted);
     IThrottleOperation operation = _helper;
     operation.OperationComplete += new EventHandler<OperationStateEventArgs>(HandleOperationComplete);
     throttleManager.ThrottleComplete += new EventHandler<EventArgs>(HandleThrottleComplete);
     throttleManager.AddOperation(operation);
 }
Beispiel #50
0
        /// <summary>
        /// Invoke method 'Create' on local or remote machine
        /// </summary>
        /// <param name="stringCommandLine"></param>
        private void CreateProcess(string stringCommandLine)
        {
            //Set up a handler for the asynchronous callback
            ManagementOperationObserver observer = new ManagementOperationObserver();
            completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler();
            observer.ObjectReady  += new ObjectReadyEventHandler(completionHandlerObj.Done);

            string stringMachineName = "";

            //Connect to the remote computer
            ConnectionOptions co = new ConnectionOptions();

            if (radioMachine.Checked == true)
            {
                stringMachineName = "localhost";
            }
            else
            {
                stringMachineName = textIP.Text;
            }

            if (stringMachineName.Trim().Length == 0)
            {
                MessageBox.Show("Must enter machine IP address or name.");
                return;
            }

            //get user and password
            if (textUserID.Text.Trim().Length   > 0)
            {
                co.Username = textUserID.Text;
                co.Password = textPassword.Text;
            }

            //Point to machine
            System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2", co);
            //get process path
            ManagementPath path = new ManagementPath( "Win32_Process");

            //Get the object on which the method will be invoked
            ManagementClass processClass = new ManagementClass(ms,path,null);

            //Status
            updateStatus("Create process " + stringCommandLine + ".");

            //Create an array containing all arguments for the method
            object[] methodArgs = {stringCommandLine, null, null, 0};

            //Execute the method
            processClass.InvokeMethod (observer, "Create", methodArgs);

            //wait until invoke method is complete or 5 sec timeout
            int intCount = 0;
            while (!completionHandlerObj.IsComplete)
            {
                if (intCount > 10)
                {
                    MessageBox.Show("Create process timed out.", "Terminate Process Status");
                    break;
                }
                //wait 1/2 sec.
                System.Threading.Thread.Sleep(500);

                //increment counter
                intCount++;
            }

            if (intCount != 10)
            {
                //InvokeMethod did not time out
                //check for error
                if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
                {
                    //refresh process list
                    this.Refresh();
                }
                else
                {
                    MessageBox.Show("Error creating new process.", "Create New Process");
                }
            }

            //Status
            updateStatus("Ready");
            this.Update();
        }
Beispiel #51
0
 public void GetRelationships(ManagementOperationObserver watcher, string relationshipClass)
 {
     throw new NotImplementedException();
 }
Beispiel #52
0
 public void Put(ManagementOperationObserver watcher, PutOptions options)
 {
     throw new NotImplementedException();
 }
 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");
     }
 }
Beispiel #54
0
 public void InvokeMethod(ManagementOperationObserver watcher, string methodName, object [] args)
 {
     throw new NotImplementedException();
 }