Factory Pattern

I had to use Factory pattern for one my mutual fund house project.The investment strategies includes buying funds as Lumpsum,SIP etc..and the funds which has be bought have options like Redeem,Purchase,Switch.This might not sound familiar if you are not from banking and finance domain,you can have a read over here.

Intention :

There are various Investment plans like SIP,LumpSum etc..and all investment plans has the following option (Purchase,Redeem,Switch).So Its clear that i would have an interface and classes below


public interface IFundOption

{

void Purchase();

void Redeem();

void Switch();

}

//Investment Plan

class Luupsum: IFundOption

{

public void Purchase()

{

//Do Purchase

}

public void Redeem()

{

//Do Redeem

}

public void Switch()

{

//Do Switch

}

}

class SIP : IFundOption

{

public void Purchase()

{

//Do Purchase

}

public void Redeem()

{

//Do Redeem

}

public void Switch()

{

//Do Switch

}

}

 

Problem  :

Given an investment plan as argument,i want to get the instance of investment plan and perform the various options like redeem,purchase etc..Typically i don’t want to write a switch case where i make a comparison based on investment plan and then initiate the class(against open closed principle). The goal is to write a method which accepts investment plan name and returns the instance of investment plan.


public investmentplaninstance   GetinstanceofInvesmentPlan(string investementplanname)

{

return investmentplaninstance ;// goal

}

This is where Factory Pattern comes in,You create a interface for creating object and let sub classes decide which class to initiate.

Factory Pattern :

1.Lets create a interface which is responsible for returning investmentplaninstance.


public interface IGetInvestmentPlanInstance

{

IFundOption CreateInvestmentPlanInstance(); //the instance should be used to create investment plan.

}

2. Lets create Managers (sub classes) which creates the instance of investment plan.


class SIPManager : IGetInvestmentPlanInstance

{

public IFundOption CreateInvestmentPlanInstance()

{

var sipinstance = new SIP(); //sip class implements IFundOption  interface.

return sipinstance;

}

}

class LumpsumManager : IGetInvestmentPlanInstance

{

public IFundOption CreateInvestmentPlanInstance()

{

var lumsuminstance = new Lumpsum(); //Lumpsum class implements IFundOption  interface.

return lumsuminstance ;

}

}

 

3. We have the managers who are ready to give the investment plan instance based on investment plan name.Typically we would put all manager class in settings file/config,and based on input,we create the manager instance based on reflection .


static IGetInvestmentPlanInstance GetManagerClass(string investmetpan)

{

var getmanager = _dictionary.Key(investmentplan);

return Assembly.GetExecutingAssembly.CreateInstance(getmanager) as IGetInvestmentPlanInstance ;

}

[/csharp]

we would make use of this manager class and get the instance of investment plan as below,



var getmanager = GetManagerClass("SIPManager ");

IFundOption options = getmanager.CreateInvestmentPlanInstance();

options.Purchase();

options.Redeem();

 

 

 

#Redis Cache in Azure-MVC

What is Redis Cache and Why do we need to move cache into separate server?

1.If you have a enterprise web application which is responsible for serving several thousand of request,it is advisable that you maintain a separate server for maintaining the cache,so that your cache does not eats up your server memory.(Azure)

2.Traditional Cache can operate only on Key/Value Pair,where as Redis Cache you have built-in data types like string,hash,list.It is more of a useful library which has several custom function which can be used over cache.

Creating an Sample Redis Cache Service in Azure.

1.Setting up Redis Service in Azure:

This is pretty easy one. You would need the Primary Connection String,make sure you add it to the web config of your file.

Capture

 

2.Setting up connection for your project.

1.Copy the Connection String from the Portal and add it to your web config

2.Make use of ConnectionMultiplexer class provided by .Net for connecting to the redis cache.


public class CacheInstance
{
private static ConnectionMultiplexer _connection;

public CacheInstance()
{
var constring = ConfigurationManager.ConnectionStrings["RedisCache"].ConnectionString;
_connection = ConnectionMultiplexer.Connect(constring);
}

public void PutItem(String Key,String Value)
{
IDatabase cache = _connection.GetDatabase();
cache.StringSet(Key,Value);
}

public String GetItem(String Key)
{
IDatabase cache = _connection.GetDatabase();
string redisValue = cache.StringGet(Key);
return redisValue;
}
}

In the above sample,i have created two sample methods Put and GetItem which would add and retrieve items from cache.

3.Using  Redis Cache in your Application.

This is Sample controller which makes use of redis cache in Azure,this application will cache the time when it first runs and will never update the time from then.


public class HomeController : Controller
{
public ActionResult Index()
{
var cache = new CacheInstance();

var res = cache.GetItem("Datetime");
if (String.IsNullOrEmpty(res))
{
cache.PutItem("Datetime",DateTime.Now.ToString());
}
return Content(res);
}
}

In the web page you can see that time is cached and never updated.

Capture

and here is the proof that we are hitting the azure redis cache,

Capture.JPG

 

 

 

 

HttpHanlder Vs HttpModule

HttpHandler: 

1.They are process which run when a request is made by client. Handlers include extension like (.aspx,.ashx).

2.We can implement custom Handler by implementing IHttpHanlder (ProcessRequest and IsReusable method)

Life cycle of HTTPHandler is only till the request is made.

HTTPModule : 

1.They are events which can be used even before page load /request is made to the server. 2.HTTP Module can be used for the entire life cycle of MVC where as HTTPHandler is valid only for handling request.

3.We can implement custom Module by implementing IHTTPModule(Init and Dispose Methods)

 

 

#Content Type vs Accept in Request Header

Accept : Tells the server  what the media type client needs as response.

“Accept”: text/html —Client expects the response as text/html.

Content-Type : Tells the server what media type the client sends when making a request.This is useful for server so that it can parse the request accordingly.

“Content-Type” :application/json –Client tells the server that it sending input as json.

 

#Content Negotiation in Web API?

A client might send a request with multiple media types in header

<pre class="prettyprint prettyprinted"><span class="pln">GET http</span><span class="pun">:</span><span class="com">//localhost.:21069/api/products/1 HTTP/1.1</span>
<span class="typ">Host</span><span class="pun">:</span><span class="pln"> localhost</span><span class="pun">.:</span><span class="lit">21069</span>
<span class="typ">Accept</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">,</span><span class="pln"> text</span><span class="pun">/</span><span class="pln">javascript</span><span class="pun">,</span> <span class="pun">*</span><span class="com">/*; q=0.01</span></pre>

Accept : Tells the server whats the client want as response.

In the above case client tells,it is comfortable with josn,xml or any type.

The server response with

<pre class="prettyprint prettyprinted"><span class="pln">HTTP</span><span class="pun">/</span><span class="lit">1.1</span> <span class="lit">200</span><span class="pln"> OK
</span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">;</span><span class="pln"> charset</span><span class="pun">=</span><span class="pln">utf</span><span class="pun">-</span><span class="lit">8</span>
<span class="typ">Content</span><span class="pun">-</span><span class="typ">Length</span><span class="pun">:</span> <span class="lit">57</span>
<span class="typ">Connection</span><span class="pun">:</span> <span class="typ">Close</span>

<span class="pun">{</span><span class="str">"Id"</span><span class="pun">:</span><span class="lit">1</span><span class="pun">,</span><span class="str">"Name"</span><span class="pun">:</span><span class="str">"Gizmo"</span><span class="pun">,</span><span class="str">"Category"</span><span class="pun">:</span><span class="str">"Widgets"</span><span class="pun">,</span><span class="str">"Price"</span><span class="pun">:</span><span class="lit">1.99</span><span class="pun">}</span></pre>

The server makes a choice of its own of 3 types and returned the json in first place.

The process of deciding the content type between the server and client is called content -negotiation.

 

 

#Web API-Custom MediaTypeFormatters

1.You can create custom MediaTypeFormatter by inheriting abstract   BufferedMediaTypeFormatter. 

2.To add it to your web api,make changes in HttpConfiuration in Startup.cs

<pre class="prettyprint prettyprinted"><span class="pln"> config</span><span class="pun">.</span><span class="typ">Formatters</span><span class="pun">.</span><span class="typ">Add</span><span class="pun">(</span><span class="kwd">new</span> CustomFormat <span class="pun">());</span> 
</pre>

3. BufferedMediaTypeWritters  has two methods WriteToStream(write in custom format(Serialize)) and ReadFromStream(read the custom format(deserialize)).


public class CustomFormat :BufferedMediaTypeFormatter
{
public CustomFormat()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
}
public override bool CanReadType(Type type)
{
throw new NotImplementedException();
}

public override bool CanWriteType(Type type)
{
throw new NotImplementedException();
}
}

# Linq To Entities DBFunctions and SqlFunctions

When using linq to sql queries,few functions like DateTime Comparison,FirstorDefault would not work and you would end up getting exception “LinqtoEntities is not supported by this function”.

Problem:

For instance I was trying to compare a column of Date-time type with today’s date,I had issue when comparing it since the sql server Date-Time type was of (yyyy-mm-dd) and today’s date was of (mm-dd-yyyy),I was not able to use ToString method to format date since linq to entities  did not support it.

Solution:

LinqToEntities provides DBFunction and SqlFunction for sql related operations.It has got several methods like DateAdd,DatePart,TruncateTime etc…I had used the same to compare dates.


var somequery = from f in mytable where DbFunction.TruncateTime (f.mydatecolumn) == Dbfunction.TruncateTime(SqlFunction.GetDate())

 

 

# What is REST ?

Rest(Representational State Transfer)  is recommended style/suggested pattern  which is recommend for web applications.

A System which is Restful  is  expected to meet the five principles listed below :

1.System must be represented as resource.

2.Uniform Interface (Usage of GET,POST,PUT,DELETE ) is advised to be used across the system.

3. Identify Resource by a Unique Identifier.

4. Communication via Representation (represent data by JSON/XML etc..)

5. Stateless.

# Web API : HTTP VERBS PUT VS POST

We would be aware  that both Put and Post could do both insert and update operation.However we must follow certain standard and choose either of  one verb based on scenario.

Use POST :

1.If  the insert is going to create a new resource/identifier than use POST.

2.Post is not idempotent.

what is Idempotent ?

Idempotent :  Let’s assume we are sending a  request to server with post method  “/create/1” .If we send  multiple request,it would have side effects like creating the resource twice. This might not be the desired output. Other verbs like GET,PUT are Idempotent. If we make a request to server with GET Methods ” /GET/1″ multiple times,it will yield the same result and the same with PUT  “/PUT/1”,it will only update  existing record.

 

POST /resources HTTP/1.1
The post will create new resource
/resources/newresource/

 

Use PUT :

1. If insert or update has to be performed based on existing resource .

2.Put is idempotent.

PUT /resource/<perform operation on existing_resource> 

//Update Resource or create related resource if not existing.

 

 

 

 

#Routing Constraint

Route Constraint : Restrict browser request that matches route value based on constraints.

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints : new {id = @"\d"} // Constraint
);

The above constraint allows only integer to be passed,if a string is passed you
would get “No Resource Found“.If constraint is not handled,the page would have
throwed exception saying String could not be converted to string.thus constraint
also helps to hide sensitive information to client.