Friday 24 April 2015

How to convert a DataTable into JSON format in c# asp.net ?

Here I am writing a c# program that will convert a DataTable into JSON formate. First I created a DataTable and then inserted 5 Rows into it, then passed to a method ConvertDataTableToJSON(DataTable dt) and it will return a JSON string.

Source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using System.Data;
using System.Globalization;
using Newtonsoft.Json;

namespace ConsoleDemoApp
{
    class ConvertDataTableToJSON
    {

     protected void Page_Load(object sender, EventArgs e)
     {
         try{
                // Create datatable first
               DataTable dt= GetTable();
                // Convert it into JSON formate.
             String jsonString=  ConvertDataTableToJson(dt);

               }
            catch(Exception ex)
            {
                //catch the exception and write to txt file
                writeInFile(ex.ToString());
            }
      }

// Create DataTable and insert some rows.
       protected DataTable GetTable()
        {
            // Here we create a DataTable with four columns.
            DataTable table = new DataTable();
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Gender", typeof(string));
            table.Columns.Add("Email", typeof(DateTime));

            // Here we add five DataRows.
            table.Rows.Add(1, "Ram", "Male", "abc@gmail.com");
            table.Rows.Add(2, "Shyam", "Male", "abc@gmail.com");
            table.Rows.Add(3, "Kavita", "Female","abc@gmail.com");
            table.Rows.Add(4, "Suman", "Female", "abc@gmail.com");
            table.Rows.Add(4, "Naveen", "Male","abc@gmail.com");

            return table;
        }

   // Method to convert.
        protected string ConvertDataTableToJson(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new
            System.Web.Script.Serialization.JavaScriptSerializer();

            List<Dictionary<string, object>> DtRows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> newrow = null;

            //Code to loop each row in the datatable and add it to the dictionary object
            foreach (DataRow drow in dt.Rows)
            {
                newrow = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    newrow.Add(col.ColumnName.Trim(), drow[col]);
                }
                DtRows.Add(newrow);
            }

            //Serialising the dictionary object to produce json output

            JSSerializer.MaxJsonLength = Int32.MaxValue;

            return JSSerializer.Serialize(DtRows);
        }


   // Write exception to text file
        static void writeInFile(string excep)
        {
            // it will get base directory path but you can change it.
            string path = AppDomain.CurrentDomain.BaseDirectory;
            String dir = Path.GetDirectoryName(path);
            dir += "\\Error\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string newFileName = string.Format("{0:dd-MMM-yyyy_hh-mm-ss-tt}" + ".txt", DateTime.Now);
            string filepath = dir + newFileName;
            if (!File.Exists(filepath))
            {
                File.Create(filepath).Close();
            }
            using (StreamWriter w = File.AppendText(filepath))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Excepation :" + excep;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
  }
}


Output in JSON format


          [
             {
"Id": "1",
"Name": "Ram",
"Gender": "Male",
"Email": "abc@gmail.com",
    },
{
"Id": "2",
"Name": "Shyam",
"Gender": "Male",
"Email": "abc@gmail.com",
    },
{
"Id": "3",
"Name": "Kavita",
"Gender": "Female",
"Email": "abc@gmail.com",
    },
{
"Id": "4",
"Name": "Suman",
"Gender": "Female",
"Email": "abc@gmail.com",
    },
{
"Id": "5",
"Name": "Naveen",
"Gender": "Male",
"Email": "abc@gmail.com",
    }
]

How to write a Exception to Text file in c# asp.net

Here I am writing a program, program, throw a exception in try block then it catch by catch block.
finally pass this exception to method called writeInFile(string excep) and this method will write
the thrown exception in text file in the base directory by default.

source code:-

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

namespace ConsoleDemoApp
{
    class WriteException
    {
        /* program to write a exception in c# */
       
        static void Main(string[] args)
        {
            int numerator=100;
            int Denominator=0;
            try{
                // throw a exception
                 int result=   numerator/Denominator;
                 Console.ReadKey();
               }
            catch(Exception ex)
            {
                //catch the exception and write to txt file
                writeInFile(ex.ToString());
            }
           
        }

        static void writeInFile(string excep)
        {
            // it will get base directory path but you can change it.
            string path = AppDomain.CurrentDomain.BaseDirectory;
            String dir = Path.GetDirectoryName(path);
            dir += "\\Error\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string newFileName = string.Format("{0:dd-MMM-yyyy_hh-mm-ss-tt}" + ".txt", DateTime.Now);
            string filepath = dir + newFileName;
            if (!File.Exists(filepath))
            {
                File.Create(filepath).Close();
            }
            using (StreamWriter w = File.AppendText(filepath))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Excepation :" + excep;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
    }
}

Output