Showing posts with label Export. Show all posts
Showing posts with label Export. Show all posts

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.