.Net, Design Patterns

Abstract Factory Pattern in C#

Introduction

According to Wikipedia:

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

According to Gang Of Four:

Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime.

UML:

677px-Abstract_factory_UML.svg

When to use it?

  • When the system is independent on how the objects are created.
  • When the system should work with multiple families of product.
  • When an interface is required to create similar family products, not the implementation.

Why to use it?

  • Provides an interface for creating objects which are related or dependent objects without specifying concrete classes
  • Calling code works with abstract interface and classes and does not need to know the exact types of the objects created by the factory

The main players in the pattern are:

  • AbstractFactory – declares a interface for operations that create abstract products.
  • ConcreteFactory – implements operations to create concrete products.
  • AbstractProduct – declares an interface for a type of product objects.
  • Product – defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface.
  • Client – uses the interfaces declared by the AbstractFactory and AbstractProduct classes.

Example in C#

ComputerFactory.cs (Abstract Factory)


namespace DesignPatterns.AbstractPattern {
abstract class ComputerFactory {
public abstract Computer GetComputer();

}//ComputerFactory
}

ConcreteComputerFactory.cs (ConcreteFactory)


namespace DesignPatterns.AbstractPattern {
class ConcreteComputerFactory : ComputerFactory {

public override Computer GetComputer() {

return new ConcreteComputer();

}//GetComputer

}//ConcreteComputerFactory
}

Computer.cs (Abstract Product)


namespace DesignPatterns.AbstractPattern {
abstract class Computer {

public abstract int Mhz { get; }

}//Computer
}

ConcreteComputer.cs (Product)


namespace DesignPatterns.AbstractPattern {
class ConcreteComputer : Computer {

int _mhz = 500;

public override int Mhz{
get { return _mhz; }
}//Mhz

}//ConcreteComputer
}

Client Code


using System;

namespace DesignPatterns.AbstractPattern {
class AbstractFactoryPatternClient : IDesignPattern {
public void Run() {
Console.WriteLine("\n------------------Abstract Factory Pattern------------------");
ComputerFactory factory = new ConcreteComputerFactory();

new ComputerAssembler().AssembleComputer(factory);
}
}
}

ComputerAssembler.cs


using System;

namespace DesignPatterns.AbstractPattern {
class ComputerAssembler {
public void AssembleComputer(ComputerFactory factory) {

Computer computer = factory.GetComputer();
Console.WriteLine("Assembled a {0} running at {1} MHz",
computer.GetType().FullName, computer.Mhz);

}//AssembleComputer
}
}

Output:

Assembled a DesignPatterns.AbstractPattern.ConcreteComputer running at 500 MHz

So whats happening here?

If you see the client code its passing an Abstract factory to the ComputerAssembler class and this class has a public method AssembleComputer which takes the Abstract factory class and calls the exposed public method of that factory.

So good thing here is that the AssembleComputer does not care about any specific object but it can support any type of ComputerFatcory which in this example its the ConcreteComputerFacory which implements ComputerFactory; and then it calls the GetComputerMethod which returns a concrete computer which implements Computer abstract class, which again decouples it from any concrete class.

Basically idea is to decouple the implementation logic to any specific concrete class, in this way every concrete class will have an common interface to implement and the client can call any method of the Product without worrying the exact object type.

Code can be found at GitHub

Reference:

 

 

.Net, Design Patterns

Design Patterns using C#

My notes on various design patterns from the book of Gang of Four (Design Patterns – Elements of Reusable Object Oriented Software). Sharing so that others also could benefit from this.

Creational Patterns

  • Prototype Pattern: The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. Read the article
  • Abstract Factory Pattern: This pattern is used when creating families of related or dependent objects without specifying their concrete classes by using a common interface. Read the article
.Net, Software Architecture

Prototype Pattern using C#

Introduction

According to Wikipedia:

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.

According to Gang Of Four:

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

UML:

600px-Prototype_UML.svg

When to use it?

  1. To avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.
  2. Hide concrete classes from the client.
  3. Add and remove new classes (via prototypes) at runtime.
  4. Keep the number of classes in the system to a minimum.
  5. Adapt to changing structures of data at runtime.

The main players in the pattern are:

IPrototype
Defines the interface that says prototypes must be cloneable

Prototype
A class with cloning capabilities

PrototypeManager
Maintains a list of clone types and their keys

Client
Adds prototypes to the list and requests clones

Example in C#

PrototypeBase.cs

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public abstract class PrototypeBase<T> {

// Shallow clone
public T Clone() {
return (T)this.MemberwiseClone();
}

//Deep Clone
public T DeepClone() {
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T)formatter.Deserialize(stream);
stream.Close();
return copy;
}
}
}

Prototype.cs

using System;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public class Prototype : PrototypeBase<Prototype> {
// Content members
public string Country { get; set; }
public string Capital { get; set; }
public DeeperData Language { get; set; }

public Prototype(string country, string capital, string language) {
Country = country;
Capital = capital;
Language = new DeeperData(language);
}

public override string ToString() {
return Country + "\t\t" + Capital + "\t\t->" + Language;
}
}
}

DeeperData.cs

using System;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public class DeeperData {
public string Data { get; set; }
public DeeperData(string s) {
Data = s;
}
public override string ToString() {
return Data;
}
}
}

PrototypeManager.cs

using System.Collections.Generic;

namespace DesignPatterns.PrototypePattern {
public class PrototypeManager {
public Dictionary<string, Prototype> prototypes
= new Dictionary<string, Prototype> {
{"Germany",
new Prototype("Germany", "Berlin", "German")},
{"Italy",
new Prototype("Italy", "Rome", "Italian")},
{"Australia",
new Prototype("Australia", "Canberra", "English")}
};
}
}

PrototypeClient.cs

using System;

namespace DesignPatterns.PrototypePattern {
public class PrototypeClient : IDesignPattern {

private void Report(string s, Prototype a, Prototype b) {
Console.WriteLine("\n" + s);
Console.WriteLine("Prototype " + a + "\nClone      " + b);
}

public void Run() {
Console.WriteLine("\n------------------Prototype Pattern------------------");
PrototypeManager manager = new PrototypeManager();
Prototype c2, c3;

// Make a copy of Australia's data
c2 = manager.prototypes["Australia"].Clone();
Report("Shallow cloning Australia\n===============",
manager.prototypes["Australia"], c2);

// Change the capital of Australia to Sydney
c2.Capital = "Sydney";
Report("Altered Clone's shallow state, prototype unaffected",
manager.prototypes["Australia"], c2);

// Change the language of Australia (deep data)
c2.Language.Data = "Chinese";
Report("Altering Clone deep state: prototype affected *****",
manager.prototypes["Australia"], c2);

// Make a copy of Germany's data
c3 = manager.prototypes["Germany"].DeepClone();
Report("Deep cloning Germany\n============",
manager.prototypes["Germany"], c3);

// Change the capital of Germany
c3.Capital = "Munich";
Report("Altering Clone shallow state, prototype unaffected",
manager.prototypes["Germany"], c3);

// Change the language of Germany (deep data)
c3.Language.Data = "Turkish";
Report("Altering Clone deep state, prototype unaffected",
manager.prototypes["Germany"], c3);
}
}
}

Output:

Shallow cloning Australia
===============
Prototype Australia             Canberra                ->English
Clone      Australia            Canberra                ->English

Altered Clone’s shallow state, prototype unaffected
Prototype Australia             Canberra                ->English
Clone      Australia            Sydney          ->English

Altering Clone deep state: prototype affected *****
Prototype Australia             Canberra                ->Chinese
Clone      Australia            Sydney          ->Chinese

Deep cloning Germany
============
Prototype Germany               Berlin          ->German
Clone      Germany              Berlin          ->German

Altering Clone shallow state, prototype unaffected
Prototype Germany               Berlin          ->German
Clone      Germany              Munich          ->German

Altering Clone deep state, prototype unaffected
Prototype Germany               Berlin          ->German
Clone      Germany              Munich          ->Turkish

So whats happening here?

Firstly we are using two ways to clone the object

  1. Shallow Clone: In .Net we have a method called MemberwiseClone, its a method that is available on all objects. It copies the values of all fields and any references, and returns a reference to this copy. However, it does not copy what the references in the object point to.Many objects are simple, without references to other objects, and therefore shallow copies are adequate.To preserve the complete value of the object, including all its subobjects use a deep copy.
  2. Deep Clone: An alternative is a deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B. The result is different from the result a shallow copy gives in that the objects referenced by the copy B are distinct from those referenced by A, and independent. Deep copies are more expensive, due to needing to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph. In the .NET Framework they are encapsulated in a process called serialization, which can be defined by using attribute [Serializable] on the class to be serialized. Objects are copied to a given destination and can be brought back again at will. The options for serialization destinations are several, including disks and the Internet, but the easiest one for serializing smallish objects is memory itself. Thus a deep copy consists of serializing and deserializing in one method.

Then we are also using a PrototypeManager, which I mentioned earlier that its used to maintains a list of clone types and their keys so that we can retrieve an already cloned object quickly.

The main program consists of a series of experiments demonstrating the effects of cloning and deep copying.

In the first group, Australia is shallow copied. After changing of Australia’s clone, the capital is Canberra in the prototype and Sydney in the clone. The statement responsible is   c2.Capital = “Sydney”;

however, changing the language to Chinese (  c2.Language.Data = “Chinese”;) also changes the prototype’s language to Chinese. That is not what we wanted. We got the error because we did a shallow copy and the language in the prototype and in the clone reference the same DeeperData object.

In the next experiment, we clone Germany using a deep copy ( c3 = manager.prototypes[“Germany”].DeepClone();).

Now changing the capital ( c3.Capital = “Munich”;) does not affect the prototype but the deep clone is affected. Similarily  altering the deep state-its language to Turkish ( c3.Language.Data = “Turkish”;), shows the prototype after the changes; it is unaffected.

That’s all about Prototype Pattern.

Code can be found at GitHub

Reference:

 

.Net

Sharing the code between multiple exceptions

Today I had a situation where I wanted to do same opertation in case of different exceptions. I came up with something simple

Here is the situation:

try{
  // Exception throwing code
}catch(MongoConnectionException ex){
  // Some code here
}catch(IOException ex){
  // Some code here
}catch(SocketException ex){
  // Some code here
}

Now this looks already quite ugly. Not for you? Ok then its ugly for me 🙂

So what I did some may consider it even more ugly but I can atleast share the code

I did it so that

try{
  // Exception throwing code
}catch(Exception ex){
  if(ex is MongoConnectionException || ex is IOException || ex is SocketConnection){
    // Do some specific logic or setting of state for these type of exceptions
}
  // Do some common logic here
}

If you find some problem in doing this please let me know so that I can fix my code as well 🙂 But this reduced my code.

Thanks

.Net, Azure

Integrating SSL to Azure Websites

freessl

So after very very long I have finally got some time to share something. Today I will share how to integrate SSL with Azure Website; trust me it can be a bit of pain to get this working specially if you are quite new to this. So in this article I will explain it with all pictures; which I feel is the best way to explain or learn.

So to try this two things is a must.

  • You should have a registered domain. Do not use *.azurewebsites.net for registering SSL since almighty Microsoft provides the SSL support for azurewebsites.net domain. So if you are planning to use *azurewebsites.net then you do not need to have a seperate SSL certificate.
  • The SSL Provider we are going to use here i.e RapidSSL send a mail to the domain administrator mail id which is actually a set of email id’s which RapidSSL support. Here is the list of all supported email id’s (admin@yourdomain.com,administrator@yourdomain.com,
    hostmaster@yourdomain.com,webmaster@yourdomain.com,
    postmaster@yourdomain.com)

Ok Lets get started not.

First go to the URL www.freessl.com and click on TRY button to try with freessl or you are quite sure to buy it then just buy. I will use the free version which is valid for 1month.

Now on clicking on the TRY button you will get series of forms to be filled for which I have attached the screenshots.

freessl_pop1

freessl_pop2

freessl_csr

Now this is the point we need to generate the CSR (Certificate Signing Request). We can do it using IIS Manager or OpenSSL as well. But lets use IIS though we would openssl in later stage but for this purpose lets use IIS Manager.

So press start in windows OS and then type IIS; and you will get IIS Manager. If you do not find it then go to Control Panel -> Program Features -> Turn windows features on or off.

So if you find the IIS manager then you just follow these snapshots

iis_open_feature

iis_create_cert_dialog1

iis_create_cert_dialog2

iis_create_cert_dialog3

Now after you have save this file. Open this file in the Notepad and copy the content and paste it to the freessl website ; here

freessl_csr

Now after pressing the submit you follow these

freessl_continue1

freessl_continue2

freessl_continue_domain_approver

freessl_orderno

After this you should get a mail on the Domain email id you have selected after clicking the link provided on that you should get your CSR to the registered email address. And if you look at the end of the mail you will see the Web Server certificate. Copy that and save it as myserver.crt. Now right click on this file and press install certificate.

Now we need to generate the .pfx file which is needed to be uploaded to the azure. So lets do that.

First lets get the private key; which we get from teh CSR request we made

On the start serach mmc.exe then File -> Add/Remove SnapIn; select Certificates and then Local Computer.

Now go to folder level Personal -> Certificates and you should find the certificate www.whynotme.com.

Click on next and select yes then again next and select to PKCS #12. and then the location of the file and save it as file name privatekey.pfx

Now we need to generate a .pfx file which is password protected and accepted by Azure website. So lets use OpenSSL to generate this.

We need 3 files for this

  1. Private Key file
  2. Web Server Cert from RapidSSL
  3. Intermediate or Chain Cert as bundle which you can get it here and save it as Intermediate.pem

Now we have the private key as .pfx file but we need .key file to generate the final .pfx file. So lets extract the .key file from privatekey.pfx.

You can get the Open SSL installer from here. INstall it in C:\openssl drive with all its binaries. Open command prompt and type the following

set OPENSSL_CONF=c:\OpenSSL-Win64\bin\openssl.cfg

And to generate the .key file

C:\>.\OpenSSL-Win64\bin\openssl.exe pkcs12 -in privatekey.pfx -nocerts -out privatekey.pem

C:\>.\OpenSSL-Win64\bin\openssl.exe rsa -in privatekey.pem -out private.key

Now we have all the files lets generate the final .pfx file which should be uploded to Azure by just running the following command

C:\>.\OpenSSL-Win64\bin\openssl.exe pkcs12 -export -out whynotme_ssl.pfx -inkey private.key -in myserver.crt -certfile intermediate.pem

So the final file which should be uploaded is whynotme_ssl.pfx

Go to your azure website -> Configure; search for Upload Certificate.

ssluploadcert

ssluploaddlg

In the ssl bindings section of the CONFIGURE tab, use the dropdowns to select the domain name to secure with SSL, and the certificate to use. You may also select whether to use Server Name Indication (SNI) or IP based SSL.

sslbindings

  • IP based SSL associates a certificate with a domain name by mapping the dedicated public IP address of the server to the domain name. This requires each domain name (contoso.com, fabricam.com, etc.) associated with your service to have a dedicated IP address. This is the traditional method of associating SSL certificates with a web server.
  • SNI based SSL is an extension to SSL and Transport Layer Security (TLS) that allows multiple domains to share the same IP address, with separate security certificates for each domain. Most modern browsers (including Internet Explorer, Chrome, Firefox and Opera) support SNI, however older browsers may not support SNI. For more information on SNI, see the Server Name Indication article on Wikipedia

Click Save to save the changes and enable SSL.

Thats it. Now try https://yourdomain.com

Hope it works for you as it worked for me. Please leave a comment good or bad or improvements all are appreciated.

Reference : Enable HTTPS for an Azure web site

.Net

C# + REPL + Scripting -> Life is Good

cshell_logo

Alright this time I have again made my life a bit easy by finding a solution for problem where I want to test a library but I do not want to create .Net Solution using VS and then type class and all those. Since I want to just test the working of an API so I do not want to go soo long. Someone will say then use IronRuby and do it; but then we do not get Syntax Highlighting, Code completion, intellisense and etc. (productivity enhancing tools).

So I get this nice tool called CSHELL; its a REPL for C# script (isn’t that cool).

So let me show you how I have experimented this tool by solving one of my simple issue.

Problem Description:

          As you all know we in Platform team working on DB renewal stuff and we often need to check various different Databases and their functionality. This time I wanted to check Couchbase’s functionality on How to get the list of buckets in a default pool. Terminologies may be confusing for some who does not understand about Couchbase but in simple term Bucket is a collection of JSON documents.

Steps:

1) Run cshell -> Download it from here. It is just an .exe so you can just run it. (Tips: Better to pin it up with the Taskbar for easy access);

2) You will see this main window.

CShell Main Window

3) Now I want to have the reference to Couchbase .Net SDK.

CShell Referencing DLL

4) Select the required ones

CShell Referencing DLL

5) Now I have written the statement in the script to check the problem which I described earlier. So here is the snapshot of it:

CShell Intellisense

You see I get the intellisense. isn’t that nice? And if you see a bit above that I was using a class without the reference (that too two time (tongue)) and it gives me a colourful error . That’s neat.

CShell Linq Intellisense

Intellisense with LINQ as well. Nice!!

And finally I get the result which I want.

CShell Final Result

That’s it. It took me just 5 mins to do this. Time creating this blog post is not counted 

More info you can find in http://cshell.net/.

Please share if you find something useful as well or something which does not work. Its a good way to use C# as a scripting language. 

Thanks