I came across an example of the implementation an an interface. Portion of code is
public partial interface IDataProvider
{
DataTable GetEmployeeAbsenceDurationTypes();
void AlterEmployeeAbsenceDurationTypes(DataTable lookUpTable);
}
public partial class DataProvider : IDataProvider
{
public DataTable GetEmployeeAbsenceDurationTypes()
{
return GetEmployeeAbsenceDurationTypes((DbTransaction)null);
}
public DataTable GetEmployeeAbsenceDurationTypes(DbTransaction tran)
{
//Db Operations
}
}
My first question is about this "DbTransaction" class. Its not in my project, is it a build in class?
My second question is, why in the DataProvider (the implementing class), the function is calling another overload of itself?
DbTransaction is a common base-class for representing database transactions in ADO.NET; each actual ADO.NET provider subclasses this (typically) - for example SqlTransaction : DbTransaction (the sql-server client).
Calling an overload of self is a common way of implementing optional parameters, without code duplication prior to their addition in C# 4.0. In this case, that is essentially a pre-4.0 way of implementing:
public DataTable GetEmployeeAbsenceDurationTypes(DbTransaction tran = null) {...}
either implementation (overloads or optional parameter) allows usage of the form:
obj.GetEmployeeAbsenceDurationTypes(); // without transaction
obj.GetEmployeeAbsenceDurationTypes(tran); // with transaction
The first question is impossible to answer for sure without seeing the whole code, but it's probably referring to System.Data.Common.DbTransaction.
As for the implementation - presumably it's a way of reusing the code, that's all. If the implementation of the method with a parameter can handle a parameter value of null as "do it in a new transaction" (or whatever the behaviour of the parameterless method should be) naturally, why wouldn't you want one overload to call the other?
Related
I have a C# application using ADO.Net access to a particular type of database (VistaDB) which I need to extend to optionally use a second type of database (SQL Server).
I'm unable to use Vista Entity Framework data access (which can support multiple database types) as this requires a higher version of the .NET framework than is available to most of my users. My data access functions take VistaDBConnection as ref arguments and whilst I can overload the functions to provide SqlConnection argument support, this will mean replicating a large number of data access functions.
I was wondering if it was possible to define function arguments to be either VistaDBConnection or SqlConnection types and then test for which type has been passed and provide options inside the data access routine to use either. I can do this by passing both VistaConnection and SqlConnection arguments to the data access functions but passing a single argument or variable type would be neater. However, this does break the strong typing feature of C#.
The best would be either to create an interface or a base class. Then have two concrete classes that implement this interface, one for VistaDB and one for SQL Server. You can then use some kind of factory (or Dependency Injection) to instantiate the correct class at runtime. The methods in question would then take an instance of the interface/base class and does not need to know any of the specific inner workings. For example:
interface IApplicationDatabase
{
Foo GetFoo(int id);
}
class VistaDatabase : IApplicationDatabase
{
public Foo GetFoo(int id)
{
//do VistaDB-specific things to get the Foo
}
}
class SqlServerDatabase : IApplicationDatabase
{
public Foo GetFoo(int id)
{
//do SQL Server-specific things to get the Foo
}
}
class Demo
{
public Foo GetFooFromStorage(int id, IApplicationDatabase storage)
{
//notice here we don't need any separate code depending on the
//concrete type of database
return storage.GetFoo(id);
}
}
You just need to define more generic type or we can say parent type of the both connection SQL as well as VistaDB connection like following. and then use as operator to cast and check against null to check whether cast was successful or not.
public void Connect(DbConnection dbConnection)
{
var sqlDbCon = dbConnection as SQLConnection;
if(con != null)
{
//process here for SQLConnection
}
var vistaDbCon = dbConnection as VistaDbConnection;
if(con != null)
{
//process here for VistaDbConnection
}
}
You don't need to do separate implementation in if else if all you want is available in a parent class like in this case if you just want to call connect method then you can do it like below because it does have connect method in IDbConnection.
public void Connect(IDbConnection dbConnection)
{
dbConnection.Open();
}
It would work in both the case with sql server and vistadb.
The idea is, Instead of using a class as type for the parameter, use interface as type for the parameter.
This interface will be defined by you and implemented individually for each type of connection.
Now when you pass instance of any classes implementing the interface, your code will work.
Use Interface function to call provider specific functions.
Previous two code samples added by other contributors is the correct example for that, Use any of them.
You might feel this is homework, for that I am sorry. I have searched but couldn't find a proper answer.
So my question is:
I have several classes and each class has a method to save. So I created a separate class for database handling.
namespace HospitalMgt.Data
{
public static class DBConnection
{
public static string constr = "Data Source=ABD;Initial Catalog=HospitalMgt;User Id=sa;Password=123";
public static SqlConnection con;
// public static SqlCommand com;
public static SqlConnection OpenConnection()
{
con= new SqlConnection(constr);
con.Open();
return con;
}
}
}
However, I don't think it's suitable to implement all the classes with a DBConnection class.
My question :
What design pattern is suited to overcome this problem?
Is it good practise to create DBConnection as class? (Or should it be an Interface)
I found a few articles about DA layers using the Factory method, but according to my knowledge, that pattern does not suit my situation.
Normally, if I can't use any existing framework, I use both the Repository and Active patterns.
For simplicity, you could use only the Repository pattern. I normally define it like this:
public interface IEntity<T> { }
// Define a generic repository interface
public interface IRepository<TKey, TEntity>
where TEntity : IEntity<TKey>
{
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
IEntity<TKey> Get(TKey key);
IEnumerable<TEntity> GetRange(IEnumerable<TKey> keys);
IEnumerable<TEntity> GetAll();
// ..., Update, Delete methods
}
// Create an abstract class that will encapsulate the generic code
public abstract class Repository<TKey, TEntity> : IRepository<TKey, TEntity>
where TEntity : IEntity<TKey>
{
protected Repository(/*parameter you may need to implement the generic methods, like a ConnectionFactory, table name, entity type for casts, etc */) { }
public override void Insert(IEntity<TKey> entity)
{
// do the insert, treat exceptions accordingly and encapsulate them in your own and more concise Exceptions, etc
}
// ...
}
// Create the entities classes, one for each table, that will represent a row of that table
public class Car : IEntity<string> {/* Properties */}
// Create a specific repository for each table
// If the table have a composed key, just create a class representing it
public class CarRepository : Repository<string, Car>
{
public CarRepository() {/* pass the base parameters */}
// offer here your specific operations to this table entity
public IEnumerable<Car> GetByOwner(PersonKey ownerKey)
{
// do stuff
}
}
Obviously, when doing your own implementations, you must take into account thread safety making good using of transactions, specially across diferent entity repositories.
// simple example
ITransaction t = TransactionFactory.GetNewTransaction();
t.begin();
try{
// create person entity
personRepository.Add(person, t);
// create cars assigned to person
carRepository.AddRange(cars, t);
t.commit();
}catch(Exception){
t.rollback();
}
Just be sure that you really want to create your own DAL since it can end beeing extremelly complex, specially trying to develop the most generic solution.
First of all, I would like to recommend you the article Design Patterns for Data Persistence by Jeremy Miller.
There are some data access layer patterns:
Active record pattern (wiki, Detailed info).
Repository pattern (Detailed info).
I suggest using an ORM, Entity Framework or NHibernate will do nicely. Then you do not have to worry about a db context or create SQL statements.
Its too old but just came around this question and could not resist to post my thoughts.
I found Repository with UnitOfWork with some descent ORM is good approach. This minimizes most of the issues.
The UoW mentioned in above link can be injected in Repository. That increases the flexibility of usage. Also, all DB Communication code is centralized at one place. The example is not complete but a startup point.
Repository pattern mentioned in above link is actually a generic base class. You can create new class for each of your concrete Repository that derives from it.
Generic repository is considered an anti pattern; there are lot many articles on internet that explains it.
Why generic repository is anti-pattern?
A repository is a part of the domain being modeled, and that domain is not generic.
Not every entity can be deleted.
Not every entity can be added
Not every entity has a repository.
Queries vary wildly; the repository API becomes as unique as the entity itself.
For GetById(), identifier types may be different.
Updating specific fields (DML) not possible.
Generic query mechanism is the responsibility of an ORM.
Most of the ORMs expose an implementation that closely resemble with Generic Repository.
Repositories should be implementing the SPECIFIC queries for entities by using the generic query mechanism exposed by ORM.
Working with composite keys is not possible.
It leaks DAL logic in Services anyway.
Predicate criteria if you accept as parameter needs to be provided from Service layer. If this is ORM specific class, it leaks ORM into Services.
I suggest you read these (1, 2, 3, 4, 5) articles explaining why generic repository is an anit-pattern.
Solution:
Write an abstract Generic Repository that is wrapped by a concrete repository. That way you can control the public interface but still have the advantage of code-reuse that comes from generic repository.
Use a Generic Repository but do use composition instead of inheritance and do not expose it to the domain as a contract.
In any case, do not expose Generic Repository to calling code. Also, do not expose IQueryable from concrete repositories.
I suggest you to use a RepositoryBase for all this common operations. If you decide to use an ORM for data access it's good to think in a implementation of repositories based on a Generic Type repository.
Here is a good article about it:
http://lostechies.com/jimmybogard/2009/09/03/ddd-repository-implementation-patterns/
Okay, I need some help here.
This is the same old "can't use an interface to enforce constructors/static methods" problem.
WHAT IS THE PROPER OO DESIGN THEN??
I have a set of data entities (Entity Framework stuff) for which I wrote partial class methods to convert to/from XML (XElement objects).
I have an instance method to "save" XML:
// Convert entity to XML
public XElement ToXml() {}
...and I have a constructor to "read" XML:
// Create entity from XML constructor.
public MyEntity(XElement) {}
Alternatively, I could use a static factory method to "read" XML:
public static MyEntity ParseXml(XElement) {}
The dilemma:
I could create an interface that mandates the "save" ToXml() method, but what good is that if it only addresses half the problem? An interface can't enforce either of the "load" methods.
I could rely on my own good intent to create these methods without any sort of contract.
I could create a static class filled with redundant methods like XmlToEntity1() and XmlToEntity2(), etc... (Now I've described a good 'generics' problem.) However, the specific conversion code (which is specific to each entity) would create separate methods or switch/case for each and seems to belong inside the entity classes, not in some other class, no?
If an experienced C# coder can show a good design for this common problem I think I would learn a lot from it.
Happy 4th of July!
Possible Solution 1
A single XmlSerializer class with two static generic methods:
public static T Deserialize<T>(XElement xml) {}
public static XElement Serialize<T>(T entity) {}
Pro: Only one class (no interface needed)
Pro: Separates serialization responsibility from entity classes.
Con: Would still require separate methods or switch/case blocks for each entity type supported.
Con: ? Not extensible -- have to modify this class each time an entity changed or added/deleted.
Possible lessons learned?
The "can't use interface for constructors and static methods" problem might be a symptom of:
Violating the SRP (Single Responsibility Principal).
Violating the SoC (Separation of Concern) principal.
What about using a simple instance method for loading from XML as well? Your interface would then be something like:
public interface XmlSerializableEntity
{
XElement Serialize(); // or ToXml() if you prefer..
void Deserialize(XElement e); // or Load() or something like that..
}
Or you could use a generic solution:
public interface Serializable<T>
{
T Serialize();
void Deserialize(T e);
}
The downside is that you have to initialize the entity object before you load it, which might mean you'll have an object in an invalid state. But I do believe this is a common pattern.
It would be a good design to have the storage/retrieval separate from the entity anyway. In OO terms this can be referred to as the Single Responsibility Principle. Your entity exists for some purpose (probably related to your domain). The storage of that entity is a separate responsibility that could change independent of the domain. (e.g. you could retrive it from a database, a web service or the file system).
Static methods are not the only way to do this of course. You could create an interface at the save/retrive level and implement that interface for each of the entities. Then you could easily use those in a generic way without worrying a lot about the types.
Adding some example code:
interface EntityGateway<TEntity> {
TEntity Load(String id);
void Save(TEntity entity);
}
public class XEntityGateway implements EntityGateway<XEntity> {
XEntity Load(String id) { ... implementation details }
void Save(XEntity entity) { ... implementation details }
}
XEntityGateway gw = new XEntityGateway();
XEntity entity = gw.Load("SOMEID");
// modify entity
gw.Save(entity);
I'm using constructor injection for the first time and wish to write my code defensively.
Therefore if I have a class with a constructor and a save method as below:
public SomeConstructor(string name, Object someObject)
{
_name= name;
_someObject= someObject;
}
public void Save()
{
// Does a database save
}
But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:
public SomeConstructor(string name) : this(name, null)
{
}
How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?
I'm not using an injection tool.
Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.
What I wanted to avoid was a series of validation checks at the start of each method.
Use the friction you are experiencing as a warning system. It's really telling you that you're likely moving towards low cohesion and violation of the Single Responsibility Principle.
If this is the case, refactor the class into two separate classes.
You may prevent that situation with a run-time exception like InvalidOperationException.
If some instantiated the class with the two-parameters-constructor and tries to call Save, just check if "someObject" is null, and if it's so:
throw new InvalidOperationException("This method cannot be invoked in current object state");
In the other hand, if this second constructor would be used by your library and third-party library developers wouldn't be allowed to use it, this constructor should have the internal modifier.
The IoC it is just a way to dinamically resolve the dependency but doens't solve any OO problem.
I would focus on a good OO design instead of try to find a way to cheat the framework forcing to use a contractor instead of another.The question is how would you do that if you were not using an IoC framework?
probabily checking if SomeObject is null?
public void Save()
{
if (_someObject == null)
throw new InvalidOperationException();
}
I guess that this is obvious. But you really can't create a contract in which the type is constructed differently unless you also change your SomeConstructor type to work like a decorator pattern. What the decorator pattern does is that it let's you build the inheritance hierarchy at run-time not compile-time.
You can then create different objects depending on what operations are allowed internally. This is some work for something which can easily be handled with a pre-condition for the Save method. But maybe this is what you need. And if you did it you could stipulate your contract in the constructor of SomeConstructor.
Here's an example:
interface ISomeConstructor
{
void Save();
}
class SomeConstructor
{
ISomeConstructor impl;
public SomeConstructor(string name, object someObject)
{
impl = new StringAndObject(name, someObject);
}
public SomeConstructor(string name)
{
impl = new JustString(name);
}
public void Save()
{
impl.Save();
}
}
The types StringAndObject and JustString implements ISomeConstructor and they can handle the Save method as they see fit.
This is a slight variation of the decorator pattern as normally you'd expect ISomeConstructor to be passed as an argument to the constructor as well.
I use System.Data.SQLite and C# for accesing SQLite databases/tables. For lazy and fast development reasons, I created my own library of classes to encapsulate some of System.Data.SQLite methods in one method, and to create many common database routines (methods) that let me reduce my work when accessing to data.
If I would inherit System.Data.SQLite library instead of referencing it would help me to optimize my work, ¿is this possible? ¿may you give an example, please?
It's possible to inherit from SQLite and make additions to some of the classes, particularly SQLiteConnection. However, you won't be able to use your own classes everywhere as SQLite will internally create a lot of classes like SQLiteCommand and SQLiteParameter and you don't have an option to tell SQLite to use your custom versions. There is a SQLiteFactory, but this is used for ADO.NET data provider integration and is not used internally by SQLite.
You're much better off keeping your methods separate. If you want them to feel like they're part of the library you can use Extension Methods
This is a great question and I didn't find much in the way of answers 7-years later! I just had to do a simple inherit and found it a little tricky (because I wasn't completely familiar with constraining a generic type). But here's what I ended up with that worked.
using SQLite; // Here using sqlite-net-pcl
using System.Collections.Generic;
namespace SQLiteEx
{
class SQLiteConnection : SQLite.SQLiteConnection
{
// Must provide a constructor with at least 1 argument
public SQLiteConnection(string path)
: base(path)
{
}
// With this class, you can automatically append
// some kind of global filter like LIMIT 1000
string mGlobalFilter = "";
public string GlobalFilter
{
set { mGlobalFilter = value; }
get { return string.IsNullOrWhiteSpace(mGlobalFilter) ? "" : " " + mGlobalFilter; }
}
// You MUST constrain the generic type with "where T : new()"
// OTHERWISE feel the wrath of:
// ===================================================================
// 'T' must be a non-abstract type with a public parameterless
// constructor in order to use it as parameter 'T' in the generic
// type or method 'SQLiteConnection.Query<T>(string, params object[])'
// ===================================================================
public List<T> Query<T>(string sql) where T : new()
{
return base.Query<T>(sql + GlobalFilter);
}
}
}