Thursday 4 April 2013

How to Print particular portion of webpage?


Introduction
Here I am going to demonstrate “how to print particular portion of webpage?”. Manier  we use “Window.Print()” javascript in order to print data displayed on web-page. But there may be a case when I didn’t need to print whole page or just required to print one small portion of page instead of whole page, in those scenario “Window.print()” won’t work. So what should we do in such situation? Here is the answer.

Inside the code
We can print web document through javascript, so definitely we’ll write some javascript to print portion of web page. Here is the script:

        function CallPrint(strid) {
            var prtContent = document.getElementById(strid);
            var WinPrint = window.open('', '', 'letf=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');
            WinPrint.document.write(prtContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
            prtContent.innerHTML = strOldOne;
        }

Now, how to use this javascript? For that create a <div /> element and assign unique id to it (i.e. <div ID=”divPrint”). Now put your html content between this <div />.
For example, if I want to print Item information which are displays on grid like:

<asp:DataGrid Id=”grdItem” runat=”server>
             <Columns>
                      ……..
                      ……..
             </Columns>
</asp:DataGrid>

Put this whole html content between <div /> tag.
Now onClientClick event of button call javascript function like:
OnClientClick=”CallPrint(‘divPrint’)”
This all makes your printing done.

Wednesday 31 October 2012

How to export Encoded Data into CSV Files?


Exporting data into various file format - i.e. .csv, .tsv is frequently required in our day to day action. Many of us have been written code segment for this also. My purpose to write this article is to demonstrate How export data using various encoding into csv format?

Here I’ve developed a sample application which export a Unicode data stored in database into csv file. Note that if you export data with Unicode encoding delimited by coma (‘,’), it won’t gives you effective result. Let’s start how to overcome this problem.

Inside the code


























In above image you can see that Datagridview is loaded with data. This data contains data in unicode format – Last two row contains data in chainese and russian language. Also we’ve an option for selecting various encoding and delimeters while exporting data. Code for file export is shown as below.


        private void btnExport_Click(object sender, EventArgs e)
        {
            DataTable dt = dg.DataSource as DataTable;

            if (string.IsNullOrEmpty(txtPath.Text.Trim()))
            {
                ShowMessage("Invalid file path. Please enter valid file path");
                return;
            }

            StringBuilder builder = new StringBuilder();

            if (chkHeader.Checked)
            {
                var count = 0;
                foreach (DataColumn column in dt.Columns)
                {
                    count++;
                    string content = column.ColumnName + "";
                    content = content.Replace("\"", "\"\"");
                    builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

                    if (count < dt.Columns.Count)
                        builder.Append(GetDelimeter(cmbDelimeter.Text.Trim()));
                }
                builder.Append(Environment.NewLine);
            }

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    if (!Convert.IsDBNull(row[i]))
                    {
                        string content = row[i].ToString() + "";
                        content = content.Replace("\"", "\"\"");
                        builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

                        if (i < row.ItemArray.Length - 1)
                            builder.Append(GetDelimeter(cmbDelimeter.Text.Trim()));
                    }
                }
                builder.Append(Environment.NewLine);
            }

            using (var streamWriter = new StreamWriter(txtPath.Text.Trim(), chkAppend.Checked, GetEncoding(cmbEncoding.Text.Trim())))
            {
                streamWriter.Write(builder.ToString());
                streamWriter.Flush();
                streamWriter.Close();
            }
            ShowMessage("Data successfully exported");
        }

In above code you can see that we are iterating over each row in data table and appending each cell data into string builder. Delimiter that we choose while exporting is appended after each cell data through GetDelimeter() function. Code of GetDelimeter() function is shown below:

        private string GetDelimeter(string delimeter)
        {
            string retval = "";
            switch (delimeter.ToLower())
            {
                case "coma":
                    retval = ",";
                    break;
                case "tab":
                    retval = "\t";
                    break;
                case "space":
                    retval = "\b";
                    break;
            }
            return retval;
        }

After appending all data into string builder, initialize StreamWriter object with argument – Destination file path, data should appended or not and content Encoding. Encoding is also chosen by us while exporting. Code for selecting encoding is given below:

        private Encoding GetEncoding(string encoding)
        {
            Encoding encod = null;
            switch (encoding.ToLower())
            {
                case "unicode":
                    encod = Encoding.Unicode;
                    break;
                case "utf8":
                    encod = Encoding.UTF8;
                    break;
                case "ansi":
                default:
                    encod = Encoding.Default;
                    break;
            }

            return encod;
        }

This way we can export data in csv file with encoding we choose.






Tuesday 31 July 2012

Sample MEF Example



Introduction

I am not going cover detail about MEF or not going describe functionality of MEF. One can find good material over the net for MEF, so I am not going to post redundant information. What I feel is MEF is an extensibility framework provided by Microsoft. Many other extensibility framework exists but MEf is easy to initiate. Today I am going develop a sample application which demonstrate how to import/export components. Kindly note that this is just a small effort so that beginner can start working with MEF.

Using the code

In this article we are going to cover following topic:
1)      Develop Component behavior: This will be an interface which functionality exported by components and consume by our host application.
2)      Host Application: Application that seeks for component to be compose.
3)      ExportLib1, ExportLib2: These are components – actual implementation of our component behavior
4)      Main Application: This uses all these.
So lets start with 1st part of our application.

1)  Create Contract library which contains IComponent interface as shown below. Through this interface our component will communicate.

namespace Contracts
{
    public interface IComponent
    {
        string Description { get; }
        string ManipulateOperation(params double[] args);
    }
}

2)      Create library ImportingLib, this contains a class that actually host and calls the components. Here one has to add System.ComponentModel.Composition assembly. Code for Importer class shown as below.

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Contracts;

namespace ImportingLib
{
    public class Importer
    {
        [ImportMany(typeof(IComponent))]
        private IEnumerable<Lazy<IComponent>> operations;

        public void DoImport()
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();

            //Add all the parts found in all assemblies in
            //the same directory as the executing program
            catalog.Catalogs.Add(
                new DirectoryCatalog(
                    Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location
                    )
                )
            );

            //Create the CompositionContainer with the parts in the catalog.
            CompositionContainer container = new CompositionContainer(catalog);

            //Fill the imports of this object
            container.ComposeParts(this);
        }

        public int AvailableNumberOfOperation
        {
            get { return operations != null ? operations.Count() : 0; }
        }

        public List<string> CallAllComponents(params double[] args)
        {
            var result = new List<string>();

            foreach (Lazy<IComponent> com in operations)
            {
                Console.WriteLine(com..Description);
                result.Add(com.Value.ManipulateOperation(args));
            }

            return result;
        }
    }
}

This host imports components implementing IComponent and lists them into private variable operations. The DoImport method initializes list. Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) gives a path in which our executing assembly resides.MEF will automatically start searching all assemblies in the  directory where the calling program resides. This is done by creating DirectoryCatelog on that folder and then adding it to the main AggregateCatelog. Property AvailableNumberOfOperation returns the number of found operations and CallAllComponents method calls all the exporting components and returns the result.

3)      As our host is ready for import functionality now major task is to develop component that exports desired functionality. For demonstration I developed two class library which contains classes that implement IComponent interface. Their code section shown as below.

using System;
using System.ComponentModel.Composition;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contracts;

namespace ExportSumLib
{
    [Export(typeof(IComponent))]
    public class SumOfNumberComponent : IComponent
    {
        public string Description
        {
            get { return "Summation of components"; }
        }

        public string ManipulateOperation(params double[] args)
        {
            string result = "";
            double count = 0;
            bool first = true;

            foreach (double d in args)
            {
                if (first)
                {
                    count = d;
                    first = false;
                }
                else
                    count += d;
                result += d.ToString() + " + ";
            }

            return result.Trim('+', ' ') + " = " + count.ToString();
        }
    }
}

Here you can see the code of SumOfNumberComponent class. This class built in ExportingLib1.dll file.
You’ve add reference for Contracts.dll and System.ComponentModel.Composition.

Same way develop another library called ExportingLib2.dll which contains SubstractOfNumberComponent class. Code of that class shown as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Contracts;

namespace ExportSubstractLib
{
    [Export(typeof(IComponent))]
    public class SubstractOfNumberComponent : IComponent
    {
        public string Description
        {
            get { return "Subtraction of components"; }
        }

        public string ManipulateOperation(params double[] args)
        {
            string result = "";
            double count = 0;
            bool first = true;

            foreach (double d in args)
            {
                if (first)
                {
                    count = d;
                    first = false;
                }
                else
                    count -= d;
                result += d.ToString() + " - ";
            }

            return result.Trim('-', ' ') + " = " + count.ToString();
        }
    }
}

Now let’s move to the final step of this exercise.

Create an application that uses all these stuffs.

4)      Develop a console application called MEFApplication. Add reference of ImportingLib.dll. now write down code section shown below.

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

namespace MEFApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = new ImportingLib.Importer();
            t.DoImport();
            Console.WriteLine("{0} component(s) are imported successfully.", t.AvailableNumberOfOperation);
            var result = t.CallAllComponents(125, 5, 10, 27, 45, 19, 10);
            foreach (string s in result)
            {
                Console.WriteLine(s);
            }
            Console.Read();
        }
    }
}

Before executing application do one thing go to the Project Properties->Build option and set building path of each application to bin\Debug folder of MEFApplication project. Now build whole project and see the magic.

You can when you execute MEFApplication project it will show 2 component(s) are imported successfully. message and rest messages. If you remove any of library from ExportingLib1.dll or ExportingLib2.dll message will change to 1 component(s) are imported successfully.




Wednesday 9 May 2012

Inversion of Control : Overview and Example


Introduction

Definition: “Inversion of Control, is an abstract principal describing an aspect of some software architecture design in which the flow of control of a system is inverted in comparison to procedural programming.”
Let’s go in simple manner what happened in procedural programming is chunk of code that uses or consumes another chunk of code, is in control of process. It knows what piece of code, which method in which class it uses and in this way it knows about some implementation detail in the code it uses.

Example






Here is a example of such scenario when a class called X uses another class called Y. The consumer class X, needs to consume the class Y, to accomplish something. This is very obvious example, but waits and thinks for a minute, does X really needs to know that it uses Y? Isn’t it enough that X knows that it uses something that has the behavior, the methods, the properties etc. of Y without knowing who actually implement the behavior? By extracting abstract definition of the behavior used by X in Y and let the consumer X to use an instance of that behavior instead of Y. This way X does same thing without knowing the specific about Y










As illustrated above class Y implement interface I and class X uses I. Here interesting matter is though class X still uses Class Y through interface I, but X doesn’t know that it uses Y, it just knows that it uses something that implement I, right now it’s Y but it would be A, B or C that implement interface I. this way we are reducing dependency of X over Y. Now you might have question in your mind, what is dependency? And how it’s dangerous for software?

What is Dependency in terms of classes?

Example mentioned in starting of this article is example of dependent classes. When class X uses any method of class Y or class Y as whole we can says that class X has some level of dependency over class Y. dependency may extend to several levels. i.e. X uses Y, Y uses A and B, A uses C and more. This way this chain go on and on. Problem with this is if we have any change in these classes, it may spawn to multiple classes. Solution of this dependency is define loose relation between classes. One way to achieve this is Inversion of Control pattern. This pattern uses Dependency Injection to eliminate tight coupling between objects. Let’s see dependency with some practical example.

A Sample Scenario
We have a class called LoggerEngine, which is used for logging messages. It had a method called Log which receives a string object as an argument and logs it into file using another class named FileLogger .








The code for LoggerEngine looks like this.















Notice above code, in which Log method creates instance of FileLogger class and then logs the message by using its own Log method. Here you may define all three method to static or there might be singleton instance of FileLogger class. Ways doesn’t matter what is the matter, dependency of LoggerEngine class over FileLogger class. We can solve this matter by creating an abstract definition of the behavior in FileLogger that LoggerEngine needs in the form of interface ILooger and making Log method use an instance of ILogger instead of  an instance of FileLogger












Now LoggerEngine no longer knows about the FileLogger class. It just uses instance of ILogger interface of which FileLogger is one of many possibly implementation. Now in fact we could easily change it so that LoogerEngine logs message on console instead of file without changing single line of code in LoggerEngine.
This all sounds good, but main question is How does LoggerEngine get instance of ILogger? Here we need a way for LoggerEngine to get an instance of ILogger at runtime without knowing about any concrete implementation. There are couple of ways to do that, one of which is through Dependency Injection.

Dependency Injection

This is basic concept for implementing inversion of control (IoC) pattern.
  1. It eliminate tight coupling between objects.
  2. Makes object and application more flexible.
  3. It facilitates to create more loosely coupled objects and their dependencies.

















Constructor Injection

Here object reference would get pass to constructor of business class LoggerEngine. In this case since LoggerEngine class depends on FileLogger class, so reference of FileLogger class will pass steps to implement Constructor Injection.

Step-1 Create an Interface


 Only method of interface will expose in business class.

Step-2 Implement interface to FileLogger class

 















Object of FileLogger class is going to be referenced by LoggerEngine class. So this class needs to be implement interface.

Step-3 Make reference of interface in LoggerEngine class











Step-4 Create a third party class, who creates instance of all this objects. 












Step 5 Use this third party class at client side.



Disadvantage of constructor injection
  • In constructor injection business logic class doesn’t have default constructor.
  • Once the class is instantiated, object dependency cannot be  changed.
Setter Injection

This uses the Properties to inject dependency. Here rather than creating a reference and assign them in constructor, it has been done in properties. By this way LoggingEngine class could have default constructor.

Step-1 Same as Constructor Injection

Step-2 Same as Constructor Injection

Step-3 LoggerEngine.cs












In LoggerEngine class, there is property Logger, which is setting and getting value of reference of interface.

Step-4 There is some changes in third party class















Step-5 Same as Constructor Injection

Advantages of Setter Injection

  • It’s more flexible than Constructor Injection.
  • Dependency of object can be change without creating any instance.
  • Dependency of object can be change without changing constructor.
  • Setters has constructive and self descriptive meaningful name that simplify understanding and using them

Interface Injection

In this instance creation is transferred to an additional interface. This interface passes as an argument in calling method.

Step-1 Same as Constructor Injection

Step-2 Same as Constructor Injection

Step-3 Create an interface and its implemented class, which creates instance.








Here one more interface and its implemented class has defined which are responsible for instance creation.

Step-4 LoggerEngine.cs








Step-5 Our third party class will be















Step-6 Same as Step-5 in Constructor Injection

Service Locator Injection

Here one Service class introduced which contains either static method or Service class may be uses singleton pattern.

Step-1 Same as Constructor Injection

Step-2 Same as Constructor Injection

Step-3 Define service class as follow






Here we have static writeonly property Logger which is uses for setting value of reference of ILogger instance and a static mettod which is uses for getting value of reference of ILogger instance

Step-4 LoggerEngine.cs







Step-5 IoCClass.cs

















Step-6 Same as Step-5 in Constructor Injection

Generic-Type Injectiom

In this method either we can define Generic LoggerEngine class or Generic method in LoggerEngine clas. Generic method would be more appropriate because if we use Generic class then it will cause same problems which are identified in Constructor Injection.

Step-1 Same as Constructor Injection

Step-2 Same as Constructor Injection

Step-3
 
Let’s define LoggerEngine class which contains generic method for writing log






Here we explicitly mentioned that our TLogger would be any reference implementation of ILogger.

Step-4

Our third party code would be as per shown below.
















Step-5 Same as in Constructor Injection

Benefits of Inversion of Controls
  • We can reduce dependency between objects and can design more flexible systems.
  • We can isolate our code at a time of unit testing.