Search This Blog

Thursday, 10 December 2015

Factory Method pattern

In Factory Method pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.



C# - Implementation Code

    interface Product
    {
    
    }
    
    class ConcreteProductA : Product
    {
    }
    
    class ConcreteProductB : Product
    {
    }
    
    abstract class Creator
    {
     public abstract Product FactoryMethod(string type);
    }
    
    class ConcreteCreator : Creator
    {
     public override Product FactoryMethod(string type)
     {
     switch (type)
     {
     case "A": return new ConcreteProductA();
     case "B": return new ConcreteProductB();
     default: throw new ArgumentException("Invalid type", "type");
     }
     }
    }

***************************************************************************************************************
Another C# - Implementation for FactoryMethod design pattern:

interface IIceCream


{


    string Functionality();


}


class ChocolateIceCream : IIceCream


{


    public string Functionality()


    {


        return "Chocolate Ice cream";


    }


}


class VanillaIceCream : IIceCream


{


    public string Functionality()


    {


        return "Vanilla Ice cream";


    }


}


class StrawberryIceCream : IIceCream { public string Functionality()


    {


        return "Strawberry Ice cream";


    }


}

This is the basic structure
of our program. Now we need to implement the "Factory Method", which
will create the instance of our desired ice-cream at run-time. So we
will create this method now.

This is how I’m going to do this.



static class Factory


{


   /// <summary>    /// This is the Factory method   

/// </summary>   

public static IIceCream Get(int id)


   {


       switch (id)


       {


           case 0:


                return new ChocolateIceCream();


           case 1:


                return new VanillaIceCream();


           case 2:


                return new StrawberryIceCream(); default:


                return null;


        }
   }
}



The Repository Pattern

The Repository Pattern

Context

In many applications, the business logic accesses data from data stores such as databases, SharePoint lists, or Web services. Directly accessing the data can result in the following:
  • Duplicated code
  • A higher potential for programming errors
  • Weak typing of the business data
  • Difficulty in centralizing data-related policies such as caching
  • An inability to easily test the business logic in isolation from external dependencies

Objectives

Use the Repository pattern to achieve one or more of the following objectives:
  • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
  • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
  • You want to implement and centralize a caching strategy for the data source.
  • You want to improve the code's maintainability and readability by separating business logic from data or service access logic.
  • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
  • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
  • You want to apply a domain model to simplify complex business logic.

Solution

Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. For example, the data source layer can be a database, a SharePoint list, or a Web service.
The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.

Monday, 19 May 2014

Build Vs Rebuild Vs Clean

Build means compile and link only the source files that have changed since the last build.
If they have not changed those files will not be touched.

while Rebuild means compile and link all source files regardless of whether they changed or not.
Rebuild will build everything from scratch, irrespective of if there is code change in the file or not.
Rebuild solution will clean and then build the solution from scratch.
Rebuild = Clean + Build

Clean Solution will delete all compiled files (i.e., EXE’s and DLL’s) from the bin/obj directory

Monday, 5 May 2014

Custom exception in sql server

RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

RAISERROR (N'This is message %s %d.', -- Message text.
           10, -- Severity,
           1, -- State,
           N'number', -- First argument.
           5); -- Second argument.
-- The message text returned is: This is message number 5.
GO

Monday, 28 April 2014

Razor View Engine

The Razor View Engine

ASP.NET MVC 3 comes with a new view engine named Razor that offers the following benefits:
  • Razor syntax is clean and concise, requiring a minimum number of keystrokes.
  • Razor is easy to learn, in part because it's based on existing languages like C# and Visual Basic.
  • Visual Studio includes IntelliSense and code colorization for Razor syntax.
  • Razor views can be unit tested without requiring that you run the application or launch a web server.
Some new Razor features include the following:
  • @model syntax for specifying the type being passed to the view.
  • @* *@ comment syntax.
  • The ability to specify defaults (such as layoutpage) once for an entire site.
  • The Html.Raw method for displaying text without HTML-encoding it.
  • Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).
Razor also includes new HTML helpers, such as the following:
  • Chart. Renders a chart, offering the same features as the chart control in ASP.NET 4.
  • WebGrid. Renders a data grid, complete with paging and sorting functionality.
  • Crypto. Uses hashing algorithms to create properly salted and hashed passwords.
  • WebImage. Renders an image.
  • WebMail. Sends an email message.

Thursday, 24 April 2014

WCF Self Hosting

Windows Communication Foundation (WCF) is a programming interface as part of .NET Framework.
Using three types we can host service in WCF:
  1. Self-Hosting
  2. IIS Hosting
  3. WAS

1. What is Self Hosting

WCF comes with System.ServiceModel.ServiceHost class that makes you can host your services in your own application easily. With Self Hosting what you need to do is just configuring your service endpoint and calling the .open() method of ServiceHost. To host WCF service you need WCF runtime and .NET application where you want to host your service.

2. What are the advantages and Disadvantages of Self hosting

Advantages of Self Hosting:
  • It is Easy: This way of hosting don’t need many lines of code to successfully run.
  • It is Flexible: You can easily decide when your service active by calling the .open() and .close() method.
Disadvantage of Self Hosting
This self-hosting service is reachable only when the application that hosts the service is running. So, self-hosting is only suitable when the development and demonstration phase of your system.
There are two main advantages of using IIS over self-hosting:
  • Automatic activation
  • Process recycling

3. What is ServiceHost in Self Hosting

  • A Service Host basically provides you everything you need to host a WCF service in a non-IIS or WAS setting. A common place for a ServiceHost would be in a console app or Windows service.
  • You can either instantiate a Service-Host class yourself in a console app, a Windows service, or even a Win-forms app, and thus make your WCF service class available to the outside world or you can delegate that work to IIS or WAS.
  • Even IIS or WAS will use a ServiceHost to host your WCF service - they just do it automatically behind the scenes, and "on demand" - whenever a request for your WCF service comes in.

Calling WCF Services asynchronously using async and await

 

In my previous post, I covered how to use async and await keywords in C# 5 to create asynchronous methods. This post is a continuation of asynchronous programming, in which I will cover how to call WCF services from a client program using async and await.

Response of an application will be slower when it includes heavy weight operations like running complex queries against database, reading a piece of data from a file, calling a service to get some data or any remote operation. When such operations are performed synchronously, the application will be halted till the operation gets over. If we assign the slower operation to a separate task, the thread will be free to perform some other operation till the operation responds.

When a WCF service is called synchronously, the thread associated with the operation is idle till the response is obtained from the server. To avoid this in earlier versions of .NET framework (4.0 or earlier), we had an option to create asynchronous methods with an associated event. Using .NET 4.5, we can create task-based proxies while adding service reference to an application. This can be done using by clicking on the Advanced button in the Add Service Reference dialog.


To call a WCF service synchronously, you can simply use the proxy method created by the Visual Studio, similar to calling a local method.
  • To call a WCF service asynchronously, you will need to first create an "AsyncCallback" "delegate" and pass this delegate to the asynchronous proxy method generated by the Visual Studio. Since the "AsyncCallback" "delegate" is executed in a worker thread different from the UI thread, any access to the "UI elements" needs to be "Dispatched".
  • From the application point of view, either way has its advantages and disadvantages. For most applications, after the calling of a WCF service, the application will be in an intermediate state until the response from the service is received. During this time, it may be ideal to block the UI thread to prevent user actions to get into any un-predictable results. In this case, a synchronous call may be appropriate. In some other scenarios, particularly when we work on some "SOA" applications, we may need to make multiple service calls at the same time and let the services to work in parallel. In this case, asynchronous WCF calls will be the ideal.
  • One thing just came to my mind. To make an asynchronous call, you probably do not need to have the asynchronous proxies. You can well fork a worker thread by yourself and let the thread to do a synchronous call. You will achieve the same effect as using the asynchronous proxies.
  • If you are not familiar with WCF services, this link is a good place to get you started.