Showing posts with label oop. Show all posts
Showing posts with label oop. Show all posts

Implementing Repository pattern and Dependency Injection in ADO.net using Generics in C#

Udemy
Nowadays i am trying to learn different design patterns in object oriented paradigm that are pretty useful to implement generic solutions for different scenarios, few weeks back for a job hunt i got an assignment to do which was a web application which would interact with database, so i took it as a challenge and decided to make it loosely coupled using design patterns which were applicable in that scenario.

One of them which implemented in my assignment is repository pattern using generics and with that Dependency Injection using which i injected dependencies of Repository class via constructor.
 


I made generic class which would be inherited by other types against the different tables in the application. in this class i have used different framework features like Reflection and Generics.


My generic class is an abstract class, so it needs to be inherited for making use of it, you will see next how we will use it.


Here is the Repository class:

public abstract class Repository<TEntity> where TEntity : new()
{
    DbContext _context;

    public Repository(DbContext context)
    {
        _context = context;
    }

    protected DbContext Context 
    { 
        get
        {
          return this._context;
        } 
    }

    protected IEnumerable<TEntity> ToList(IDbCommand command)
    {
        using (var record = command.ExecuteReader())
        {
            List<TEntity> items = new List<TEntity>();
            while (record.Read())
            {
                    
                items.Add(Map<TEntity>(record));
            }
            return items;
        }
    }

        
    protected TEntity Map<TEntity>(IDataRecord record)
    {
        var objT = Activator.CreateInstance<TEntity>();
        foreach (var property in typeof(TEntity).GetProperties())
        {
            if (record.HasColumn(property.Name) && !record.IsDBNull(record.GetOrdinal(property.Name)))
                property.SetValue(objT, record[property.Name]);


        }
        return objT;
    }


}

Now i have table in database User whose schema is :

CREATE TABLE [dbo].[tblUser] (
    [UserID]    INT           IDENTITY (1, 1) NOT NULL,
    [FirstName] NVARCHAR (25) NULL,
    [LastName]  NVARCHAR (25) NULL,
    [UserName]  NVARCHAR (25) NULL,
    [Password]  NVARCHAR (25) NULL,
    [IsActive]  BIT           NULL,
    [IsDeleted] BIT           NULL,
    [CreatedBy] INT           NULL,
    [CreatedAt] DATETIME      NULL,
    [UpdatedBy] INT           NULL,
    [UpdatedAt] DATETIME      NULL,
    [Email]     NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([UserID] ASC)
);



Against this table i have Model class for mapping from table to that type which looks :

public class User
{
    public int UserID { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public bool IsActive { get; set; }

    public bool IsDeleted { get; set; }

    public DateTime CreatedAt { get; set; }

    public int CreatedBy { get; set; }

    public DateTime UpdatedAt { get; set; }

    public int UpdatedBy { get; set; }

    public string Email { get; set; }
}

We want to fetch data from User table for which we will create a Repository class for User type and the we will write implementation to fetch records from User table from database. Our all methods that need to get data, insert data,update data or delete data from User table will reside in the UserRepository class.

Here is the implementation of User Repository class:

public class UserRepository : Repository<User>
{
    private DbContext _context;
    public UserRepository(DbContext context)
        : base(context)
    {
        _context = context;
    }


    public IList<User> GetUsers()
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandText = "exec [dbo].[uspGetUsers]";

            return this.ToList(command).ToList();
        }
    }

    public User CreateUser(User user)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignUp";

            command.Parameters.Add(command.CreateParameter("@pFirstName", user.FirstName));
            command.Parameters.Add(command.CreateParameter("@pLastName", user.LastName));
            command.Parameters.Add(command.CreateParameter("@pUserName", user.UserName));
            command.Parameters.Add(command.CreateParameter("@pPassword", user.Password));
            command.Parameters.Add(command.CreateParameter("@pEmail", user.Email));

            return this.ToList(command).FirstOrDefault();


        }

    }


    public User LoginUser(string id, string password)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignIn";

            command.Parameters.Add(command.CreateParameter("@pId", id));
            command.Parameters.Add(command.CreateParameter("@pPassword", password));

            return this.ToList(command).FirstOrDefault();
        }
    }


    public User GetUserByUsernameOrEmail(string username, string email)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspGetUserByUsernameOrEmail";

            command.Parameters.Add(command.CreateParameter("@pUsername", username));
            command.Parameters.Add(command.CreateParameter("@pEmail", email));

            return this.ToList(command).FirstOrDefault();
        }
    }


}


We are done for the UserRepository for new, i have added methods are wrote Stored Procedure to complete the assignment and now i will tell how to make use of it in the Service Layer or in Business Rule to do operations.




First create an interface namely IUserService:

[ServiceContract]
public interface IUserService
{

    [OperationContract]
    IList<User> GetUsers();

    [OperationContract]
    User RegisterUser(User user);

    [OperationContract]
    User Login(string id, string password);

    [OperationContract]
    bool UserNameExists(string username, string email);


}


Here is my WCF Service for User that calls the UserRepository for doing operations:

public class UserService : IUserService
{
    private IConnectionFactory connectionFactory;

    public IList<User> GetUsers()
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.GetUsers();
    }

    public User RegisterUser(User user)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.CreateUser(user);
    }


    public User Login(string id, string password)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.LoginUser(id, password);
    }

    public bool UserNameExists(string username, string email)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        var user = userRep.GetUserByUsernameOrEmail(username, email);
        return !(user != null && user.UserID > 0);

    }
}

You can see that when creating instance of UserRepository i am injecting database context via constructor and then i am calling different methods from userReposiory according to need.

Now in future when i add another table in database, i would create another Repository type and implement its Data Access logic and will call it same way, so applying Dependency Injection and Repository pattern we are following DRY principle to some extent, but i am sure we can make it more better than this.



OOP Difference between Shadowing and Overriding

Udemy

Introduction:

In this post, we will discuss the concept of Shadowing in OOP using c# and we will see how it works which will give you some idea that where we can use it and hopefully you will be able to decide when working practically in c# where it can be useful.

What is Shadowing:

Shadowing is a concept of  OOP (Object Oriented Programming) paradigm. Using Shadowing we can  provide a new implementation to base class member without overriding it, which means that original implementation of base class member gets shadowed (hidden) with the new implementation of base class member provided in derived class.

Consider a scenario where you have an external assembly which you have added in your project. You have a class in that assembly and it has a method which is not defined as virtual and you want to override that method(define your own implementation for that method) in the derived class. What would you do?
This is the scenario where you can use shadowing concept to override the method in the derived class

Definition:

 Following are few definitions of it

 According to MSDN:

  • Shadowing is concept of using Polymorphism in Object Oriented Programming. When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference; instead, when your code uses the element name, the compiler resolves it to the shadowing element. 
  •  Shadowing is actually hiding overridden method implementation in derived class and call the parent call implementation using derived class object

Difference between Overriding and Shadowing 

There is a major difference in shadowing and overriding which is normally when we override a virtual method in derived class and create instance of derived class and then if we hold reference to derived class object as base class object, and call that member, it always calls derived class implementation which is supposed to happen, but in shadowing the case is different, if for the same virtual member we shadow it in the derived class using new keyword and we call the implementation as above it will call base class implementation when we have reference to object of type base class and if we have reference to same object of derived type it will call derived type implementation so base class and derived class implementation are hidden from each other, method of which implementation to be called depends upon we are calling the member using reference of base type or derived type.

Example:

Suppose, I have a base class BaseLogger which has two virtual methods(means they can be overridden in subclass) defined:

public abstract class BaseLogger
{
    public virtual void Log(string message)
    {
        Console.WriteLine("Base: " + message);
    }

    public virtual void LogCompleted()
    {
        Console.WriteLine("Completed");
    }
}

Now i create a class Logger that inherits from BaseLogger class. Logger class looks like this:

public class Logger : BaseLogger
{
    public override void Log(string message)
    {
        Console.WriteLine(message);
    }

    public new void LogCompleted()
    {
        Console.WriteLine("Finished");
    }
}

Now i want my Console to Print following lines:

Log started!

Base: Log Continuing

Completed



What should i write in Main Program to get the above output ? Here is the code we will need to write:

public class Program
{
    public static void Main()
    {

        BaseLogger logger = new Logger();

        logger.Log("Log started!");
        logger.Log("Base: Log Continuing");
        logger.LogCompleted();
    }
}

The first call to Log method is OK, it has called Derived Logger class Log method and it should because we have overridden it in the Logger class.

The second call is also same.

Now note the third call, it has called  the base class LogCompleted() method not derived class, it is because we have defined derived class method with new keyword which is hiding the derived class method when we are calling it with object of type BaseLogger which is our base class.

If we want to call the derived class LogCompleted() method our object reference should be of type Logger not BaseLogger.While in method overriding this is not the case.

In method overriding if we cast object of derived class to base  class and call method, it will call overridden implementation of derived class.




Should i use Abstract Class or Interface ? (abstract class vs Interface)

Udemy
Most of the time developers get confused about abstract class and interface. while interview most of the time interviewer asks the difference between abstract class and interface, we give answer that we read on internet and what we have understanding, but it gets messed up always.


Also when developing applications, we are not sure often that it is the scenario to use abstract class or create interface.

I am posting text from CLR via C# book where Jeffery Richter is trying to explain when should we use abstract class and when interface. Here is the text from book:

I often hear the question "Should i design a base type or interface ?" The answer is not always clear cut.

Here are some guidelines that might help you:


  • IS - A VS CAN-DO relationship : A type can inherit only one implementation If the Derived type can't claim  IS-A relationship with the base type, don't use a base type, use an interface. interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable), etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface.
  • Ease of Use: It’s generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
  • Consistent Implementation:No matter how well an interface contract is documented, it’s very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Word or with Windows Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested, you can then modify parts that need modification.
  • Versioning:If you add a method to the base type, the derived type inherits the new method, you start off using a type that works, and the user’s source code doesn't even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.