Saturday, July 20, 2013

Shake Animation in android.

      This tutorials explains you about Shake animation in android. Now you can validate the required fields with shake animation rather than set error and toast message.




activity_main.xml  code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Registration"
        android:textSize="22sp"
        android:textColor="#0099FF"/>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/Name"
        android:ems="10" 
         android:layout_marginTop="20dp"
       
        <requestFocus />
    </EditText>
    
    
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/Email"
        android:ems="10"  android:layout_marginTop="5dp"
      </EditText>
    


    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:hint="@string/password"
        android:ems="10" 
        android:password="true" android:layout_marginTop="5dp"
       </EditText>

<LinearLayout 
    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="Onsubmit"
        android:text="@string/submit"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="Onreset"
        android:text="@string/reset"
       />

    </LinearLayout>

</LinearLayout>

Add anim folder in Android resources. Then create a new XML file in anim named as shakeanim.xml.

Shakeanim.xml code: 

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="0"
    android:interpolator="@android:anim/cycle_interpolator"

    android:toXDelta="10" />


ShakeActivity Code:

public class shakeActivity extends Activity {
EditText name,email,password;
Animation shake;

      @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

name=(EditText)findViewById(R.id.editText1);
email=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.editText3);
 //Load Shake Animation xml file here
shake = AnimationUtils.loadAnimation(this, R.anim.shakeanim);

}
//Submit button Onclick code...
public void Onsubmit(View view)
{
if(name.getText().toString().length()==0)
                  {
//Animation works here...
name.startAnimation(shake);
                  }
               //remaining code here......

}
public void Onreset(View view)
{
//reset code here
}

}



By default, it rotates only one cycle. If you want custom cycles then create a another xml file in anim folder named as cycles.xml.
android:cycles represents no.of cycles.

Cycles.xml code:

<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:cycles="4" />
And change the android:interpolator in Shakeanim.xml.

Shakeanim.xml code:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="10000"
    android:fromXDelta="0"
    android:interpolator="@anim/Cycles"
    android:toXDelta="10" />

Enjoy.......


Read More »

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 »