Wednesday, May 25, 2016

Factory Pattern With Reflection



An important aspect of software design is the manner in which objects are created, although far more time is often spent considering the object model and object interaction. But if this simple design (of object creation) aspect is ignored, it will adversely impact the entire system. Thus, it is not only important what an object does or what it models, but also in what manner it was created. 
Factory pattern is one of the most widely used pattern for these kind of situations. In this article lets see how to use Factory pattern with Reflection.  

What is Reflection ? 

Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. 

Example -: 

int
 i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

Output -: System.Int32


Factory pattern without Reflection

------------------- IFruit Interface (IFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    interface IFruit
    {
        string Name { get; }

        void eatMe();

        void donEatMe();
    }
}

------------------- Apple Class(Apple.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Apple: IFruit
    {

        public string Name
        {
            get { return "I am an Apple"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Apple -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Apple -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- Orange Class(Orange.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Orange : IFruit
    {
        public string Name
        {
            get { return "I am an Orange"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Orange -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Orange -: Don't eat me, I'm not a good fruit");
        }
    }
}

------------------- Kiwi Class(Kiwi.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Kiwi : IFruit
    {
        public string Name
        {
            get { return "I am a Kiwi"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Kiwi -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Kiwi -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- NoFruit Class(NoFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class NoFruit:IFruit
    {
        public string Name
        {
            get { return "I am not a Fruit"; }
        }

        public void eatMe()
        {
            Console.WriteLine("You can't eat me");
        }

        public void donEatMe()
        {
            Console.WriteLine("You can't eat me");
        }
    }
}



------------------- FruitFactory Class(FruitFactory.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
        public static IFruit getFruit(string fruitName)
        {
            switch (fruitName)
            {
                case "Orange":
                    return new Orange();
                 
                case "Apple":
                    return new Apple();
               
                case "Kiwi":
                    return new Kiwi();
             
                default:
                    return new NoFruit();
                 
            }

        }
    }
}


------------------- Program Class(Program.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            IFruit myFruit = FruitFactory.getFruit("Orange");
            Console.WriteLine(myFruit.Name);
            myFruit.eatMe();          

            Console.ReadLine();
        }
    }
}


Factory pattern with Reflection

Change FruitFactory.cs and Program.cs Classes as below


------------------- FruitFactory Class(FruitFactory.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
         Dictionary<string, Type> cars;

         public FruitFactory()
        {
            TypesToReturn();
        }

        public IFruit CreateInstance(string carName)
        {
            Type t = TypeToCreate(carName);

            if (t == null)
            {
                return new NoFruit();
            }
            else
            {
                return Activator.CreateInstance(t) as IFruit;
            }
        }

        public Type TypeToCreate(string carName)
        {
            foreach (var car in cars)
            {
                if (car.Key.Contains(carName.ToUpper()))
                {
                    return cars[car.Key];
                }
            }
            return null;
        }

        public void TypesToReturn()
        {
            cars = new Dictionary<string, Type>();

            Type[] typesInCurrentAssembly = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type type in typesInCurrentAssembly)
            {
                if(type.GetInterface(typeof(IFruit).ToString()) != null)
                {
                    cars.Add(type.Name.ToUpper(), type);
                }
            }
        }
    }
}


------------------- Program Class(Program.cs) ---------------------

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            FruitFactory fruitFactory = new FruitFactory();

            IFruit myfruit = fruitFactory.CreateInstance("Orange");

            Console.WriteLine(myfruit.Name);
            myfruit.eatMe();
            //myfruit.donEatMe();

            Console.ReadLine();

        }
    }
}











Monday, April 25, 2016

Constructor Dependency Injection Pattern With C#



Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. The term "loosely coupled" deserves clarification and sometimes the best way to explain something is by first describing its opposite, which in this case is "tight coupling." When two classes are tightly coupled, they are linked with a binary association. For example, you can see in the below code, Calculate and ErrorHandler, that are joined together as an aggregation. 

Without Constructor Dependency Injection Pattern 

create an interface IErrorHandler which has one method to show the Error occurred. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public interface IErrorHandler
    {
        void showError(string erroMessage);
    }

}

Next create a class called ErrorHandler, which inherits the IErrorHandler interface and implement it's showError method, which we are going to use to show the Error message. 


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class ErrorHandler : IErrorHandler
    {
     
        public void showError(string erroMessage)
        {
            Console.WriteLine(erroMessage);
        }
      
    }
}

Now lets create a another class called Calculate to understand the concept of tight coupling. 



using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public class Calculate
    {
        IErrorHandler errorHandler = new ErrorHandler();
        public void calcValues()
        {
          
            try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }


        }
    }
}

Above class has an interface IErrorHandler instance which reference the ErrorHandler class. because of this the Calculate class is tightly coupled with the ErrorHandler class. 

Now lets call the calcValues method from main class.



using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculate calculate = new Calculate();
            calculate.calcValues();        

            Console.ReadLine();
        }
    }
}

this will show the below output, but as you can see this is not a good design because of tightly coupled.


With Constructor Dependency Injection Pattern 

The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.

Advantages
  • Construction Injection makes a strong dependency contract
  • Construction Injection supports testing, because dependencies can be passed in the constructor.
  • A dependency may be made immutable by making the dependency reference final by means that it prevents circular dependency.
Disadvantages
  • It requires up front wiring of the entire dependency graph.
The class that needs the Dependency must be exposing a public constructor that takes dependent class as constructor argument. In most cases, this should be the only one available constructor but if more than one Dependency is required then additional constructor arguments can be used.


Now lets create a CalculationEvent, That class has a parameter constructor. This constructor will be used to inject dependencies in the object. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public class CalculationEvent
    {
        IErrorHandler errorHandler;

        public CalculationEvent(IErrorHandler errorHandler)
        { 
            this.errorHandler = errorHandler;        
        }

        public void PerformCalculation()
        {
             try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }
        }
    }
}

you can see that the CalculationEvent class is not depend on any other class. 


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            CalculationEvent calculationEvent = new CalculationEvent(new ErrorHandler());
            calculationEvent.PerformCalculation();

            Console.ReadLine();
        }
    }
}



Tuesday, February 16, 2016

Passing an array from PHP to Javascript using JQuery & JSON



Step 01 -:

Create a php file named exampleJsonArray.php and copy & paste below code to that

<html>
<title> Easy Way For Codings</title>
<header> 
<h1>--- Easy Way For Codings PHP example ---</h1> 
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script> 
<script>

function onClick()
{
var ajaxurl = 'examplePHPCode.php';
            
            data =  {'action':'getCountryList'};
            
            $.post(ajaxurl, data, function (response) {
               
               var responses = jQuery.parseJSON(response);
  var countries = "";
  for (var s in responses){                   
                    
countries += responses[s][0] +"   "+ responses[s][1]+"\n";

               }
  alert(countries);            
            
});
}

</script>
</header>
<body>
<button type="button" onClick="onClick()">Show Country List</button>
</body>
</html>

Step 02 -:

Create a another php file named examplePHPCode.php and copy & paste below code to that

<?php
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'getCountryList':
            getCountryList();
            break;
                  
    }
}

function getCountryList()
{
    $countryList = array();
    
    $country = array("1000","Sri Lanka");
    array_push($countryList, $country);                         
    $country = array("2000","India");
    array_push($countryList, $country);       
    $country = array("3000","USA");
    array_push($countryList, $country);       
    $country = array("4000","UK");
    array_push($countryList, $country);       
    $country = array("5000","Australia");
    array_push($countryList, $country);       
    $country = array("6000","Indonesia");
    array_push($countryList, $country);       
    $country = array("7000","China");
    array_push($countryList, $country);       

    echo json_encode($countryList);                          
    exit;
}
?>

Final Result -:



Download Source Code



Access PHP code through Jquery



Step 01 -:

Create a php file named example.php and copy & paste below code to that

<html>
<title> Easy Way For Codings</title>
<header> 
<h1>--- Easy Way For Codings PHP example ---</h1> 
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script> 
<script>

function onClick()
{
var ajaxurl = 'examplePHPCode.php';
            
            data =  {'action':'getModifiedName', 'name': $('#txtname').val()};
            
            $.post(ajaxurl, data, function (response) {
               
               alert(response);

            });

}
</script>
</header>
<body>
 Enter Value Here: <input type="text" name="txtname" id="txtname"><br><br>
<button type="button" onClick="onClick()">Click Me !</button>
</body>
</html>

Step 02 -:

Create a another php file named examplePHPCode.php and copy & paste below code to that

<?php
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'getModifiedName':
            getModifiedName($_POST['name']);
            break;
                  
    }
}

function getModifiedName($name)
{
echo 'Welcome '.$name;
}

?>

Final Result -:

Download Source Code



Sunday, November 9, 2014

MongoDB






Intriduction
MongoDB is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open-source software.
First developed by the software company 10gen (now MongoDB Inc.) in October 2007 as a component of a planned platform as a service product, the company shifted to an open source development model in 2009, with 10gen offering commercial support and other services.[1] Since then, MongoDB has been adopted as backend software by a number of major websites and services, including Brave Collective, CraigslisteBayFoursquareSourceForgeViacom, and the New York Times, among others. MongoDB is the most popular NoSQL database system.

How to use MongoDB (Part 01)



How to use MongoDB (Part 02)