Showing posts with label Software Patterns. Show all posts
Showing posts with label Software Patterns. Show all posts

Monday, January 5, 2015

Abstract Classes Vs Interfaces in .Net


What is preferable? To create Abstract base classes to inherit from? Or to design Interfaces to implement them in other objects?
While it is up to the characteristics of your application project to decide whether to design interfaces or abstract classes, there are some very important points to have clear before you start developing your software.
Essentially, an Interface is just an empty contract, while an Abstract Class is really a plain standard class, but containing at least one abstract member. An Abstract Class can contain indexers, constants, fields, properties and plenty functional methods.
First, let's see some examples of abstract inheritance and some of interfaces implementation.
The following graph represents an inheritance chain from abstract classes :
The abstract classes can have its own inner functionality and concrete methods, as you can see in the following code:


abstract class Parent
{
   public
abstract void DoIt();
}


This is an abstract base class, no functionality. And this other one is also abstract, but inherits from the former, and owns some behavior:

abstract class Base : Parent
{
  protected Parent component;

  public void Setup(Parent component)
  {
    this.component = component;
  }
  public override void DoIt()
  {
    if (component != null)
    {
      component.DoIt();
    }
  }
}



This last one inherits from the abstract class:

class Child : Base 
{
  public override void DoIt()
  {
    base.DoIt();
    ExtendedFunctionality();
    Console.WriteLine("You are at 
Child .DoIt()");
  }

  void 
ExtendedFunctionality()
  {
    // TODO
  }
}

Interfaces are just empty contracts:

interface IContract
{
void DoIt();
}

class SomeClass : IContract
{
   public void DoIt()
  {
     // TODO
  }
}



I have summarized in this table the main differences between interfaces and abstract classes:


Characteristics
Interfaces
Abstract Classes
Definition
Empty contract
Class with at least one abstract member
Functionality
No: just empty methods
Yes : all kind of class behavior
Access modifiers
No : all public
As you wish
Relevance
Adds secondary functionality to a class
Intended to be used as Base or Core Class
Performance
Wastes time searching the appropriate method
Fast
Properties
Yes : always empty
Yes
Constants, Fields & Indexes
No
Yes
Multiple Inheritance
Yes: a class can implement several interfaces
No: a class can have only one base class
Versioning
        Not recommended
             Straightforward



Important:
Before you start building some project or application take into account the versioning problem: if after you deployed the software, it happens to be that you must add new behavior to an interface (adding a new method to an existing interface), the whole application will cease working, because at compile time the classes which implement the interface will incur in error while lacking the new method's implementation.
However, if you add a new method to an abstract base class, the application will keep running, because the child classes do not have to implement the method necessarily. It can remain unimplemented until you want.


Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן

Saturday, August 16, 2014

Building Blocks - Gang of Four Decorator Pattern Simple Sample


A Decorator class is a class that extends the functionality of another class at run-time without inheriting it :  is one of the 23 software patterns researched by the Gang of Four in their 1995 classic book. The Decorator Pattern become really useful in an MVC application, when you want to add functionality to many classes , respecting the Open-Closed Software Principle, therefore without touching any existing code.
The Open-Closed Principle, stated by Meyer in 1988, specifies that any class once completed, could only be modified in order to fix errors, but any new or appended functionality would require an extension new class to be created.This pattern allows you to create absolutely loosely-coupled relationships between classes, since it works without the standard inheritance mechanism known as "sub-classing" : instead of extending functionality at compile time through a sub-class, the Decorator wraps another objects at a runtime dynamic basis.
This pattern is materialized using interfaces or abstract classes. In this example, we'll use an abstract class, because it will be preferable in real world applications (see this article comparing interfaces vs abstract classes).

The following lines contain the code for the Decorator. Just use it as a bootstrap in your Model's classes :

Suppose you have this given parent-child classes to be extended with a Decorator:

abstract class Parent
{
   public abstract void DoIt();
}


class Child : Parent
{
  public override void DoIt()
  {
    Console.WriteLine("You are at 
Child .DoIt()");
  }
}


And when called, the output will be :

Child child = new Child();
child.DoIt();

You are at Child .DoIt()

Step #1 : Create an abstract Decorator class:


abstract class DecoratorBase : Parent
{
  protected Parent component;

  public void Setup(Parent component)
  {
    this.component = component;
  }
  public override void DoIt()
  {
    if (component != null)
    {
      component.DoIt();
    }
  }
}

The abstract base decorator wraps the old class as a component, and overrides the methods to extend , simultaneously respecting the old functionality.

Step #2 : Create as many Decorators as you wish : 


class Decorator1 : 
DecoratorBase 
{
  public override void DoIt()
  {
    base.DoIt();
    ExtendedFunctionality();
    Console.WriteLine("You are at 
Decorator1 .DoIt()");
  }

  void 
ExtendedFunctionality()
  {
    // TODO
  }
}

The functional decorator does two things:
1) calls the method's base of the old class (through the abstract decorator)
2) adds new behavior to the old functionality 
Thus , the old class is now a component of the decorator. 

Call & output:

Child child = new Child();
Decorator1 dec1 = new 
Decorator1 ();

dec1.Setup(child);
dec1.DoIt();

You are at Child.DoIt()
You are at Decorator1 .DoIt()

Yet another Decorator :

class Decorator2 : DecoratorBase 
{
  public override void DoIt()
  {
    base.DoIt();
    ExtendedFunctionality();
    Console.WriteLine("You are at 
Decorator2 .DoIt()");
  }

  void 
ExtendedFunctionality()
  {
    // TODO
  }
}

Call and output:

Child child = new Child();
Decorator1 dec1 = new 
Decorator1 ();Decorator2 dec2 = new Decorator2 ();
dec1.Setup(child);

dec2.Setup(dec1);
dec2.DoIt();





You are at Child.DoIt()
You are at Decorator1.DoIt()

You are at Decorator2 .DoIt()



That means, with this design pattern we can not just decorate twice an old class, but also decorate another decorator, which now becomes a component of a newer decorator class.

Important:
We practically didn't touch the old code : the old class is now a component of the new decorator/s.
All we did was adding an abstract parent to the extended class, thus respecting the Open-Close Principle.

That's all!!  
Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן

Wednesday, August 13, 2014

Singleton Data Repository - Gang of Four Singleton Pattern Simple Sample


In this article we create a singleton Data Repository for MVC. A Singleton class is a class of which only a single instance can exist: is one of the 23 software patterns by the Gang of Four. The Singleton Pattern become really useful in an MVC application, because instead of re-creating the Repository 1) each time a request comes to the MVC app, and 2) also for every different user which browser to the site, it is created ONLY ONE time and kept for the whole lifetime of the MVC application, that means, until the IIS application pool is reset.
First i give you the whole c# code to create a Singleton Data Repository for Asp.Net MVC. It will be  connected to a single XML file , and will be exposing all CRUD operations, using the XDocument class. The basic class will be "Message", and the Repository , "IMessagesRepository". The initial XML file is placed at the end of this post, if you want to use it as bootstrap.
After giving you the Repository code for COPY-PASTE, we'll explain how it works, and we'll compare its behavior with a non-singleton MVC application.

  The whole application can show as follows (i'm using the Twitter Bootstrap: HERE you have a tutorial for installing it in 5 minutes):




This is the code for the Singleton Data Repository. Just COPY-PASTE it in your Models folder and use it inside the Controller: 


namespace RichFormApplication.Models
{

    public class Message
    {
        public int ID { get; set; }
        public string To { get; set; }
        public string Sender { get; set; }
        public string Title { get; set; }
        public string Contents { get; set; }
    }


    public interface IMessagesRepository
    {
        IEnumerable GetAll();
        Message Get(int id);
        Message Add(Message item);
        bool Update(Message item);
        bool Delete(int id);
    }


    public class MessagesRepository : IMessagesRepository
    {
        static private int test;
        private List<Message> Messages = new List<Message>();
        private int iNumberOfMsgs = 1;
        private XDocument doc;

        #region Singleton Init
        private static MessagesRepository _RepositoryInstance = new MessagesRepository();
        public static MessagesRepository RepositoryInstance
        {
            get
            {
                test = 1;
                return _RepositoryInstance;
            }
        }
        #endregion

        private MessagesRepository()
        {
            doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/data.xml"));
            foreach (var node in doc.Descendants("note"))
            {
                Messages.Add(new Message
                {
                    ID = Int32.Parse(node.Descendants("id").FirstOrDefault().Value),
                    To = node.Descendants("to").FirstOrDefault().Value,
                    Sender = node.Descendants("from").FirstOrDefault().Value,
                    Title = node.Descendants("heading").FirstOrDefault().Value,
                    Contents = node.Descendants("body").FirstOrDefault().Value
                });
            }

            iNumberOfMsgs = Messages.Count;
        }

        public IEnumerable GetAll()
        {
            return Messages;
        }
        public Message Get(int id)
        {
            return Messages.Find(p => p.ID == id);
        }
        public Message Add(Message item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            item.ID = iNumberOfMsgs++;

            XElement newNode = new XElement("note");
            XElement id = new XElement("id"); id.Value = item.ID.ToString();
            XElement to = new XElement("to"); to.Value = item.To;
            XElement from = new XElement("from"); from.Value = item.Sender;
            XElement Title = new XElement("heading"); Title.Value = item.Title;
            XElement Contents = new XElement("body"); Contents.Value = item.Contents;
            newNode.Add(id, to, from, Title, Contents);
            doc.Root.Add(newNode);
            SaveToXML();
            return item;
        }
        public bool Update(Message item)
        {            
            XElement Message = doc.Descendants("Message").Where(n => Int32.Parse(n.Descendants("id").FirstOrDefault().Value) == item.ID).FirstOrDefault();
            Message.Descendants("to").FirstOrDefault().Value = item.To;
            Message.Descendants("from").FirstOrDefault().Value = item.Sender;
            Message.Descendants("heading").FirstOrDefault().Value = item.Title;
            Message.Descendants("body").FirstOrDefault().Value = item.Contents;
            SaveToXML();
            return true;
        }
        public bool Delete(int id)
        {
            doc.Root.Descendants("note").Where(n => Int32.Parse(n.Descendants("id").First().Value) == id).Remove();
            SaveToXML();
            return true;
        }

        private void SaveToXML()
        {
            doc.Save(HttpContext.Current.Server.MapPath("~/App_Data/data.xml"));
        }
    }
}

Take a look at the red code : the steps for creating the Singleton are:
1) change the "public" for a "private" constructor;
2) declare a "public static" property which returns an INSTANCE of the class
3) that static instance will be created by the .Net CLR runtime , at the private static field containing the
         instance, at the precise instant in which someone calls at least one of the properties or methods
         of the class. The static instance of the class will survive for all lifetime of the MVC application.

To use the Repository just type the following code in the Controller:

        public ActionResult Index()
        {
            return View(MessagesRepository.RepositoryInstance.GetAll());
        }

Now let's test the singleton: browse to the website and put in debugger two breakpoints inside the Repository:


There is no initialization of the Repository , as it is static and its constructor is private.
You'll see that the first time some user browse to the site, the repository is initialized:





Try a second time, refreshing the web page: the repository will not be created again, because it already exists:



Try now as a new user, opening a second session in another browser tab, to see that you keep using the same repository as the first user does.

This is the XML initial file:



<?xml version="1.0" encoding="utf-8"?>
<notes>
  <note>
    <id>0</id>
    <to>Fry</to>
    <from>Leela</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!!!</body>
  </note>
  <note>
    <id>1</id>
    <to>Leela</to>
    <from>Fry</from>
    <heading>Finally!!!</heading>
    <body>Leela, have you asked permission from the Professor?</body>
  </note>
  <note>
    <id>2</id>
    <to>Fry</to>
    <from>Leela</from>
    <heading>Rejection</heading>
    <body>You know what? In second thoughts, i'm going out with Lars this weekend. Sorry...</body>
  </note>

</notes>

That's all concerning to the Singleton Repository.

If you are asking yourself about the XML related code, some relevant points about the XML include:
 We are using the Descendants("") method and the Load() method, for reading the XML file into memory and then inside the List<>.
The Get methods use Find(p => p):


To add a new node, we CREATE an XElement with all its XElement CHILDREN , and then add it to the ROOT (be careful adding them to the root) of the XDocument:




That's all!!  
Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן

Friday, January 3, 2014

Step By Step How to create an MVC 4 Controller

         By Carmel Schvartzman


In this tutorial we'll learn how to create an MVC 4 Controller  in ASP.NET MVC
An MVC application is based on the Model View Controller Architecture Pattern, a Software Pattern which separates an application in three components:
   Model - containing the Bussiness Data Logic and the Data Model Validation rules.
   Controller - containing the Input or Application Logic to interact with the user
   View - containing the UI Logic

That means, the Controller is the one who decides whether to render certain view to the user, is the responsible for fetching and persisting data via the Model and its Data Repository, or everything else concerning Views and Model. All this is done using Action Methods.

In an MVC app, a special HTTP Module named UrlRoutingModule parse and routes every request to the appropriate Controller's Action method, according to the following pattern:
                    http://server/Controller/ActionMethod/QueryArguments

All Controllers names must end with the suffix "Controller". The Controller class inherits from ControllerBase, and essentially is responsible for performing the following tasks:
   1) Getting the values the user input
   2) Deciding which Action method to call , passing it the values from the input
   3) Deciding which View must be rendered
   4) Handling any errors that may occur inside the Action methods

To create a new Controller, open Visual Studio , and click FILE > New Project. There, select "ASP.NET MVC 4 Web Application" , type a name and choose a location for the project:



Then, select " Internet Application" as the Template to use, and "Razor" as the View Engine. Also check the "Create a Unit Test Project" option:


Go to the Solution window and find the "Controllers" folder:


Then click "Add" and select "Controller":


You get the following dialog:


Type "MyController" (must be a single word and must use the "Controller" suffix) ,  and from the Scaffolding list select "MVC Controller with empty read/write actions":


We got the following Controller containing the action methods for read and write data from a database:


In this Controller, we got 8 Action methods: 5 are meant to render a View for the following actions: Create, Retrieve, Update and Delete, and also a special View for displaying the Details:



In addition, we got another  3 Action methods which handle the HTTP POST requests, one for Create requests which contain the data to create an entity:





Another for Editing an existing Entity, with updated data from the user:



And a last one for deleting an Entity:





This way we created our first Controller with Action methods to perform all CRUD (Create Retrieve Update Delete) Operations.

That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

Tuesday, December 31, 2013

When to use MVC and when to use Web Forms: an ASP.NET MVC-WebForms Comparison

         By Carmel Schvartzman

In this post we'll discuss when to use ASP.NET MVC and when to use ASP.NET Web Forms, performing an MVC-WebForms comparison

This is an MVC View:

Compare it with the Web Forms markup:

Web Forms are based on pre-built building stones called HTML Controls and Server Controls.
On the other side, MVC is based in the Model-View-Controller Pattern, that is reflected in the MVC folders architecture:



For those who until now have been working with traditional ASP.NET Web Forms, the following remarks about the Web Forms will not be new at all:

                                    ASP.NET Web Forms

Separation between UI Design (HTML) and Application Logic
ViewState:  exists, and usually is a heavy weight upon rendering HTML markup
Postback:  YES
Event-Driven Development: YES
Controls:  large library of drag-and-drop pre-built milestones that help you but limite you
SEO: Search Engine Optimization: limited by the pre-built controls
RAD: Rapid Application Development based on a rich variety of HTML and Server Controls
Test-Driven Development: no


                                       ASP.NET MVC

Separation between UI Design (View) - Data Bussiness Logic (Model) - Application Logic (Controller)
ViewState: NO (stateless model)
Postback: NO
Event-Driven: NO
Controls:   do not exist: there is complete control on the generated HTML
SEO: Search Engine Optimization: enhanced by the complete control on the generated HTML
RAD: Rapid Application Development is not the priority
Test-Driven Development: optimized for it

Based on the previous considerations, we could use the following table for deciding between MVC-WEBFORMS:

Needs
MVC
Web Forms





 SEO optimizations
 
YES
NO
Development Speed

NO
YES
Control over rendered HTML

YES
NO
Intranet Applications

NO
YES
Internet Applications

YES
MAYBE




Test-Driven Development

YES
NO
HTML5 skills

YES
NO

















Following the previous rough considerations, you could consider which ASP.NET development options to use.


That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

Thursday, December 26, 2013

Step By Step How to create a Data Repository with Data Caching in ASP.NET MVC 4

         By Carmel Schvartzman

In this tutorial we'll learn how to create a Data Repository with Data Caching in ASP.NET MVC 4. The MVC C# code for this step-by-step tutorial is available for download on GitHub at :
https://github.com/CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4
Its GitHub Wiki page is:
https://github.com/CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4/wiki

The Data Repository is a class which is designed to implement the Repository Pattern. This software pattern was created in order to access, cache in memory and persist in the database the application data. That means, the Repository will fetch the data ONLY IF IT'S NOT AVAILABLE IN MEMORY. 
There are, however, Repository implementations with no use of caching. The caching only stands to avoid unnecesary round trips to the SQL server. But when scalability of the sites is on the stage, may be we don't want to choke our web server's memory. Then, caching is not only redundant, but also dangerous as a waste of the web server resources. Of course using the Cache or the Application storages is less wasteful than using the Session ASP.NET storage, but even then the RAM memory of the web server should be taken into account and preserved as much as possible.
In this tutorial we'll add a Repository functionality with caching support to a new ASP.NET MVC 4 app.
Let's say we have an MVC internet application with an Entity Data Model mapped to an SQL server database. This EDM maps just two entities: Blog and Comment:

Our Repository will be added to the Model folder, which holds all the bussiness logic of the MVC application. Therefore focus the Model folder and create a new class: MyDataRepository.

Next, we'll create our Data Context, using the class created by the Entity Framework, inheriting DbContext: this class will be located under the Entity Data Model .edmx node: just open it until you see the XXX.Context.cs file:

 open it to see the name of your data context class which inherits from DbContext:

 This is your Data context and you'll add it to the Repository:

 Also add a null check to be sure your DbContext is there:

 Enclose the properties in a region:

 Take a look at the DbContext: you'll see that the Blog and Comment entities are represented by generic collections with a type DbSet<> :


 DbSet class provides the CRUD (Create Retrieve Update Delete) functionality we'll need to persist data changes to the database:


 The first method we'll add to our Repository will be the Save method. We separate this functionality so then we could make several changes all together and, just when done, we'll call the Repository Save method:



Now is time of designing the caching mechanism to store in memory the data. We'll use the caching infraestructure from the System.Runtime.Caching library, therefore add the pertinent reference:



Now focusing on the Model folder, create a new class named MyCachingProvider:



The class will use the ObjectCache, so add a private property to provide it. Implement the Get function instantiating the MemoryCache:



The first method we'll implement in our caching facility will be the Add functionality,and we'll take advantage of a MemoryCache aspect which puts this kind of storage far before from another storages like Application or Session: the caching policy. Later we'll state a caching expiration of a whole hour:




Now add the Remove functionality:



Also append the IsInMemory(key) method to check whether the required data is in memory:


Finally code the FetchData() method to get the data stored in memory:




 Next, we'll add all CRUD functionality to our Repository, as follows:



Notice that every C_UD (Create Update Delete) operation evicts the Comments from the Cache: that is because when a Comment is updated, created or deleted, the cached list remains in a async state with the actual data persisted in the database. We can either use the Sql Cache Dependencies functionality of the framework, or just evict the data from cache every time it is changed. For simplicity, we'll choose this later option.

 Finally, add the Retrieve functionality also for ALL the Comments and for just ONE selected Comment:


In the code you'll notice the use of the Caching functionality: first we check whether the data is in memory: if so we use the cache; elsewhere we fetch the data from the database and refresh the cache.


The RetrieveComment(id) method makes use of the previous RetrieveComment() method to get the List<> from memory:



 Now, let's check how our Repository works. On the server view, check the Comments table:


 Open the table contents, and clear them:




 Now, create a Testing class to run tests against the Repository. Inside the class, instantiate the Repository and create a new Comment:


 Next, call the Repository's AddComment() method, and Save() it all:


 Finally, in the HomeController make a call to our Test class:

 Build and debug the MVC application:



 As you can see, the original Comment has been instantiated.

 When finished the run, refresh the Comments table:



 The new record has been persisted by the Repository to the database.
Do it all again, adding the Retrieve part of the testing, fetching two comments to verify that the SECOND time we try to get data, it is loaded from the cache and not from database:


We get the Comment with CommentID = 2, as required:


Finally, test the Update method of the Repository, adding the code to change the Comment data:




Set a breakpoint inside the RetrieveComment() method to see how the "IF" clause causes to fetch data from the cache instead of from the database:





We've seen how to create a Data Repository with Data Caching in ASP.NET MVC 4 with support for all CRUD operations.
That's all!! 

Happy programming.....


כתב: כרמל שוורצמן