Design Patterns

Factory Pattern with example – Exception logger

The intent of Factory Mehod is Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

In below example i have used two different places where exception can be stored – File system and Database. The logs are created depending on the LogType specified by the client.

Create ExceptionFactory.cs class file and add below code.

using System;
namespace dotnetfundamentals.AbstractFactory
{
//Creating the Abstract Logger
public interface ILog
{
void Log();
}
public class FileLogger : ILog
{
public void Log()
{
Console.Write("Log to File");
}
}
public class DBLogger : ILog
{
public void Log()
{
Console.Write("Log to DB");
}
}
//Creating the Concrete Factories
public class LogTypeChecker
{
static public ILog WriteLog(LogType logType)
{
ILog objLog = null;
if(logType == LogType.File)
{
objLog = new FileLogger();
}
else if (logType == LogType.Database)
{
objLog = new DBLogger();
}
return objLog;
}
}
public enum LogType
{
File,
Database
}
}

Add below code in Program.cs file.

using System;
namespace dotnetfundamentals.AbstractFactory
{
class Program
{
static void Main(string[] args)
{
ILog objLogger = LogTypeChecker.WriteLog(LogType.File);
objLogger.Log();
}
}
}

Design Patterns

Implementation of Dependency Injection Pattern in C# – Constructor Injection

Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to “inject” a dependency from outside the class.

Key points about Dependency Injection
1. Reduces class coupling
2. Increases code reusing
3. Improves code maintainability
4. Improves application testing

For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.

Constructor Injection

1. This is the most common DI.
2. Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when instantiating that class.
3. Injected component can be used anywhere within the class.
4. Should be used when the injected dependency is required for the class to function.
5. It addresses the most common scenario where a class requires one or more dependencies.

     public interface IService  
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
//To Do: Some Stuff
}
}
public class Client
{
private IService _service;
public Client(IService service)
{
this._service = service;
}
public void Start()
{
Console.WriteLine("Service Started");
this._service.Serve();
//To Do: Some Stuff
}
}
class Program
{
static void Main(string[] args)
{
Client client = new Client(new Service());
client.Start();
Console.ReadKey();
}
}

The Injection happens in the constructor, by passing the Service that implements the IService-Interface. The dependencies are assembled by a “Builder” and Builder responsibilities are as follows:

1. Knowing the types of each IService
2. According to the request, feed the abstract IService to the Client

Design Patterns

What is Design Patterns ? and Some Basic Design Patterns.

Design patterns are represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution.

The following are some of the most common design patterns.

  • Presentation Logic
    • Model-View-Controller (MVC)
    • Model-View-Presenter (MVP)
    • Use Case Controller
  • Host or Behavioral
    • Command
    • Publish-Subscribe / Observer
    • Plug-in / Module / Intercepting Filter
  • Structural
    • Service Agent / Proxy / Broker
    • Provider / Adapter
  • Creational
    • Factory / Builder / Injection
    • Singleton
  • Persistence
    • Repository
MongoDB

Set Up MongoDB on Windows

Download a ZIP file containing the appropriate version of MongoDB from MongoDB.org.

Install MongoDB for Windows
In Windows Explorer, locate the downloaded MongoDB .msi file and double click .msi  file. By  default it will installed MongoDB to C:\mongodb.

Setup MongoDB environment
MongoDB requires a data directory to store all data. MongoDB’s default data directory path is C:\MongoDB\data\db. Create folder using Command Prompt.
Command :- md \data\db

Start MongoDB
To start MongoDB, run mongod.exe. For example, from the Command Prompt.
Command :- C:\mongodb\bin\mongod.exe

Connect to MongoDB
You should see output something like the following:

 C:\mongodb\bin\mongod –dbpath c:\mongodb\data\db    
Thu Oct 01 08:27:43.083 [initandlisten] MongoDB starting : pid=8608 port=27017 dbpath=c:\mongodb\data\db 64-bit host=s2ua3031x9m
Thu Oct 01 08:27:43.084 [initandlisten] db version v2.4.8
Thu Oct 01 08:27:43.084 [initandlisten] git version: a350fc38922fbda2cec8d5dd842237b904eafc14
Thu Oct 01 08:27:43.085 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack=’Service Pack 1′) BOOST_LIB_VERSION=1_49
Thu Oct 01 08:27:43.085 [initandlisten] allocator: system
Thu Oct 01 08:27:43.085 [initandlisten] options: { dbpath: "c:\mongodb\data\db"}
Thu Oct 01 08:27:43.122 [initandlisten] journal dir=c:\mongodb\data\db\journal
Thu Oct 01 08:27:43.123 [initandlisten] recover : no journal files present, no recovery needed
Thu Oct 01 08:27:43.206 [FileAllocator] allocating new datafile c:\mongodb\data\db\local.ns, filling with zeroes…
Thu Oct 01 08:27:43.207 [FileAllocator] creating directory c:\mongodb\data\db\_tmp
Thu Oct 01 08:27:43.246 [FileAllocator] done allocating datafile c:\mongodb\data\db\local.ns, size: 16MB, took 0.037 secs
Thu Oct 01 08:27:43.247 [FileAllocator] allocating new datafile c:\mongodb\data\db\local.0, filling with zeroes…
Thu Oct 01 08:27:43.373 [FileAllocator] done allocating datafile c:\mongodb\data\db\local.0, size: 64MB, took 0.125 secs
Thu Oct 01 08:27:43.374 [initandlisten] command local.$cmd command: { create: "startup_log", size: 10485760, capped: true } ntoreturn:1 keyUpdates:0 reslen:37 167ms
Thu Oct 01 08:27:43.375 [initandlisten] waiting for connections on port 27017
Thu Oct 01 08:27:43.375 [websvr] admin web console waiting for connections on port 28017

To verify that you can connect to the new MongoDB server, open a second command window and execute c:\mongodb\bin\mongo.