public WMIRetriever(WMIContext context, WMIRetrieverOptions options) { Context = context; Options = options; m_retrieval_context = new RetrievalContext(Options.Timeout); }
/// <summary> /// Gets a list of Dictionaries mapping the property name to the object retrieved /// for that property. /// A list is returned because some WMI call return multiple things /// /// Was recently updated to handle the WMI calls in an asynchronous way, so the /// data collection can be stopped during a long-running WMI call. /// /// https://msdn.microsoft.com/en-us/library/cc143292.aspx /// </summary> /// <param name="log"></param> /// <returns></returns> public RetrievalContext Retrieve(ILog log) { string query_str = string.Format("SELECT {0} FROM {1}", Context.Properties, Context.Class); if (string.IsNullOrEmpty(Context.Where) == false) { query_str += " WHERE " + Context.Where; } string path = string.Empty; try { SelectQuery query = new SelectQuery(query_str); ManagementScope scope = Context.GetManagementScope(); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) { path = scope.Path.Path; if (log != null) { log.Debug("Executing: " + path + " -- " + query_str); } ManagementOperationObserver results = new ManagementOperationObserver(); results.ObjectReady += new ObjectReadyEventHandler(this.OnNewObject); results.Completed += new CompletedEventHandler(this.OnComplete); // Start a new Retrieving object so everything is up-to-date right now m_retrieval_context = new RetrievalContext(Options.Timeout); searcher.Get(results); while (m_retrieval_context.IsCompleted == false) { if (m_retrieval_context.HasTimedOut) { results.Cancel(); throw new Exception($"Timeout executing '{query_str}', path is '{path}'"); } if (GlobalIsRunning.IsRunning == false) { m_retrieval_context.IsCompleted = true; results.Cancel(); } else { Thread.Sleep(250); } } } } catch (Exception e) { if (log != null) { log.Error(e); log.Error(query_str); if (string.IsNullOrEmpty(path) == false) { log.Error(path); } } } finally { m_retrieval_context.IsCompleted = true; } return(m_retrieval_context); }