using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Serialization;
namespace ChadSoft.DataAccess
{
public sealed class SqlDatabase : Database
{
public SqlDatabase()
{
}
public SqlDatabase(string connectionName) : base(connectionName)
{
}
///
/// Executes the XML reader.
///
///
/// The command text.
/// The parameters.
///
///
/// The default CommandType for this method is StoredProcedure
/// (as opposed to the other ExecuteX() methods, where it is Text)
///
public T ExecuteXmlReader(string commandText, IDictionary parameters)
{
return ExecuteXmlReader(commandText, CommandType.StoredProcedure, parameters);
}
///
/// Executes the XML reader.
///
///
/// The command text.
/// Type of the command.
/// The parameters.
///
public T ExecuteXmlReader(string commandText, CommandType commandType, IDictionary parameters)
{
var serializer = new XmlSerializer(typeof(T));
return ExecuteXmlReader(commandText, commandType, parameters, rdr => (T)serializer.Deserialize(rdr));
}
///
/// Executes the XML reader.
///
///
/// The command text.
/// Type of the command.
/// The parameters.
/// The conversion function.
///
public T ExecuteXmlReader(string commandText, CommandType commandType, IDictionary parameters, Func conversionFunction)
{
var cmd = new XmlReaderToObjectCommand(conversionFunction);
return Execute(commandText, commandType, parameters, cmd.Execute);
}
///
/// Executes the specified command text.
///
/// The query's result type
/// The command text.
/// Type of the command.
/// The parameters.
/// The result processor.
///
/// The result of the
///
public override T Execute(string commandText, CommandType commandType, IDictionary parameters, Func resultProcessor)
{
using (var connection = new SqlConnection(GetConnectionString()))
{
using (var command = new SqlCommand(commandText, connection))
{
command.CommandType = commandType;
populateParameters(command, parameters);
connection.Open();
return resultProcessor(command);
}
}
}
private static void populateParameters(SqlCommand command, IDictionary parameters)
{
if (parameters == null) return;
foreach (var name in parameters.Keys)
command.Parameters.AddWithValue(name, parameters[name]);
}
}
internal class XmlReaderToObjectCommand
{
private readonly Func conversionFunction;
public XmlReaderToObjectCommand(Func conversionFunction)
{
this.conversionFunction = conversionFunction;
}
public T Execute(DbCommand command)
{
var sqlCommand = command as SqlCommand;
if (sqlCommand == null)
throw new ApplicationException("Command is not a SqlCommand!");
using (var reader = sqlCommand.ExecuteXmlReader())
return conversionFunction(reader);
}
}
}