Tuesday, April 23, 2013

Read text file from file system.



public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sourcePath = @"E:\Users\Public\TestFolder\";
            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                // Copy the files and overwrite destination files if they already exist. 
                foreach (string s in files)
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        String line = sr.ReadToEnd();
                        Response.Write(line);
                    }
                }
            }
        }
    }
}

Create text file, copy text file, move text file and The process cannot access the file because it is being used by another process.


  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string fileName = "test.txt";
            string sourcePath = @"E:\Users\Public\TestFolder";
            string targetPath = @"E:\Users\Public\TestFolder\SubDir";

            // Use Path class to manipulate file and directory paths. 
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            File.Create(sourcePath + "\\test.txt").Dispose();           
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }

            //System.IO.File.Copy(sourceFile, destFile,false);

            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                // Copy the files and overwrite destination files if they already exist. 
                foreach (string s in files)
                {
                    StreamWriter sw = new StreamWriter(s, true);
                    sw.WriteLine("my sssssdfdf df dfd d fd fdf d 55454545454545");
                    sw.Flush();
                    sw.Close();

                    // Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, true);
                   // System.IO.File.Move(s, destFile);

                  
                }
               
              
            }
            else
            {
                MessageBox.Show("Source path does not exist!");
            }


            //string pathDirectory = @"E:\\testfolder\\";
            //string pathMoveDirecoty=@"D:\\Receivedtestfiles\\";
            //if (Directory.Exists(pathDirectory))
            //{
            //    string[] allFiles = Directory.GetFiles(pathDirectory);
            //    if (allFiles.Length > 0)
            //    {
            //        Directory.Move(allFiles[0].ToString(), pathMoveDirecoty + allFiles[0].ToString());
            //    }
            //}
        }
    }

Get running processes. The RPC server is unavailable:



The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)" error may occurs when deploying VNC to a remote computer or when using built-in management tools.
There can be a few reasons for this error:

1. The remote computer is blocked by the firewall.
Solution: Open the Group Policy Object Editor snap-in (gpedit.msc) to edit the Group Policy object (GPO) that is used to manage Windows Firewall settings in

your organization. Open Computer Configuration, open Administrative Templates, open Network, open Network Connections, open Windows Firewall, and then open either 

Domain Profile or Standard Profile, depending on which profile you want to configure. Enable the following exception: "Allow Remote Administration Exception" and 

"Allow File and Printer Sharing Exception".
2. Host name or IP address is wrong or the remote computer is shutdown.
Solution: Verify correct host name or IP address.

3. The "TCP/IP NetBIOS Helper" service isn't running.
Solution: Verity that "TCP/IP NetBIOS Helper" is running and set to auto start after restart.

4. The "Remote Procedure Call (RPC)" service is not running on the remote computer.
Solution: Verity that "Remote Procedure Call (RPC)" is running and set to auto start after restart.
5. The "Windows Management Instrumentation" service is not running on the remote computer.
Solution: Verity that "Windows Management Instrumentation" is running and set to auto start after restart.

 public void GetWMIProcess()
    {

const string Host = "systemname";//ip
        const string Path = (@"\\" + Host + @"\root\CIMV2");
        const string Exe = "notepad";

        var queryString = string.Format("SELECT Name FROM Win32_Process WHERE Name = '{0}'", Exe);
        var query = new SelectQuery(queryString);

        var options = new ConnectionOptions();
        options.Username = "Administrator";
        options.Password = "password";
      

        var scope = new ManagementScope(Path, options);

        var searcher = new ManagementObjectSearcher(scope, query);

        bool isRunnning = searcher.Get().Count > 0;

        Label1.Text = "Is {0} running = {1}." + Exe + isRunnning;

   }

Saturday, April 20, 2013

sql Database BackUp


Database BackUp:

backup database myDb to disk = 'E:\myfolder\mydbMay28.bak'

Thursday, April 18, 2013

what is interface, understanding on interface in c#, how to implement interface in c#,Real Time example


Interface:
1. Interface is a way to provide communication between user and program classes, methods,structures.
2. Interfaces in C # provide a way to achieve runtime polymorphism.
3. can not create instance of an interface
4. Using interfaces we can invoke methods from different classes through the same Interface reference.
5. using virtual method we can invoke mthods from different classes in the same inheritance hierarchy through the same reference. 
6. An abstract class serves as the base class for a family of derived classes, while interfaces are meant to be mixed in with other inheritance trees
7. Interface does not contain any concrete methods.
8. Multiple Inheritance is possible with interface
9. Access Specifiers are not supported in Interface(Interface is a contract with the outside world which specifies that class implementing this interface does a certain set of things. So, hiding some part of it doesn't make sense.However, interfaces themselves can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.)
10. All the interface methods are Public. You can't create an access modifier in interface.

Sample Example:
namespace InterfaceDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ImplementedMainClass obj = new ImplementedMainClass();

            //I want to call first interface methods
            ISampleInterface sample = obj;
            sample.getData();
            sample.saveData();
            sample.checkStatus();

            //I want to call second interface methods
            int id=2;
            ISampleInterface2 sample2 = obj;
            sample2.getDataByID(id);
            sample2.createUserCredentials("demo", "demopwd");
        }
    }


    public interface ISampleInterface
    {
        DataTable getData();
        string saveData();
        string checkStatus();
    }
    public interface ISampleInterface2           
    {
        DataTable getDataByID(int id);
        string createUserCredentials(string userName,string password);
    }

    public class ImplementedMainClass : ISampleInterface, ISampleInterface2
    {
              

        #region SampleInterface2 Members

        public DataTable getDataByID(int id)
        {
            DataTable dt = new DataTable();
            ////Write code for retrive data by using id from database\
            return dt;
        }

        public string createUserCredentials(string userName, string password)
        {
           //Write a logic for save user credentials into database
            return string.Empty;
        }

        #endregion

        #region SampleInterface Members

        public DataTable getData()
        {
            DataTable dt = new DataTable();
            //Write code for retrive data from database
            return dt;
        }

        public string saveData()
        {
            //Write code for insert/update/delete 
            return string.Empty;
        }

        public string checkStatus()
        {
            return string.Empty;
        }

        #endregion
    }
    
}


What is the difference between JavaScript and jQuery?

JavaScript is a language whereas jQuery is a library written using JavaScript.

JQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers. The jQuery framework is extensible and very nicely handles DOM

manipulations, CSS, AJAX, Events and Animations.
Mask:

$(document).ready(function() {
    // Attaches masks to page controls
    $('#<%= txtSsn.ClientID %>').mask("999-99-9999");
    $('#<%= txtBirthDate.ClientID %>').mask("99-99-9999");
});
 

Calling an ASP .NET page method

A sample page method
The following is the code sample of a sample page method that takes no parameters
[WebMethod()]
public static string Hello2()
{
    return "hello ";
}
Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page

method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the

controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carries around by an asp .NET page.

Calling a page method from jQuery:
We use the same jQuery command $.ajax to call a page method, as shown in the following example.
<script type="text/javascript">
      $(document).ready(function() {
          $.ajax({
              type: "POST",
              url: "pagemethod.aspx/Hello2",
              contentType: "application/json; charset=utf-8",
              data: "{}",
              dataType: "json",
              success: AjaxSucceeded,
              error: AjaxFailed
          });
    });
      function AjaxSucceeded(result) {
          alert(result.d);
      }
      function AjaxFailed(result) {
          alert(result.status + ' ' + result.statusText);
      } 
  </script>

Consuming a web service using jQuery

It looks deceivingly simple. However, you can stuff a lot of specifics in this umbrella parameter options, such as the required ones: url of the web service (url), request content type (contentType), response data type (dataType), callback function for success (success); and the optional ones: callback function in case of failure (error), a timeout for the AJAX request in milliseconds (timeout), etc.

For example, we can call a specific web method in a web service as such.
JQuery .ajax command:
  $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});
Two things are worth noting in the above JQuery AJAX call. First, we must specify the contentType’s value as application/json; charset=utf-8, and the dataType as json; second, to make a GET request, we leave the data value as empty.
So put it together, the following code demonstrates how we would use JQuery to call the web service we created above.

Calling a web service using jQuery:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head id="Head1" runat="server">
<title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
 <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">  
</script> 
  <script type="text/javascript">
      $(document).ready(function() {
         $("#sayHelloButton").click(function(event){
             $.ajax({
                 type: "POST",
                 url: "dummyWebsevice.asmx/HelloToYou",
                 data: "{'name': '" + $('#name').val() + "'}",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(msg) {
                     AjaxSucceeded(msg);
                 },
                 error: AjaxFailed
             });
         });
     });
          function AjaxSucceeded(result) {
              alert(result.d);
          }
          function AjaxFailed(result) {
              alert(result.status + ' ' + result.statusText);
          } 
  </script> 
</head>
<body>
    <form id="form1" runat="server">
     <h1> Calling ASP.NET AJAX Web Services with jQuery </h1>
     Enter your name:
        <input id="name" />
        <br />
        <input id="sayHelloButton" value="Say Hello"
               type="button"  />
    </form>
</body>
</html>

how do call ASP .NET web services using jQuery?

use the jQuery command ajax with the following syntax:
$.ajax (options)

Consuming a web service using ASP .NET AJAX


It is easy to call web services with the native ASP .NET AJAX, which would automatically take care all of the gritty details. It takes two steps:
First, add a ServiceReference to the ScriptManager control in the web form, as such:

<asp:ScriptManager ID="_scriptManager" runat="server">
  <Services>
    <asp:ServiceReference Path="dummywebservice.asmx" />
  </Services>
</asp:ScriptManager>

Second, call any web methods defined in the web service by passing the necessary parameters and a callback function. The callback will be invoked once the data is returned from server. The following is a complete example of how we call a web service using ASP .NET AJAX.


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head id="Head1" runat="server">
<title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
 <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">  
</script> 
  <script type="text/javascript">
      function OnSayHelloClick() {
          var txtName = $get("name");
          dummyWebservice.HelloToYou(txtName.value, SayHello);
      }
      function SayHello(result) {
          alert(result);
      }
  </script> 
</head>
<body>
   <form id="form1" runat="server">
    <asp:ScriptManager ID="_scriptManager" runat="server">
      <Services>
        <asp:ServiceReference Path="dummyWebsevice.asmx" />
      </Services>
    </asp:ScriptManager>
    <h1> ASP.NET AJAX Web Services: Web Service Sample Page </h1>
     Enter your name:
        <input id="name" />
        <br />
        <input id="sayHelloButton" value="Say Hello"
               type="button" onclick="OnSayHelloClick();" />
    </form>
</body>
</html>
However as we have mentioned before, ASP .NET AJAX is rather heavy-handed and carries hefty performance penalties. In comparison, jQuery is superior in its promise of “less code do more”.

ASP .NET web services using jQuery


From the conception to now, web services has gone a long way. Web services use XML as the default data exchange format and SOAP as its protocol. However it has long been dogged by complaints of complexity and lack of open standards. XML as its default message format often feels cumbersome and bandwidth-heavy.

However, with AJAX, JSON overtook XML as a more efficient alternative. It retains all of the advantages claimed by XML, such as being readable and writable for humans, and easy to parse and generate. JSON, though completely language independent, borrows a lot of conventions from languages such as C, C++, C#, Java, JavaScript, Perl, Python, etc. This makes JSON an instant hit among programmers.

To accommodate this trend, data returned from ASP .NET web script services are by default in JSON format.

JSON serialized web service:

EX:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class dummyWebservice : System.Web.Services.WebService
{
  [WebMethod()]
  public string HelloToYou(string name)
  {
      return "Hello " + name;
  }
  [WebMethod()]
  public string sayHello()
  {
      return "hello ";
  } 
}

jQuery Document.Ready()

Document.Ready():

The most commonly used command in jQuery is Document.Ready(). It makes sure code is executed only when a page is fully loaded. We often place code blocks inside this Document.Ready() event. For example:

$(document).ready(function(){
 $("#buttonTest").click(function(event){
   alert("I am ready!");
 });
});

jQuery Selectors


1. $(‘p.note’) returns all <p> elements whose class name is note;
2. $(‘p#note’) returns the <p> element whose id is note;
3. $(‘p’) returns all <p> elements
4. To select a child or children, we use the right angle bracket (>), as in $(‘p>a’) (returns all of the hyper links within the <p> element);
5. To select element(s) with certain attributes, we use [], as in input[type=text] (returns all text input element);
6. To select a container of some other elements, we use has keyword, for example: $(‘p:has(a)’) (returns all <p> elements that contains an hyperlink);
7. jQuery also has a position-based selector for us to select elements by position, for example $(‘p:first’)

await and async keywords in .net

.NET 4.5 has new keywords await and async:

The .NET Framework 4.5 introduced an asynchronous programming concept referred to as a task. The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. A scenario like a report method should be executed asynchronously an dinside the method, fetching DB information should be synchronized. Here's how it should display

private async Task ShowReport()
 {
        var result = await DB.ExecuteNonQuery(<<some SP>>);
    // Code to handle the report display
}

Above, bolded words are key. It's saying ShowReport() will execute as async, but DB operation inside it will be synchronized

Difference Between IQueryable and IEnumerable


In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by IQueryable, hence it has all the features of it and except this, it has its own features. Both have their own importance to query data and data manipulation. Let’s see both the features and take the advantage of both the features to boost your LINQ Query performance.

IEnumerable
IEnumerable exists in System.Collections Namespace.
IEnumerable can move forward only over a collection, it can’t move backward and between the items.
IEnumerable is best to query data from in-memory collections like List, Array etc.
While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
IEnumerable supports deferred execution.
IEnumerable doesn’t supports custom query.
IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
Extension methods supports by IEnumerable takes functional objects.

Example
MyDataContext dc = new MyDataContext ();
IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take<Employee>(10);


IQueryable
IQueryable exists in System.Linq Namespace.
IQueryable can move forward only over a collection, it can’t move backward and between the items.
IQueryable is best to query data from out-memory (like remote database, service) collections.
While query data from database, IQueryable execute select query on server side with all filters.
IQueryable is suitable for LINQ to SQL queries.
IQueryable supports deferred execution.
IQueryable supports custom query using CreateQuery and Execute methods.
IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
Extension methods supports by IEnumerable takes expression objects means expression tree

Example
MyDataContext dc = new MyDataContext ();
IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take<Employee>(10);

*Notice that in this query "top 10" is existing since IQueryable executes query in SQL server with all filters.

1. IEnumerable<T> represents a forward-only cursor of T, .NET 3.5 added extension methods that included the LINQ standard query operators like Where and First, with any operators that require predicates or anonymous functions taking Func<T>.
2. IQueryable<T> implements the same LINQ standard query operators, but accepts Expression<Func<T>> for predicates and anonymous functions. Expression<T> is a compiled expression tree, a broken-up version of the method ("half-compiled" if you will) that can be parsed by the queryable's provider and used accordingly.

Tuesday, April 16, 2013

Create proxy using svcutil



Now we are using a tool called svcutil.

--> You need to type in VS command Prompt like this
        svcutil /out:proxy.cs /config:app.config "http://localhost:8025/Service"
        It will generate proxy.cs and app.config.

--> Now lets create a client application.Copy and paste the proxy.cs and app.config from the particular location and paste into client application.

netTcpBinding in WCF


Introduction:

Advantages of using Net.Tcp are as follows:
         1) It can be used for high performance communication.
         2) Net.Tcp Port sharing service enables net.tcp port to be shared across multiple user processes.

Monday, April 15, 2013

List To Get Specific Type of data in c#


public void LinqGetType() 

    object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 }; 
  
    var doubles = numbers.OfType<double>(); 
  
    Console.WriteLine("Numbers stored as doubles:"); 
    foreach (var d in doubles) 
    { 
        Console.WriteLine(d); 
    } 
}

Linq union in c#


public void LinqUnion() 

    List<Product> products = GetProductList(); 
    List<Customer> customers = GetCustomerList(); 
  
    var productFirstChars = 
        from p in products 
        select p.ProductName[0]; 
    var customerFirstChars = 
        from c in customers 
        select c.CompanyName[0]; 
  
    var uniqueFirstChars = productFirstChars.Union(customerFirstChars); 
  
    Console.WriteLine("Unique first letters from Product names and Customer names:"); 
    foreach (var ch in uniqueFirstChars) 
    { 
        Console.WriteLine(ch); 
    } 
}

Linq distinct in c#


public void LinqDistinct() 

    int[] f = { 2, 2, 3, 5, 5 }; 
  
    var uniqueFactors = f.Distinct(); 
  
    Console.WriteLine("Prime factors of 300:"); 
    foreach (var f in uniqueFactors) 
    { 
        Console.WriteLine(f); 
    } 
}


public void Linq2() 

    List<Product> products = GetProductList(); 
  
    var categoryNames = ( 
        from p in products 
        select p.Category) 
        .Distinct(); 
  
    Console.WriteLine("Category names:"); 
    foreach (var n in categoryNames) 
    { 
        Console.WriteLine(n); 
    } 
}

Linq groupby in c#


public void LinqGroupby() 

     List<Product> products = GetProductList(); 
      
        var groupby= 
            from p in products 
            group p by p.Category into g 
            select new { Category = g.Key, Products = g }; 
  
   gridview1.datasource=groupby;
   gridview1.databind();
}

Linq orderby in c#


public void LinqOrder() 

    List<Product> products = GetProductList(); 
  
    var sp= 
        from p in products 
        orderby p.ProductName 
        select p; 
  
   gridview1.datasource=sp;
   gridview1.databind();
}

Linq query Top 5 rows in c#


public void Linq() 
  

  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };  
  
    var first3Numbers = numbers.Take(5);  
  
    Console.WriteLine("First 5 numbers:"); 
  
    foreach (var n in first5Numbers) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}

Linq query on List in c#


public void Linq() 

    List<Product> products = GetProductList(); 
  
    var productNames = 
        from p in products 
        select p.ProductName; 
  
    Console.WriteLine("Product Names:"); 
    foreach (var productName in productNames) 
    { 
        Console.WriteLine(productName); 
    } 
}

Linq query - where - c#


 public void Linq1()
    {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
     
        var lowNums =
            from n in numbers
            where n < 5
            select n;
     
        Console.WriteLine("Numbers < 5:");
        foreach (var x in lowNums)
        {
            Console.WriteLine(x);
        }
    }

Factory pattern:
The factory pattern method is a popularly used design pattern

--> it is very useful to restrict clients from knowing the actual business logic methods.
--> it is useful to create a decoupled system.
--> it is useful to eliminate object creation in a client environment.

Eg:
based on user input we need to call particular class methods.
I have a customer input screen. He enters his choice whether they want to buy a bike or a car. Normally we get input from the user and based on that will create an object in the client class and call those methods like below.

 Collapse | Copy Code
//
// customer enters their choice
//
If (choice == “Car”)
{
// call car class and it’s methods
Car c = new car();
c.buy();
}
If (choice == “bike”)
{
// call bike class and it’s methods
Bike b = new Bike();
b.buy()}

1. In case in future if there is any other vehicle added then we need to change the client functionality.
2. The above client code depicts that there are classes Car, Bike, and a method Buy. There is no security at the client side.
3. Need to use the new keyword in client classes.
To avoid these problems Factory pattern is used.

Problem1: Create a new interface to depict methods, for example, in our scenario, it is Buy(). Using this interface it will solve problems 1 and 2.
public interface IChoice
{
    string Buy();
}

A new class will be added and this class we will be called factory class.
This class sits between the client class and the business class.
Based on user choice it will return the respective class object through the interface. It will solve problem 3.

//
// Factory Class
//
public class FactoryChoice
{
    static public IChoice getChoiceObj(string cChoice)
     {
        IChoice objChoice=null;
        if (cChoice.ToLower() == "car")
        {
            objChoice = new clsCar();
        }
        else if (cChoice.ToLower() == "bike")
        {
            objChoice = new clsBike();
        }
        else
        {
            objChoice = new InvalidChoice();
        }
        return objChoice;
    }
}
//Business classes
//Car
public class clsBike:IChoice
{
    #region IChoice Members

    public string Buy()
    {
        return ("You choose Bike");
    }

    #endregion
}

//Bike
public class clsCar:IChoice
{

    #region IChoice Members

    public string Buy()
    {
        return ("You choose Car");
    }

    #endregion
}

From the client class call the factory class object and it will return the interface object.
Through the interface object we will call the respective method.

//Client class
IChoice objInvoice;
objInvoice = FactoryClass.FactoryChoice.getChoiceObj(txtChoice.Text.Trim());
MessageBox.Show(objInvoice.Buy());

In future if we need to add a new vehicle then there is no need to change the client class, simply return that object using the factory class.

Advantages:
Suppose we want to add a decoupled structure and don’t want to disturb the client environment again and again, this pattern is very useful. The factory class will take all the burden of object creations.
One of the eminent facets of a good software design is the principle of loose-coupling or de-coupling, i.e., reducing or removing class dependencies throughout the system. Factory class removes the dependency on the specific product classes generated by the Factory from the rest of the system. The system is only dependent on the single interface type that is generated by the Factory. Loosely coupled or decoupled code is easier to test or reuse since the code has fewer dependencies on other code.
Note: refer from codeproject
http://www.codeproject.com/Tips/469453/Illustrating-Factory-pattern-with-a-very-basic-exa#

Dictionary in c#.net

Dictionary: The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings.


Dictionary<string, string> KeyValue = new Dictionary<string, string>();
KeyValue.Add("A", "Load");
KeyValue.Add("B", "Save");

foreach (KeyValuePair<string, string> item in KeyValue) {
   Console.WriteLine("{0} = {1}", item.Key, item.Value);
}