public T QuerySingleOrDefault <T>() { string className = WmiHelper.GetClassName <T>(); if (string.IsNullOrEmpty(className)) { throw new NullReferenceException($"Type of {typeof(T)} does not use {typeof(WmiClassAttribute)}. This is required."); } string searchableProperties = WmiHelper.GetSearchableProperties <T>(); return(this.QuerySingleOrDefault <T>(WmiHelper.GetNamespace <T>(), $"SELECT {searchableProperties} FROM {className}")); }
public IEnumerable <T> Query <T>(string @namespace, string query) { if (!query.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"The query is not a select statement."); } scope.Path = new ManagementPath(@namespace); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query))) using (ManagementObjectCollection wmiRes = searcher.Get()) { foreach (ManagementObject mo in wmiRes) { yield return(WmiHelper.LoadType <T>(mo)); } } }
/// <summary> /// Query a single record of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="namespace">The wmi namespace to query. /// <param name="query">What to select using WMI Query Language</param> /// <returns></returns> public T QuerySingleOrDefault <T>(string @namespace, string query) { if (!query.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"The query is not a select statement."); } T result = default(T); scope.Path = new ManagementPath(@namespace); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query))) using (ManagementObjectCollection wmiRes = searcher.Get()) { foreach (ManagementObject mo in wmiRes) { result = WmiHelper.LoadType <T>(mo); break; } } return(result); }