A day with .Net

My day to day experince in .net

Archive for September, 2012

Abstract Factory Pattern

Posted by vivekcek on September 15, 2012

Source Code http://sdrv.ms/O4X56A

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

participants

The classes and/or objects participating in this pattern are:

AbstractFactory (IMobileFactory)
declares an interface for operations that create abstract mobiles

ConcreteFactory (IPhoneFactory, NokiaFactory)
implements the operations to create concrete product objects

AbstractProduct (IMobile)
declares an interface for a type of product object

Product (IPhone3,Iphone3gs,Lumia800 etc..)
defines a product object to be created by the corresponding concrete factory
implements the AbstractProduct interface
Client (Program.cs)
uses interfaces declared by AbstractFactory and AbstractProduct classes

Advertisements

Posted in Design Patterns | Leave a Comment »

Factory Method Design Pattern

Posted by vivekcek on September 13, 2012

DOWNLOAD http://sdrv.ms/OrSETl

definition by GOF:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses

Our Example

The participants classes in this pattern are:

IProduct: defines the interface for objects the factory method creates.

ConcreteProduct: implements the Product interface (ex: Book, Mobile).

IProductFactory: declares an interface with method CreateProduct,Implemented by ConcreteFactory.

ConcreteFactory: overrides the generating method for creating ConcreteProduct objects.(ex: BookFactory, MobileFactory)

All concrete products are implementation of the IProduct, so all of them have the same basic implementation,

In our example class Book and Mobile are concrete implementation of IProduct.

The classes BookFactory and MobileFactory implement IProductFactory. These classes are responsible for creating concrete objects of our Book and Mobile class according to client requirement.

In our example Program.cs is our client class. Client will tell which factory to use. Based on that we get instances of concrete products.

Posted in Design Patterns | Leave a Comment »

Factory Pattern in C#

Posted by vivekcek on September 11, 2012

creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface

The implementation is really simple

1. The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
2.The factory instantiates a new concrete product and then returns to the client the newly created product.
3.The client uses the products as abstract products without being aware about their concrete implementation

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

namespace SimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            ProductFactory factory = new ProductFactory();
            IProduct product = factory.CreateProduct("Book");
        }
    }
    class ProductFactory
    {
        Dictionary<string, Type> Products;
        public ProductFactory()
        {
            LoadProducts();
        }
        public IProduct CreateProduct(string productName)
        {
            Type t = GetType(productName);
            IProduct product = Activator.CreateInstance(t) as IProduct;
            return product;
        }

        private Type GetType(string productName)
        {
            foreach (var product in Products)
            {
                if (Products.Keys.Contains(productName))
                    return Products[product.Key];
            }
            return null;
        }
        private void LoadProducts()
        {
            Products = new Dictionary<string, Type>();
            Type[] produtTypes = Assembly.GetExecutingAssembly().GetTypes();
            foreach (Type product in produtTypes)
            {
                if (product.GetInterface(typeof(IProduct).ToString()) != null)
                    Products.Add(product.Name.ToString(), product);
            }
        }
    }
    interface IProduct
    {
        string ProductName { get; }
    }
    class Book : IProduct
    {

        public string ProductName
        {
            get { return "Book"; }
        }
    }
    class MobilePhone : IProduct
    {

        public string ProductName
        {
            get { return "MobilePhone"; }
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Chain Of Responsibility Design Pattern in C#

Posted by vivekcek on September 10, 2012

read about it here http://www.dofactory.com/Patterns/PatternChain.aspx#_self2

Here i am giving a simple example from my organization.
In our organization if i need a leave i have to submit a leave form to someone just above me. The person just above me is my mentor.If i need a leave for 1 day he can immediately approve my leave. If i need more than 1 day he will contact Project manger he is just above the mentor. The project manger can approve leave upto 2 days.If i need leave more than 2 days, the project manger consult HR Manger.HR Manger can approve leave up-to 4 days.If i request more than 4 days leave my request will be forwarded to CEO. CEO will approve leave’s up-to 5 days.If i need more than 5 day’s of leave CEO will call me for a meeting.

In all the above case i just need to submit leave application to my mentor. The approval process propagate automatically and i will get some response.

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

namespace ChainOfResponsibility
{
    class Program
    {
        static void Main(string[] args)
        {
            int NumberOfDays;
            var vivek = new SoftwareEngineer();
            var myMentor = new Mentor();
            var myPM = new ProjectManger();
            var myHR = new HRManger();
            var myCEO = new CEO();

            vivek.SetNextLevelEmployee(myMentor);
            myMentor.SetNextLevelEmployee(myPM);
            myPM.SetNextLevelEmployee(myHR);
            myHR.SetNextLevelEmployee(myCEO);

            while (true)
            {
                Console.WriteLine("Enter Number Of Day's Of Leave");
                NumberOfDays = int.Parse(Console.ReadLine());
                vivek.ProcessLeave(NumberOfDays);
            }

        }
    }
    public abstract class Employee
    {
        protected Employee NextLevelEmployee;
        public abstract void ProcessLeave(int numberOfDays);
        public void SetNextLevelEmployee(Employee emp)
        {
            NextLevelEmployee = emp;
        }
    }
    public class SoftwareEngineer : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class Mentor : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if(numberOfDays<2)
            {
                Console.WriteLine("Leave approved by Mentor");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class ProjectManger : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <=3)
            {
                Console.WriteLine("Leave approved by Project Manger");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class HRManger : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <=4)
            {
                Console.WriteLine("Leave approved by HRMnager");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class CEO : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <= 5)
            {
                Console.WriteLine("Leave approved by CEO");
            }
            else 
            {
                Console.WriteLine("Let us have a meeting with CEO");
            }
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Facade Pattern

Posted by vivekcek on September 8, 2012

A facade is an object that provides a simplified interface to a larger body of code, such as a class library.
Look at the example below where the ‘SoftwareCompany’ abstract the building step of a software.

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use

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

namespace Facade
{
    class Program
    {
        static void Main(string[] args)
        {
            SoftwareCompany comp = new SoftwareCompany();
            comp.BuildSoftware();
            Console.ReadLine();
        }
            
    }
    /// <summary>
    /// Abstract the building of a software
    /// </summary>
    class SoftwareCompany
    {
        private RequirementAnalysis rqAnlysis = null;
        private Design design = null;
        private Coding coding = null;
        private Testing testing = null;
        private Deploying deploy = null;
        public SoftwareCompany()
        {
            rqAnlysis = new RequirementAnalysis();
            design = new Design();
            coding = new Coding();
            testing = new Testing();
            deploy = new Deploying();
        }
        public void BuildSoftware()
        {
            rqAnlysis.DoRequirementAnalysis();
            design.DoDesign();
            coding.DoCoding();
            testing.DoTesting();
            deploy.DoDeploying();
        }
    }
    class RequirementAnalysis
    {
        public void DoRequirementAnalysis()
        {
            Console.WriteLine("RequirementAnalysis");
        }
    }
    class Design
    {
        public void DoDesign()
        {
            Console.WriteLine("Design");
        }
    }
    class Coding
    {
        public void DoCoding()
        {
            Console.WriteLine("Coding");
        }
    }
    class Testing
    {
        public void DoTesting()
        {
            Console.WriteLine("Testing");
        }
    }
    class Deploying
    {
        public void DoDeploying()
        {
            Console.WriteLine("Deploying");
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Singleton – Normal-Thread Safe-Lazy

Posted by vivekcek on September 8, 2012

Ensure that only one instance of a class is created.
Provide a global point of access to the object

Not Thread Safe Implementation

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

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
           Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
           Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
        /// <summary>
        /// Private variable hold the instance.
        /// </summary>
        private static Singleton _Instance = null;

        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new Singleton();
                    return _Instance;
                }
                else
                    return _Instance;
            }
        }

        /// <summary>
        /// Some Functionality.Hash code indicate same instance.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param + "from " + _Instance.GetHashCode();
        }


    }
}

Thread Safety By Double Lock

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

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
            Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
            Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
        private static readonly object _SyncLock = new object();
        /// <summary>
        /// Private variable hold the instance.
        /// </summary>
        private static Singleton _Instance = null;

        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get
            {

                if (_Instance == null)
                {
                    lock (_SyncLock)
                    {
                        if (_Instance == null) //Double check
                            _Instance = new Singleton();
                    }

                }
                return _Instance;
            }
        }

        /// <summary>
        /// Some Functionality.Hash code indicate same instance.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param + "from " + _Instance.GetHashCode();
        }


    }
}

Singleton lazy instantiation

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

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
            Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
            Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
                
        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get { return Nested.Instance; }
        }

        /// <summary>
        /// Some Functionality.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param ;
        }

        /// <summary>
        /// Nested class for lazy
        /// </summary>
        private class Nested
        {
            static Nested()
            { }
            internal static readonly Singleton Instance = new Singleton();
        }


    }
}

Posted in Design Patterns | Tagged: , | Leave a Comment »

SQLite with Windows 8 apps

Posted by vivekcek on September 6, 2012

Installing the SQLite

The first thing you want to do is install the package.You can do this from within Visual Studio itself in all editions.
From the Tools menu, choose Extensions and Updates and then choose the Online section (on the left of the dialog) and
search for ‘sqlite’ in the search term. This will show you the SQLite for Windows Runtime package.

Using the new package in your C#

Now that you have the SQLite for Windows Runtime package installed in your Visual Studio environment, you want to use it. In a managed (.NET) app you would do the following steps.
First, create your app (e.g., a Blank XAML app is fine). Once within your app, use the Add Reference mechanism to get to
the next step. Now you will not be browsing for any DLL directly like you would in a traditional .NET.
What we are adding here is a reference to the Extension SDK…not the library itself, a small but important distinction.
Once in the Add Reference dialog choose the Windows\Extensions view (see on left) and you’ll see SQLite for Windows Runtime.

To correctly use this in a managed app you’ll need to select that *and* the C++ runtime as seen below:

<

Now with this involved you can grab a managed wrapper to call the SQLite APIs. I personally recommend the sqlite-net library (available via NuGet) to make this easier for you.

Using the sqlite-net library you can perform tasks using a model similar to LINQ2SQL where you can have types represent database entities:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using SQLite;

namespace App1
{

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "person.sqlite");
            using (var db = new SQLite.SQLiteConnection(dbPath))
            {
                db.CreateTable<Person>();

                db.RunInTransaction(() =>
                     {
                         db.Insert(new Person() { Name = "vivek", Surname = "ps" });
                     });
            }

        }

    }

    public class Person
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        [MaxLength(30)]
        public string Name { get; set; }

        [MaxLength(30)]
        public string Surname { get; set; }

    }

}

Now you just need to specify your architecture for your app (x86, x64, ARM) and when you build, the appropriate sqlite3.dll will be packaged in your app automatically. This also happens during the packaging step for the store so the right item is included for each architecture-specific package.

Posted in Windows 8 | Tagged: , , | Leave a Comment »

Navigation and Passing Information Between Pages Windows 8 Metro

Posted by vivekcek on September 4, 2012

Read my previous post Hello World Windows 8 Metro App

Download Source http://sdrv.ms/R3zfId

In this post i am going to show how we can implement navigation in a windows 8 metro app.
In metro the Frame class is primarily responsible for navigation and implements methods such as Navigate, GoBack, and GoForward.We use the Navigate method to display content in the Frame.

1. Create a new metro blank application.

2. Delete the MainPage.xaml.

3. Now add 2 Basic Page template to our app named FirstPage.xaml and SecondPage.xamal. The solution will look like below.

4. In the FirstPage.xaml.Find the TextBlock element named pageTitle and change the Text property to ‘First Page’. The XAML should look like below.

 <TextBlock x:Name="pageTitle" Grid.Column="1" Text="First Page" Style="{StaticResource PageHeaderTextStyle}"/>

5. Do the same title change in the SecondPage.xaml also.

6. Now we want to show the FirstPage.xaml when the application first launches. For that go to App.xaml.cs file under the OnLaunched() method add the code below.

 var rootFrame = new Frame();
            if (!rootFrame.Navigate(typeof(FirstPage)))
            {
                throw new Exception("Failed to create initial page");
            }

7. So when our application launches a rootFrame will be created and FirstPage.xaml will be loaded into the rootFrame.

8. Now we will create a TextBox and a Button in our FirstPage using the below xaml markup.

 <StackPanel Grid.Row="1" Margin="100,10,0,-1" >

            <TextBlock Text="Enter Your Name"/>
      
      <StackPanel Orientation="Horizontal" Margin="0,20,0,0">
  
              <TextBox x:Name="txtInput" Width="200" HorizontalAlignment="Left"></TextBox>
   
             <Button x:Name="btnSubmit" Content="Submit" Margin="5,0,0,0" ></Button>
         
      </StackPanel>
          
  <TextBlock x:Name="txtOutput"></TextBlock>
  
</StackPanel>

9. Generate Click event of button using property window of button.

10. Write the below code in button click event.

 private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(SecondPage), txtInput.Text);
        }

11. Add the below xaml markup in SecondPage.xaml. Which create a TextBlock to show passed parmeter.

<StackPanel Grid.Row="1" Margin="100,10,0,-1" >
 
             <StackPanel Orientation="Horizontal" Margin="0,20,0,0"/>
  
            <TextBlock x:Name="txtOutput"></TextBlock>
  
      </StackPanel>
</StackPanel>

12 In SecondPage.xaml.cs override the OnNavigatedTo() method and add below code.

 protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string name = e.Parameter as string;

            if (!string.IsNullOrWhiteSpace(name))
            {
                txtOutput.Text = "Hello, " + name;
            }
            else
            {
               txtOutput.Text = "Name is required.  Go back and enter a name.";
            }

        }

Posted in Windows 8 | Tagged: , , | Leave a Comment »

Hello World Windows 8 Metro App

Posted by vivekcek on September 3, 2012

Download Source Code: http://sdrv.ms/NQmKeD

Today I am going to show you how to create a simple Hello World metro app. Our Hello Word app contain a text box and a button. If we enter some text in the textbox and press submit button that text will be shown in our app.

Software’s You Need.
————————————-

. Windows 8 beta or release preview
. Visual Studio 2012 Express for Windows 8.

Knowledge Need
——————————-

. XAML,C#, Visual Studio.

1. Open the Visual Studio 2012.

2. Create a new blank project. Give some name ‘MyApp’.

3. Go to solution explorer and delete MainPage.xaml.

4. Now select and right click on the MyApp project. From the context menu select Add -> New Item

5. Add a basic page. Give name as MainPage.xaml.

6. Now in the xaml mark up of MainPage just above VisualStateManger and in the Root Grid Copy the xaml mark up code given below.

<StackPanel Grid.Row="1" Margin="100,10,0,-1" >
            <TextBlock Text="Enter Your Name"/>
            <StackPanel Orientation="Horizontal" Margin="0,20,0,0">
                <TextBox x:Name="txtInput" Width="200" HorizontalAlignment="Left"></TextBox>
                <Button x:Name="btnSubmit" Content="Submit" Margin="5,0,0,0" ></Button>
            </StackPanel>
            <TextBlock x:Name="txtOutput"></TextBlock>
        </StackPanel>

7. This xaml mark up create a textbox and button with some textblock for display data.

8. Now we need to generate a click event for out submit button. We need to use the property window to generate click event.

9. Add the below code in the event handler generated in MainPage.xaml.cs.

 private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            txtOutput.Text = "Hai " + txtInput.Text;
        }

10. Final Output

Posted in Windows 8 | Tagged: , , | Leave a Comment »