Archive

Archive for May, 2013

Serialize and Deserialize JSON using JSON.NET

May 22, 2013 Leave a comment

An awesome tool to convert json string to objects and back to json – JSON.NET
Get it from here
http://james.newtonking.com/projects/json-net.aspx

   //Deserialize
   WebClient wc = new WebClient();         
   string jsonStr = wc.DownloadString("http://example/api/GetAllBrandIds.aspx");
   JObject obj = JObject.Parse(jsonStr);
   JToken jt = obj["IdType"];
   BrandSet bs;
   List<BrandSet> list = new List<BrandSet>();
   foreach(JToken j in jt)
   {
   bs = new BrandSet(); 
   bs.ID = Convert.ToInt32((string)(j["Id"]));                
   bs.ImageType = Convert.ToInt32((string)(j["ImageType"]));
   list.Add(bs);
   }
  //Serialize back to json
  string jsonStr = JsonConvert.SerializeObject(list);
  

Happy coding:)

Read Excel file from ASP.NET C#

May 15, 2013 1 comment

Really excited to get a snippet that reads the excel file as database table:)

Sample code below

        string connStrExcel = "";
        if (type.Equals("xlsx"))
        {
          connStrExcel = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourExcelFilePath.xlsx;Extended Properties=Excel 12.0";
        }
        else
        {
          connStrExcel = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourExcelFilePath.xls;Extended Properties=Excel 8.0";
        }
        OleDbConnection oledbConn = new OleDbConnection(connStrExcel);
        DataTable tab = new DataTable();

        try
        {   //Open connection
            oledbConn.Open();
           // Create OleDbCommand object and select data from worksheet Sheet1
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
           // Create new OleDbDataAdapter
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
            // Fill the DataTable from the data extracted from the worksheet.
            oleda.Fill(tab);
        }
        finally             '
        {
           oledbConn.Close();
        }

Happy Coding:)

Categories: ASP.NET Tags: