internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results)
 {
     this.cmdCount     = 1;
     this.wmiObject    = wmiObject;
     this.computerName = computerName;
     this.results      = results;
     this.State        = WmiState.NotStarted;
     this.Job          = childJob;
 }
示例#2
0
        private static IObservable <ManagementBaseObject> observableFactory(ManagementClass mc)
        {
            var ob = new ManagementOperationObserver();

            return(Observable.FromEventPattern <ObjectReadyEventHandler, ObjectReadyEventArgs>(
                       h => { ob.ObjectReady += h; mc.GetInstances(ob); }, h => ob.ObjectReady -= h
                       ).TakeUntil(Observable.FromEventPattern <CompletedEventHandler, CompletedEventArgs>(
                                       h => ob.Completed += h, h => ob.Completed -= h
                                       )).Select(e => e.EventArgs.NewObject));
        }
示例#3
0
        /// <summary>
        /// 使用Wmi获取指定进程的创建者等信息
        /// </summary>
        /// <param name="pID">进程ID</param>
        private void FillDetailUseWmi(int pID)
        {
            ManagementObjectSearcher   searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ProcessID=" + pID);
            ManagementObjectCollection moc      = searcher.Get();

            ManagementOperationObserver observer = new ManagementOperationObserver();
            HandleObjectReady           hor      = new HandleObjectReady();

            //监测异步方法是否已成功返回
            observer.ObjectReady += new ObjectReadyEventHandler(hor.Done);

            foreach (ManagementObject mo in moc)
            {
                //异步调用该对象的GetOwner方法,获取进程创建者
                mo.InvokeMethod(observer, "GetOwner", null);
                //等待异步调用返回
                while (!hor.Complete)
                {
                    System.Threading.Thread.Sleep(500);
                }

                string user = "";
                //判断获取用户名的操作是否成功
                if (hor.Obj["returnValue"].ToString() == "0")
                {
                    user = hor.Obj.Properties["User"].Value.ToString();
                }
                //判断字典中是否已移除该项
                if (!this.mDict.ContainsKey(pID))
                {
                    return;
                }
                if (mo["ParentProcessID"] != null && this.mDict.ContainsKey(Convert.ToInt32(mo["ParentProcessID"])))
                {
                    //根据父进程ID获取父进程名称
                    this.mDict[pID].ParentProce = this.mDict[Convert.ToInt32(mo["ParentProcessID"])].ProceName;
                }
                this.mDict[pID].Creator = user;

                //触发刷新进程详细信息事件
                if (this.HandleDetailList != null)
                {
                    this.HandleDetailList(this.mDict[pID]);
                }
            }

            //释放资源
            searcher.Dispose();
            searcher = null;
            moc.Dispose();
            moc      = null;
            observer = null;
            hor      = null;
        }
示例#4
0
        private void GetWmiInstances(ManagementScope scope, ManagementPath path, string condition)
        {
            scope.Options.Authentication = AuthenticationLevel.Default;
            scope.Options.Impersonation  = ImpersonationLevel.Impersonate;
            var observer = new ManagementOperationObserver();

            observer.ObjectReady += InstanceObserver_Ready;
            var searcher = new ManagementObjectSearcher(scope, new SelectQuery(path.ClassName, condition));

            searcher.Get(observer);
        }
示例#5
0
        private void GetWmiMetaClasses(ManagementScope scope, string condition)
        {
            scope.Options.Authentication = AuthenticationLevel.Default;
            scope.Options.Impersonation  = ImpersonationLevel.Impersonate;
            var observer = new ManagementOperationObserver();

            observer.ObjectReady += MetaClassObserver_Ready;
            var searcher = new ManagementObjectSearcher(scope, new SelectQuery("meta_class", condition));

            searcher.Get(observer);
        }
示例#6
0
  }//public static void InvokeMethodParameterObjectsAsynchronous()
    	  	
  ///<summary>InvokeMethodParameterObjectsAsynchronous</summary>
  ///<param name="processParameter">processParameter</param>
  ///<param name="exceptionMessage">exceptionMessage</param>
  public static void InvokeMethodParameterObjectsAsynchronous
  (
   ref  String  processParameter,
   ref  String  exceptionMessage
  )
  { 
  
   ManagementClass              managementClass               =  null;
   ManagementBaseObject         managementBaseObjectParamIn   =  null;
   ManagementOperationObserver  managementOperationObserver   =  null;
   ObjectReadyHandler           objectReadyHandler            =  null;
   
   //Get the object on which the method will be invoked
   managementClass = new ManagementClass("Win32_Process");

   // Create a results and completion handler
   managementOperationObserver  =  new ManagementOperationObserver();
   objectReadyHandler           =  new ObjectReadyHandler();
   managementOperationObserver.ObjectReady += new ObjectReadyEventHandler
   (
    objectReadyHandler.NewObject
   );

   //Get an input parameters object for this method
   managementBaseObjectParamIn = managementClass.GetMethodParameters("Create");

   //Fill in input parameter values
   managementBaseObjectParamIn["CommandLine"] = processParameter;

   //Execute the method
   managementClass.InvokeMethod
   (
    managementOperationObserver,
    "Create",
    managementBaseObjectParamIn,
    null
   );

   //Do something while method is executing
   while( !objectReadyHandler.IsComplete ) 
   {
    System.Threading.Thread.Sleep( ThreadSleep );
   }

   //After execution is completed, display results
   //Note: The return code of the method is provided in the "returnValue" property of the outParams object
   System.Console.WriteLine
   (
    "Process Name: {0} | Return: {1} | Process Id: {2}",
    processParameter,    
    objectReadyHandler.ManagementBaseObjectResult["returnValue"],
    objectReadyHandler.ManagementBaseObjectResult["processId"]
   );
  }//public static void InvokeMethodParameterObjectsAsynchronous
示例#7
0
        public Task <IEnumerable <PropertyDataCollection> > CollectAsync()
        {
            var tcs     = new TaskCompletionSource <IEnumerable <PropertyDataCollection> >();
            var watcher = new ManagementOperationObserver();
            var results = new List <PropertyDataCollection>();

            var readyHandler = new ObjectReadyEventHandler((sender, e) =>
            {
                results.Add(e.NewObject.Properties);
            });

            // The event handler that gets invoked by the watcher.
            var completedHandler = default(CompletedEventHandler);

            completedHandler = new CompletedEventHandler((sender, e) =>
            {
                var tcsLocal = tcs;
                try
                {
                    if (e.Status == ManagementStatus.NoError)
                    {
                        // The operation was completed without any errors.
                        tcsLocal.SetResult(results);
                        return;
                    }

                    if (e.Status == ManagementStatus.CallCanceled || e.Status == ManagementStatus.OperationCanceled)
                    {
                        // The task was cancelled before it could be completed.
                        tcsLocal.SetCanceled();
                        return;
                    }

                    // An exception occurred during the operation.
                    tcsLocal.SetException(new Exception($"Runtime error {e.Status}"));
                    return;
                }
                finally
                {
                    // Clean up the event handlers.
                    watcher.Completed -= completedHandler;
                }
            });

            // Wire up the event handler and begin the operation.
            watcher.ObjectReady += readyHandler;
            watcher.Completed   += completedHandler;
            var management = new ManagementClass("Win32_LogicalDisk");

            management.GetInstances(watcher);

            return(tcs.Task);
        }
示例#8
0
        /*-----------------------------------------------------------------------*/
        #endregion


        #region Monitoring
        /*-----------------------------------------------------------------------*/
        /// <summary>Starts the monitoring of device.</summary>
        /// <param name="path"></param>
        /// <param name="mediaEvent"></param>
        public void Monitor(string path, MediaEvent mediaEvent)
        {
            if (null == mediaEvent)
            {
                throw new ArgumentException("Media event cannot be null!");
            }

            //In case same class was called make sure only one instance is running
            /////////////////////////////////////////////////////////////
            Exit();

            //Keep logica drive to check
            /////////////////////////////////////////////////////////////
            _mLogicalDrive = GetLogicalDrive(path);

            var observer = new
                           ManagementOperationObserver();

            //Bind to local machine
            /////////////////////////////////////////////////////////////
            var opt = new ConnectionOptions {
                EnablePrivileges = true
            };

            //Sets required privilege
            /////////////////////////////////////////////////////////////
            var scope = new ManagementScope("root\\CIMV2", opt);

            try
            {
                var wql = new WqlEventQuery
                {
                    EventClassName = "__InstanceModificationEvent",
                    WithinInterval = new TimeSpan(0, 0, 1),
                    Condition      =
                        String.Format(
                            @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DeviceId = '{0}'",
                            _mLogicalDrive)
                };

                _mManagementEventWatcher = new ManagementEventWatcher(scope, wql);

                //Register async. event handler
                /////////////////////////////////////////////////////////////
                _mManagementEventWatcher.EventArrived += mediaEvent.MediaEventArrived;
                _mManagementEventWatcher.Start();
            }
            catch (Exception e)
            {
                Exit();
                throw new Exception("Media Check: " + e.Message);
            }
        }
示例#9
0
        public bool Format(ManagementOperationObserver watcher, DriveManager.FileSystem FileSystem = DriveManager.FileSystem.FAT32, bool quickFormat = true, uint clusterSize = 4096, string label = "", bool enableCompression = false)
        {
            var fileSystem = FileSystem.ToString();

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(DefaultSearchQuery))
            {
                foreach (ManagementObject vi in searcher.Get())
                {
                    vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
                }
            }

            return(true);
        }
示例#10
0
        internal ManagementOperationObserver GetNewSink()
        {
            ManagementOperationObserver managementOperationObserver = new ManagementOperationObserver();

            this.wmiSinkArray.Add(managementOperationObserver);
            lock (this.syncObject)
            {
                PSWmiChildJob pSWmiChildJob = this;
                pSWmiChildJob.sinkCompleted = pSWmiChildJob.sinkCompleted + 1;
            }
            managementOperationObserver.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
            managementOperationObserver.Completed   += new CompletedEventHandler(this.JobDone);
            return(managementOperationObserver);
        }
示例#11
0
 private void Start()
 {
     if (SelectedService != null && !SelectedService.IsRunning)
     {
         Task.Factory.StartNew(() =>
         {
             var observer        = new ManagementOperationObserver();
             observer.Completed += RaiseRefreshApps;
             Operations.StartService(SelectedService.ManagementObj, observer);
         })
         .ContinueWith(t => DisplayMessage(t.Exception.ToString()), TaskContinuationOptions.OnlyOnFaulted)
         .ContinueWith(t => Refresh());
     }
 }
示例#12
0
        public static bool InvokeWMIServiceMethod(string serviceAction, string sServiceName)
        {
            bool bInvokeMethodStatus = false;

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

                //get specific service object
                ManagementObjectCollection queryCollection = GetServiceCollection(sServiceName);

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

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

                    //increment counter
                    intCount++;
                }

                //see if call was successful.
                if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
                {
                    bInvokeMethodStatus = true;
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("ServiceManagerWindowsWrapper.InvokeWMIServiceMethod()", ex);
            }

            return(bInvokeMethodStatus);
        }
示例#13
0
 private void Kill()
 {
     if (SelectedService != null)
     {
         Task.Factory.StartNew(() =>
         {
             string machineName  = GetServerName(SelectedService);
             var observer        = new ManagementOperationObserver();
             observer.Completed += RaiseRefreshApps;
             Operations.KillProcess(machineName, SelectedService.ManagementObj, observer);
         })
         .ContinueWith(t => DisplayMessage(t.Exception.ToString()), TaskContinuationOptions.OnlyOnFaulted)
         .ContinueWith(t => Refresh());
     }
 }
示例#14
0
        /// <summary>
        /// Deletes out of date temp files
        /// </summary>
        /// <param name="sDataPath">application data path</param>
        /// <param name="extensions">temp files extensions string array</param>
        /// <param name="days">number of days ILC would keep temp files</param>
        /// <returns>true in case of success</returns>
        public static bool Clean(string sDataPath, string[] extensions, int days)
        {
            ILog log = GetLogger();

            log.Info("LogCleaner: attempt to clean \"ApplicationDataPath\" directory.");

            if (days < 0)
            {
                log.Info(
                    "LogCleaner: Key \"KeepTempFilesDays\" is not set in the config file. \"ApplicationDataPath\" directory will not be cleaned.");
                return(false);
            }

            string query = GetQuery(sDataPath, extensions, days);

            if (string.IsNullOrEmpty(query))
            {
                return(false);
            }

            log.Info("LogCleaner: query string is " + query + ".");

            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
                {
                    // Create a results watcher object,
                    // and handler for results and completion
                    ManagementOperationObserver results = new
                                                          ManagementOperationObserver();

                    // Attach handler to events for results and completion
                    results.ObjectReady += NewObject;
                    results.Completed   += Done;

                    // Call the asynchronous overload of Get()
                    // to start the enumeration
                    searcher.Get(results);

                    return(true);
                }
            }
            catch (ManagementException e)
            {
                log.Error("LogCleaner: Exception occurred while WMI working.", e);
                return(false);
            }
        }
    public static void Main(string[] args)
    {
        Monitor m = new Monitor();
        ManagementOperationObserver ob = new ManagementOperationObserver();

        ob.Completed   += new CompletedEventHandler(m.OnCompleted);
        ob.ObjectReady += new ObjectReadyEventHandler(m.OnObjectReady);
        ManagementClass mc = new ManagementClass("Win32_Process");

        mc.GetInstances(ob);
        while (!m.IsComplete)
        {
            // do something while waiting
            System.Threading.Thread.Sleep(1000);
        }
    }
    public static void Main(string[] args)
    {
        Monitor mo = new Monitor();
        ManagementOperationObserver ob = new ManagementOperationObserver();

        ob.Completed   += new CompletedEventHandler(mo.OnCompleted);
        ob.ObjectReady += new ObjectReadyEventHandler(mo.OnObjectReady);
        ManagementObjectSearcher ms = new ManagementObjectSearcher(
            "SELECT * FROM Win32_Process");

        ms.Get(ob);
        while (!mo.Completed)
        {
            System.Threading.Thread.Sleep(1000);
        }
    }
示例#17
0
        // Does the async version of the enumeration in a synchronous way (apparently the usual sync version blocks things weirdly)
        public void EnumerateInstances(string queryString, ObjectReadyEventHandler myObserver)
        {
            AutoResetEvent finished = new AutoResetEvent(false);

            ManagementObjectSearcher    searcher = new ManagementObjectSearcher("root\\CIMV2", queryString);
            ManagementOperationObserver observer = new ManagementOperationObserver();

            observer.ObjectReady += myObserver;
            observer.Completed   += (sender, obj) => // CompletedEventHandler(object sender, CompletedEventArgs obj)
            {
                finished.Set();
            };
            searcher.Get(observer);      // Asynchronous
            finished.WaitOne();
            return;
        }
示例#18
0
        /// <summary>
        /// Execute a scalar query and get back the management base objects
        /// </summary>
        /// <param name="QueryString">The query to execute</param>
        /// <returns>Management base object</returns>
        public Task <ManagementBaseObject> ExecuteScalar(string QueryString)
        {
            var tsc = new TaskCompletionSource <ManagementBaseObject>();

            using (var searcher = new ManagementObjectSearcher(QueryString))
            {
                ManagementOperationObserver results = new ManagementOperationObserver();

                results.ObjectReady += (s, e) => {
                    tsc.SetResult(e.NewObject);
                };

                searcher.Get(results);

                return(tsc.Task);
            }
        }
示例#19
0
        static void Main()
        {
            ManagementObjectSearcher processorSearcher = new ManagementObjectSearcher(
                "SELECT Name, CurrentClockSpeed FROM Win32_Processor");

            ManagementOperationObserver observer = new ManagementOperationObserver();
            CallBackClass callBackObject         = new CallBackClass();

            observer.Completed += new
                                  CompletedEventHandler(callBackObject.OnAllProcessors);
            observer.ObjectReady += new
                                    ObjectReadyEventHandler(callBackObject.OnNextProcessor);

            processorSearcher.Get(observer);
            Console.WriteLine("Retrieving processors. Hit any key to terminate");
            Console.ReadLine();
        }
示例#20
0
        private async Task InvokeMethod(string method)
        {
            IsInvoking = true;
            var MOO = new ManagementOperationObserver();

            MOO.Completed += (sender, e) => { IsInvoking = false; };
            WMRObject.InvokeMethod(MOO, method, null);
            while (IsInvoking)
            {
                await Task.Delay(500);
            }
            await Task.Delay(1000);

            WMRObject.Get();
            IsEnabled = ErrorCode != 22;
            OnStateChanged();
        }
示例#21
0
    public static void Main(string[] args)
    {
        Monitor m = new Monitor();
        ManagementOperationObserver ob = new ManagementOperationObserver();

        ob.Completed += new CompletedEventHandler(m.OnCompleted);
        ob.ObjectPut += new ObjectPutEventHandler(m.OnObjectPut);
        ManagementObject mo = new ManagementObject("Win32_WMISetting=@");

        mo["BackupInterval"] = 120;
        mo.Put(ob);
        while (!m.IsComplete)
        {
            // do something while waiting
            System.Threading.Thread.Sleep(1000);
        }
    }
示例#22
0
        /// <summary>
        /// Simple Asynchronous Query without any parsing.
        /// </summary>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <List <ManagementBaseObject> > QueryAsync(ObjectQuery query, CancellationToken cancellationToken = default(CancellationToken))
        {
            //TODO: Create an queryasync with action callback instead so that we can convert data while it streams in.
            var result  = new List <ManagementBaseObject>();
            var tsc     = new TaskCompletionSource <List <ManagementBaseObject> >();
            var watcher = new ManagementOperationObserver();

            // setting up the watcher event handlers

            //Add data input handler.
            watcher.ObjectReady += (sender, args) =>
            {
                // basic cancellation support. Doesn't handle network timeouts (aka you have to wait...)
                if (cancellationToken.IsCancellationRequested)
                {
                    tsc.TrySetCanceled(cancellationToken);
                }

                // try to gracefully handle possible exceptions in parser code.
                try
                {
                    result.Add(args.NewObject);
                }
                catch (Exception e)
                {
                    tsc.SetException(e);
                }
            };

            //Add data completed handler.
            watcher.Completed += (obj, e) =>
            {
                //TODO: handle e.Status??
                tsc.TrySetResult(result);
            };

            // Create a searcher using our scope.
            using (var searcher = new ManagementObjectSearcher(this.Scope, query))
            {
                // start doing work async.
                searcher.Get(watcher);

                return(await tsc.Task);
            }
        }
示例#23
0
        public MainForm()
        {
            queryObserver              = new ManagementOperationObserver();
            queryObserver.ObjectReady += queryObserver_ObjectReady;
            queryObserver.Completed   += queryObserver_Completed;

            InitializeComponent();

            var rect = Screen.FromControl(this).WorkingArea;

            Size = new Size(rect.Width * 3 / 4, rect.Height * 3 / 4);

            scopeTree.Sorted       = true;
            scopeTree.Nodes[0].Tag = new ScopeCache();

            classList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            memberList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
示例#24
0
        /// <summary>
        /// Retrieve a list of running processes on a remote machine
        /// </summary>
        /// <param name="strMachineName">Machine name to query</param>
        /// <param name="strDomainName">Machine domain name</param>
        /// <param name="strUserName">Username</param>
        /// <param name="strPassword">User password</param>
        /// <param name="strError">Error string containing any Error message encountered</param>
        /// <returns></returns>
        public static List <ManagementObject> GetRemoteProcesses(string strMachineName, string strDomainName, string strUserName, string strPassword, ref string strError)
        {
            try
            {
                ConnectionOptions connOptions = new ConnectionOptions();
                ManagementScope   myScope     = new ManagementScope();

                connOptions.Impersonation    = ImpersonationLevel.Impersonate;
                connOptions.EnablePrivileges = true;
                if (strMachineName.ToUpper() == Environment.MachineName.ToUpper())
                {
                    myScope = new ManagementScope(@"\ROOT\CIMV2", connOptions);
                }
                else
                {
                    connOptions.Username = strDomainName + "\\" + strUserName;
                    connOptions.Password = strPassword;
                    myScope = new ManagementScope(@"\\" + strMachineName + @"\ROOT\CIMV2", connOptions);
                }

                myScope.Connect();
                ManagementObjectSearcher    objSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process");
                ManagementOperationObserver opsObserver = new ManagementOperationObserver();
                objSearcher.Scope = myScope;
                string[] sep = { "\n", "\t" };

                List <ManagementObject> listObjects = new List <ManagementObject>();

                // Loop Mamagement Objects
                foreach (ManagementObject obj in objSearcher.Get())
                {
                    listObjects.Add(obj);
                }

                return(listObjects);
            }
            catch (Exception ex)
            {
                strError += "\r\n" + "Error: Method Name: " + System.Reflection.MethodBase.GetCurrentMethod().Name + "\r\n" + "Could not Retrieve Process Machine Name" + ex.ToString();
                //ErrorList.Add(new KeyValuePair<FileInformation.FileErrorType, string>(FileInformation.FileErrorType.ExceptionThrown, strError));

                return(null);
            }
        }
示例#25
0
    public static void Main(string[] args)
    {
        Monitor m = new Monitor();
        ManagementOperationObserver ob = new ManagementOperationObserver();

        ob.Completed += new CompletedEventHandler(m.OnCompleted);
        ManagementObject mo = new ManagementObject("Win32_Process=316");

        mo.Get(ob);
        while (!m.IsComplete)
        {
            // do something while waiting
            System.Threading.Thread.Sleep(1000);
        }
        if (!m.IsError)
        {
            Console.WriteLine("Retrieved {0}", mo["__PATH"]);
        }
    }
    public static void Main(string[] args)
    {
        Monitor m = new Monitor();
        ManagementOperationObserver ob = new ManagementOperationObserver();

        ob.Completed   += new CompletedEventHandler(m.OnCompleted);
        ob.ObjectReady += new ObjectReadyEventHandler(m.OnObjectReady);
        ManagementClass      mc    = new ManagementClass("Win32_Process");
        ManagementBaseObject parms = mc.GetMethodParameters("Create");

        parms["CommandLine"]      = @"c:\winnt\system32\notepad.exe c:\boot.ini";
        parms["CurrentDirectory"] = ".";
        mc.InvokeMethod(ob, "Create", parms, null);
        while (!m.IsComplete)
        {
            // do something while waiting
            System.Threading.Thread.Sleep(1000);
        }
    }
    public AsyncGetExample()
    {
        ManagementClass c =
            new ManagementClass("Win32_Process");
        ManagementOperationObserver ob =
            new ManagementOperationObserver();

        ob.ObjectReady += new ObjectReadyEventHandler(NewObject);
        ob.Completed   += new CompletedEventHandler(Done);

        c.GetInstances(ob);

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

        // Here you can use the object
    }
    public async Task RefreshPorts()
    {
        var token = _cancellationSource.Token;

        IsRefreshBusy = true;
        await Task.Delay(750, token).ConfigureAwait(true);

        var lastSelectedDeviceId = SelectedSerialPortDeviceId;

        SerialPorts.Clear();
        try
        {
            var scope    = new ManagementScope("\\\\.\\ROOT\\cimv2");
            var observer = new ManagementOperationObserver();
            using var searcher = new ManagementObjectSearcher(scope, new SelectQuery("Win32_PnPEntity"));

            observer.ObjectReady += (_, e) =>
            {
                var portInfo = SerialPortInfo.FromManagementObject(e.NewObject as ManagementObject);
                if (portInfo == null)
                {
                    return;
                }

                SerialPorts.Add(portInfo);
            };

            var taskCompletion = new TaskCompletionSource();
            observer.Completed += (_, _) => taskCompletion.TrySetResult();

            searcher.Get(observer);
            using (token.Register(() => taskCompletion.TrySetCanceled()))
                await taskCompletion.Task.WaitAsync(token).ConfigureAwait(true);
        }
        catch { }

        SelectSerialPortByDeviceId(lastSelectedDeviceId);
        await Task.Delay(250, token).ConfigureAwait(true);

        IsRefreshBusy = false;
    }
示例#29
0
        public async Task <uint> EnableAsync()
        {
            if ((isEmbedded == false))
            {
                ManagementBaseObject inParams = null;
                var observer = new ManagementOperationObserver();
                var tcs      = new TaskCompletionSource <uint>();
                observer.ObjectReady += (sender, e) =>
                {
                    tcs.SetResult(Convert.ToUInt32(e.NewObject.Properties["ReturnValue"].Value));
                };

                PrivateLateBoundObject.InvokeMethod(observer, "Enable", inParams, null);

                return(await tcs.Task);
            }
            else
            {
                return(Convert.ToUInt32(0));
            }
        }
示例#30
0
        public bool FormatDrive(ManagementObjectSearcher searcher, ManagementOperationObserver watcher, string driveLetter,
                                string fileSystem = "FAT32", bool quickFormat = true,
                                int clusterSize   = 8192, string label        = "", bool enableCompression = false)
        {
            try
            {
                if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
                {
                    return(false);
                }

                //query and format given drive
                searcher = new ManagementObjectSearcher
                               (@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");


                ManagementObjectCollection moc = searcher.Get();

                foreach (ManagementObject vi in moc)
                {
                    vi.InvokeMethod(watcher, "Format", new object[]
                                    { fileSystem, quickFormat, clusterSize, label, enableCompression });
                }

                return(true);
            }
            catch (Exception e)
            {
                if (nabor.status.InvokeRequired)
                {
                    nabor.status.Invoke(new Action <string>((s) => nabor.status.Text += s), e.Message);
                }
                else
                {
                    nabor.status.Text += e.Message;
                }
                fail(this);
                return(false);
            }
        }
	public void GetSubclasses(ManagementOperationObserver watcher) {}
	public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options) {}
	public void Put(ManagementOperationObserver watcher) {}
	public void InvokeMethod(ManagementOperationObserver watcher, string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) {}
	public void InvokeMethod(ManagementOperationObserver watcher, string methodName, object[] args) {}
	public void Delete(ManagementOperationObserver watcher, DeleteOptions options) {}
	public void Delete(ManagementOperationObserver watcher) {}
	public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options) {}
	public void CopyTo(ManagementOperationObserver watcher, string path) {}
	public void Put(ManagementOperationObserver watcher, PutOptions options) {}
	public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options) {}
	public void GetInstances(ManagementOperationObserver watcher) {}
	public void GetRelationships(ManagementOperationObserver watcher, string relationshipClass) {}
	public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) {}
	public void GetRelatedClasses(ManagementOperationObserver watcher) {}
	public void GetRelationships(ManagementOperationObserver watcher) {}
	public void GetRelationships(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, EnumerationOptions options) {}