private void LoadSchema(DataSet ds, WmiCommand command, WmiDataReader reader) { //Match the query "table". string name = _commandtable.Match(command.CommandText).Groups["table"].Value; if (ds.Tables.Contains(name)) { ds.Tables.Remove(name); } DataTable table = new DataTable(name); //Use the first object to build the table structure. ManagementObject one = reader.GetOne(); if (one != null) { foreach (PropertyData prop in one.Properties) { table.Columns.Add(prop.Name, WmiConvert.WmiToClr(prop.Type)); } } //Add dummy column if no data is found. For consistency with other ADO.NET providers which always load the schema. if (table.Columns.Count == 0) { table.Columns.Add("Object", typeof(string)); } ds.Tables.Add(table); }
/// <summary> /// Executes the WMI query and returns an IDataReader. /// </summary> /// <returns>The reader with the results.</returns> public IDataReader ExecuteReader() { if (_connection == null || _connection.State != ConnectionState.Open) { throw new InvalidOperationException("The connection must be set and opened in order to execute the command."); } if (_query == null || _query == String.Empty) { throw new InvalidOperationException("The CommandText must be set in order to execute the command."); } // create a reader WmiDataReader reader = new WmiDataReader(_connection); ManagementObjectSearcher os = new ManagementObjectSearcher(_connection.Scope, new ObjectQuery(_query)); reader.Data = os.Get(); return(reader); }
/// <summary> /// Adds rows in the DataSet to match those in the data source. /// </summary> /// <param name="dataSet">A DataSet to fill with records and, if necessary, schema.</param> /// <returns>The number of rows successfully added to the DataSet.</returns> public int Fill(DataSet dataSet) { if (_select == null || _select.CommandText == String.Empty) { throw new InvalidOperationException("Select command doesn't contain a valid query to execute."); } //Open connection if needed. bool doclose = false; if (_select.Connection.State != ConnectionState.Open) { _select.Connection.Open(); doclose = true; } WmiDataReader dr = (WmiDataReader)_select.ExecuteReader(); LoadSchema(dataSet, _select, dr); DataTable tb = dataSet.Tables[_commandtable.Match(_select.CommandText).Groups["table"].Value]; if (tb != null) { tb.BeginLoadData(); while (dr.Read()) { object[] values = new object[dr.FieldCount]; dr.GetValues(values); tb.LoadDataRow(values, true); } } //Close connection if appropriate. if (doclose) { _select.Connection.Close(); } return(dr.RecordsAffected); }