Friday, March 29, 2013

C# Code to deserialize a Byte[] Array into DataTable


In WCF, sometimes we get a ByteArray as an output data contract and we want to deserialize that ByteArray into a DataTable.
Here we could get an idea how we can deserialize a ByteArray into DataTable.  DataTable becomes useful int the situations when we want to save data into database using DataAdapter by passing a DataSet.
In this code, we create a MemoryStream object by passing byte array and then using BinaryFormatter, we can directly deserialize MemoryStream object into DataTable.


 
 private DataSet DeserailizeByteArrayToDataSet(byte[] byteArrayData)  
     {  
       DataSet tempDataSet = new DataSet();  
       DataTable dt;  
       // Deserializing into datatable    
       using (MemoryStream stream = new MemoryStream(byteArrayData))  
       {  
         BinaryFormatter bformatter = new BinaryFormatter();  
         dt = (DataTable)bformatter.Deserialize(stream);  
         if (dt != null)  
         {  
           foreach (DataRow row in dt.Rows)  
           {  
             Console.WriteLine("----------------------");  
             Console.WriteLine("PostalCode:" + row["POSTAL_CODE"]);  
             Console.WriteLine("CountryCode:" + row["COUNTRY_CODE"]);  
             Console.WriteLine("ProcessNumber:" + row["PROCESS_NUMBER"]);  
             Console.WriteLine("ProcessStatus:" + row["PROCESS_STATUS"]);  
             Console.WriteLine("TimeStamp:" + row["TIMESTAMP"]);  
             Console.WriteLine("----------------------");  
           }  
         }  
       }  
       // Adding DataTable into DataSet    
       tempDataSet.Tables.Add(dt);  
       return tempDataSet;  
     }  







Thanks,
Hemant

Friday, February 15, 2013

Concatenate Columns in SQL


In this way we can concatenate two columns in SQL:

  SELECT 
  
  CONVERT(NVARCHAR(50),[COLUMN_1] 
  + '-'+ 
  CONVERT(NVARCHAR(50),[COLUMN_2])) AS COMBINED 
  
  FROM [TABLE_1]
  WHERE [COLUMN_1] = 'SOME_THING'

Tuesday, February 12, 2013

List.ToLookup Example in C#



Sometimes when we have a list of objects and we need to look up that collection by a member item in the object, we could easily benefit from converting a List collection into a Lookup collection. For example, we need to look up an entire product's inventory in a store by their Supply Date or by their price etc.
             So, to get a Lookup from a list we use the extension method "ToLookup" available in a List collection's extension methods.

I wrote an article on this topic recently for CShap Corner Site. Please go through following link:

http://www.c-sharpcorner.com/UploadFile/0f68f2/creating-a-lookup-from-a-list-of-objects-using-lambda-expres/