Sunday, July 14, 2013

Import/Export MS-EXCEL file data to database in ASP.NET MVC using C#.

      This article explains about the import and export MS-Excel file to SQL server. We could achieve this goal either by copy-pasting the excel rows directly to the destined database table in SQL Server Management Studio or by querying directly on the excel sheet from SQL Server Management Studio itself. SQL server has very easy Import/Export option and Excel itself provide easy options. But i done it through ASP.NET MVC using C#.


I've created this sample excel file to import/retrieve the data in SQL server, and is also the file I will be using in this article. Here is the screenshot for the same.




IMPORT:

Create a action method in Controller
 public ActionResult ImportExcelFileToDatabase()
        {
         return view()
        }
Then, create a view for  ImportExcelFileToDatabase

@using (Html.BeginForm("ImportExcelFileToDatabase", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
    { 
<div>
       
         <input type="file" id="FileUpload"                    
                            name="FileUpload" required data-val="true" data-val-required="please select a file"/>
            
          <input type="submit" id="Submit" class="submit" value="Upload"  title="Click to upload file"/> 
        
</div>
    }

The above code looks like below screenshot....

Then, create a Player-info model

public class Player-infoModel 
    {
        public long ID { get; set; }
        public string  PlayerName { get; set; }
        public string Country{ get; set; }
        public int Matches{ get; set; }
        public int Runs{ get; set; }
        public string HS{ get; set; }
        public int Hundreds{ get; set; } 
       public int  Fifties{ get; set; }
    }

 Our requirement is to import data into SQL database from excel sheet using Asp.Net MVC. For this, we use OLEDB connection to read data from excel sheet in this post. If we have excel in .xls format then we use  
 Microsoft.Jet.OLEDB.4.0 and for .xlsx format then use Microsoft.ACE.OLEDB.12.0. 

Then, Create a POST Action method to save the data into database. Follow the below code.

        [HttpPost]
        public ActionResult ImportExcelFileToDatabase(HttpPostedFileBase file)
        {

            if (Request.Files["FileUpload"].ContentLength > 0)
            {
                string fileExtension =          
                                     System.IO.Path.GetExtension(Request.Files["FileUpload"].FileName);

                if (fileExtension == ".xls" || fileExtension == ".xlsx")
                {

// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there. 
                    string fileLocation =string.Format({0}/{1}",Server.MapPath("~/App_Data/ExcelFiles"),    
                                                                                       Request.Files["FileUpload"].FileName);

                    if (System.IO.File.Exists(fileLocation))
                        System.IO.File.Delete(fileLocation);

                    Request.Files["FileUpload"].SaveAs(fileLocation);
                    string excelConnectionString = string.Empty;

                    excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connection String for xls file format.
                    if (fileExtension == ".xls")
                    {
                        excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    }
//connection String for xlsx file format.
                    else if (fileExtension == ".xlsx")
                    {
                        
                        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }



                    //Create Connection to Excel work book and add oledb namespace
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                    excelConnection.Open();
                    DataTable dt = new DataTable();

                    dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    if (dt == null)
                    {
                        return null;
                    }

                    String[] excelSheets = new String[dt.Rows.Count];
                    int t = 0;
//excel data saves in temp file here.
                    foreach (DataRow row in dt.Rows)
                    {
                        excelSheets[t] = row["TABLE_NAME"].ToString();
                        t++;
                    }
                    OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
                    DataSet ds = new DataSet();

                    string query = string.Format("Select * from [{0}]", excelSheets[0]);
                    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                    {
                        dataAdapter.Fill(ds);
                    }
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                   
                        Player-infoModel model = new Player-infoModel ();
                        model.ID = ds.Tables[0].Rows[i]["ID"].ToString();
                        model.PlayerName = ds.Tables[0].Rows[i]["PlayerName "].ToString();
                        model.Country= ds.Tables[0].Rows[i]["Country"].ToString();
                        model.Matches= ds.Tables[0].Rows[i]["Matches"].ToString();
                        model.Runs= ds.Tables[0].Rows[i]["Runs"].ToString();
                        model.HS= ds.Tables[0].Rows[i]["HS"].ToString();
                        model.Hundreds= ds.Tables[0].Rows[i]["100"].ToString();
                         model.Fifties= ds.Tables[0].Rows[i]["50"].ToString();
                        
// SAVE THE DATA INTO DATABASE HERE. I HAVE USED WEB API HERE TO SAVE THE DATA. 
// YOU CAN USE YOUR OWN PROCESS TO SAVE.
                        MemoryStream streampost = new MemoryStream();
                        WebClient clientpost = new WebClient();
                        clientpost.Headers["Content-type"] = "application/json";

                        DataContractJsonSerializer serializerpost = new          
                         DataContractJsonSerializer(typeof(Player-infoModel ));
                        serializerpost.WriteObject(streampost, model);
//Posting data to DB.
                        string url1 = string.Format("{0}SavePlayerDetailsAPI", serviceUrl);
                        byte[] datapost = clientpost.UploadData(url1, "Post", streampost.ToArray());

                        streampost = new MemoryStream(datapost);
                        serializerpost = new DataContractJsonSerializer(typeof(string));
                        string result = (string)serializerpost.ReadObject(streampost);

                    }
                    ViewBag.message = "Information saved successfully.";
                }

                else
                {
                    ModelState.AddModelError("", "Plese select Excel File.");
                }
            }
            return View();
        }



EXPORT:
Exporting to excel can be easily achieved using CLOSEDXML tool or  you can directly copy paste from database to excel sheet. It is suitable for less data and for rare usage. But it will not easy to copy thousand's of records every time.  
Create a button to export the file. Follow the VIEW code.

@using (Html.BeginForm("ExportExcelFromDatabase", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
    { 
        <div>
         
            <input type="submit" value="PlayersList - Export to Excel" title="PlayersList  - Export to Excel"/> 
            <br />
        </div>
    }

[HttpPost]
        public void ExportExcelFromDatabase()
        {

                    //  I HAVE USED WEB API HERE TO GET THE DATA FROM DB. 
                    // YOU CAN USE YOUR OWN PROCESS TO RETRIVE.
            string webServiceUrl = String.Format("{0}APIForPlayerList", serviceUrl);
            string formattedUrl = webServiceUrl + "?typeForFeed=Cricket";

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(formattedUrl);
            HttpWebResponse webResponce = (HttpWebResponse)webRequest.GetResponse();

            string Responce = string.Empty; 
            using (StreamReader sr = new StreamReader(webResponce.GetResponseStream()))
            {
               Responce = sr.ReadToEnd();
            }
//SAVE THE DATA IN LIST             
    JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Player-infoModel > PlayerList = serializer.Deserialize<List<Player-infoModel>>    (Responce);

// install closedXML(third-party) tool to your project and  add namespace " using ClosedXML.Excel;".
            XLWorkbook wb = new XLWorkbook(); 
            string sheetName = "Players"; //Give name for export file. 
            var ws = wb.Worksheets.Add(sheetName);
            ws.Cell(2, 1).InsertTable(PlayerList );  // assign list here.
            HttpContext.Response.Clear();
            HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            HttpContext.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));

            using (MemoryStream memoryStream = new MemoryStream())
            {
                wb.SaveAs(memoryStream);
                memoryStream.WriteTo(HttpContext.Response.OutputStream);
                memoryStream.Close();
            }

            HttpContext.Response.End();;

        }

//Finally, Excel file in your downloads.





Read More »

Sunday, May 19, 2013

Push Messages to GCM server using c#.net application (server side).

      Google Cloud Messaging (GCM) is a service that helps developers send data from servers to their Android applications on Android devices. Google Cloud Messaging (GCM) replaces the beta version of Android Cloud to Device Messaging (C2DM).
The free service has the ability to send a lightweight message informing the Android application of new data to be fetched from the server. Larger messages can be sent with up to 4 KB of payload data.

This tutorial explains about how to send message to GCM server using .net application. Then GCM server pushes the messages to particular devices.
1. First, create new web application (File/new/website/Asp.Net Empty web site).
2. Design your page like below



 Data Post Format


{   "collapse_key": "score_update",     "time_to_live": 108,       "delay_while_idle": true,
     "data": {
     "score": "223/3",
     "time": "14:13.2252"
                  },
     "registration_ids":["4", "8", "12", "16", "25", "38"]
}

collapse_key             = Message type                                                                          
time_to_live               = How long (in seconds) the message should be kept on     
                                                              GCM storage if the device is offline (default:4 weeks).       
delay_while_idle       = It indicates that the message should not be sent                  
                                                                immediately if the device is idle. The server will                 
                                                                wait for the device to become active, and then only the     
                                                                last message for each collapse_key value will be sent      
data                             = Message Paylod.                                                                                            
 registration_ids         = A string array with the list of devices (registration IDs)
                                                               receiving the message. It must contain at least 1 and at     
                                                               most 1000 registration IDs. To send a multicast message,    
                                                               you must use JSON. 


3. Write a method in OnClick() function of send button. The code follows


protected void SubmitButton1_Click(object sender, EventArgs e)                                                             
        {                                                                                                                                                  
         AndroidPush();  // calling android push method                                                                               
        }                                                                                                                                                  
                                                                                                                                                           
//Android push message to GCM server method                                                                                       
private void AndroidPush()                                                                                                                      
        {                                                                                                                                                   
 // your RegistrationID paste here which is received from GCM server.                                                               
       string regId = "APA91bG_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_V6hO2liMx-                   
                           eIGAbG2cR4DiIgm5Q";                                                                                              
 // applicationID means google Api key                                                                                                     
       var applicationID = "AIzaSyDScBxxxxxxxxxxxxxxxxxxxpv66IfgA";                                                         
// SENDER_ID is nothing but your ProjectID (from API Console- google code)//                                          
                var SENDER_ID = "77xxxxx625";                                                                                            

                var value = Text1.Text; //message text box                                                                               

                WebRequest tRequest;                                                                                                           

                tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");                             

                tRequest.Method = "post";                                                                                                       

                tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";                             

                tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));                              

               tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));                                         

         //Data post to server                                                                                                                                         
         string postData =     
              "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="         
               + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" +      
                  regId + ""; 


                                                                                                            

                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);                                                

                tRequest.ContentLength = byteArray.Length;                                                                  

               Stream dataStream = tRequest.GetRequestStream();                                                    

               dataStream.Write(byteArray, 0, byteArray.Length);                                                          

               dataStream.Close();

               WebResponse tResponse = tRequest.GetResponse();                                                  

               dataStream = tResponse.GetResponseStream();                                                            

              StreamReader tReader = new StreamReader(dataStream);                                          

              String sResponseFromServer = tReader.ReadToEnd();   //Get response from GCM server.

               Label3.Text = sResponseFromServer;      //Assigning GCM response to Label text 

                 tReader.Close();                                                                                                                    

                dataStream.Close();                                                                                                             
                tResponse.Close();                                                                                                              
               }                                            


Note: The above code is for sending single regID. To send mutiple regID's, you can send up-to 1000 regID's to google server once or you can loop the code.  
                                  
4. After clicking send button you will get response from GCM server like id=343kdhgsy4y32i42@adfgd. It means that you successfully sent message to GCM server.


  You will get message in your mobile like this..


For GCM Client side tutorial click here. Download the GCM C# server side code below.
                                     
                                                        
                         
                                     
                                      

Enjoy coding.....




Read More »

Saturday, May 18, 2013

How to create Facebook Hash key for android apps ?

After a lot of search i found that how to create Facebook hash key for android apps in both modes i.e debug and release modes.

 Steps to create Hash key:

 1. First download oppenssl. click here to download openssl for windows. Download either 32 bit or 64 bit according to your system requirement.
  2. Extract and copy it to your specific location.
 There are two processes to generate Facebook hash-key. one is from command prompt and another via code.

Process 1(Command prompt): 

3. Firstly, open your cmd prompt and change your directory to your java jdk path.

4. Find debug.keystore from your android sdk install path like C:\Users\Teja\.android\debug.keystore. In case of RELEASE MODE key, copy  yourProject.keystore. This one more important to generate your perfect hash key. Otherwise you will get an error like APP MISS_CONFIGURED.

5. And then find your openssl\bin copied & extracted location.

And follow the sample cmd prompt below:

 C:\Program Files\Java\jdk1.7.0_05\bin>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Teja\.android\debug.keystore" | "C:\Openssl\bin\openssl" sha1 -binary |"C:\Openssl\bin\openssl" base64

6. Run it and provide some password like 'android'. It will generates you hash key like below..


Process 2 (Using method call from android code):

Use below code snippet to get hash key.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Add code to print out the key hash

    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.facebook.sample.facebook",  //Replace your package name here
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {


    }

Save your changes and re-run the sample. Check your log-cat output for a message similar to this:

Note: For release key, run your apk with eclipse then you will get hash key like above.

7. Paste your Facebook Hash key in your Facebook app (https://developers.facebook.com/apps)
8. Go to Native Android Apps and paste your hash key in there.


Enjoy with your first android  Facebook app..........  
Read More »