Skip to content

Instantly share code, notes, and snippets.

@sandrinodimattia
Created July 22, 2012 19:38
Show Gist options
  • Save sandrinodimattia/3160833 to your computer and use it in GitHub Desktop.
Save sandrinodimattia/3160833 to your computer and use it in GitHub Desktop.
DbProviderFactoryRepository
public class DbProviderFactoryRepository
{
/// <summary>
/// The table containing all the data.
/// </summary>
private DataTable dbProviderFactoryTable;
/// <summary>
/// Name of the configuration element.
/// </summary>
private const string DbProviderFactoriesElement = "DbProviderFactories";
/// <summary>
/// Initialize the repository.
/// </summary>
public DbProviderFactoryRepository()
{
OpenTable();
}
/// <summary>
/// Opens the table.
/// </summary>
private void OpenTable()
{
// Open the configuration.
var dataConfiguration = ConfigurationManager.GetSection("system.data") as System.Data.DataSet;
if (dataConfiguration == null)
throw new InvalidOperationException("Unable to open 'System.Data' from the configuration");
// Open the provider table.
if (dataConfiguration.Tables.Contains(DbProviderFactoriesElement))
dbProviderFactoryTable = dataConfiguration.Tables[DbProviderFactoriesElement];
else
throw new InvalidOperationException("Unable to open the '" + DbProviderFactoriesElement + "' table");
}
/// <summary>
/// Adds the specified provider.
/// </summary>
/// <param name="provider">The provider.</param>
public void Add(DbProviderFactoryDescription provider)
{
Delete(provider);
dbProviderFactoryTable.Rows.Add(provider.Name, provider.Description, provider.Invariant, provider.Type);
}
/// <summary>
/// Deletes the specified provider if present.
/// </summary>
/// <param name="provider">The provider.</param>
public void Delete(DbProviderFactoryDescription provider)
{
var row = dbProviderFactoryTable.Rows.Cast<DataRow>()
.FirstOrDefault(o => o[2] != null && o[2].ToString() == provider.Invariant);
if (row != null)
{
dbProviderFactoryTable.Rows.Remove(row);
}
}
/// <summary>
/// Gets all providers.
/// </summary>
/// <returns></returns>
public IEnumerable<DbProviderFactoryDescription> GetAll()
{
return dbProviderFactoryTable.Rows.Cast<DataRow>()
.Select(o => new DbProviderFactoryDescription(o));
}
/// <summary>
/// Get provider by invariant.
/// </summary>
/// <param name="invariant"></param>
/// <returns></returns>
public DbProviderFactoryDescription GetByInvariant(string invariant)
{
var row = dbProviderFactoryTable.Rows.Cast<DataRow>()
.FirstOrDefault(o => o[0] != null && o[0].ToString() == invariant);
if (row != null)
{
return new DbProviderFactoryDescription(row);
}
else
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment