Example #1
0
        public async Task <DataSet> GetDataAsync(ReportCommand command, FieldDefinition[] fields)
        {
            using (SqlCommand sqlCommand = new SqlCommand(command.Text, this.Connection))
            {
                if (null != command.Parameters)
                {
                    foreach (var parameter in command.Parameters)
                    {
                        SqlParameter sqlParameter = new SqlParameter();
                        sqlParameter.ParameterName = parameter.Name;
                        sqlParameter.Value         = parameter.FilterValue.Value ?? DBNull.Value;

                        sqlCommand.Parameters.Add(sqlParameter);
                    }
                }


                DataSet dataSet       = DataSet.FromFields(fields);
                int[]   columnIndices = null;

                this.Logger.LogInformation($"Executing Sql Command : {command.ToString()}");

                if (null != command.Parameters)
                {
                    foreach (var parameter in command.Parameters)
                    {
                        this.Logger.LogInformation($"{parameter.Name} = {parameter.FilterValue.Value}");
                    }
                }

                using (var dataReader = await sqlCommand.ExecuteReaderAsync(System.Data.CommandBehavior.SingleResult))
                {
                    if (null == columnIndices)
                    {
                        try
                        {
                            columnIndices = fields.Select(f => dataReader.GetOrdinal(f.Name)).ToArray();
                        }
                        catch (IndexOutOfRangeException indexOutOfRangeException)
                        {
                            throw new IndexOutOfRangeException($"Field '{indexOutOfRangeException.Message}' could not be found in the retrieved dataset.", indexOutOfRangeException);
                        }
                    }

                    while (await dataReader.ReadAsync())
                    {
                        var dataRow = dataSet.CreateRow();

                        foreach (var columnIndex in columnIndices)
                        {
                            object value = dataReader.GetValue(columnIndex);
                            dataRow.AddData(DBNull.Value == value ? null : value);
                        }
                    }
                }
                return(dataSet);
            }
        }