Sunday, January 5, 2014

XML SAX Parsing in Android

     This tutorial explains you about the SAX parsing in Android. SAX (Simple API for XML) is an event-based sequential access parser API. SAX provides a mechanism for reading data from an XML document that is an alternative to that provided by the Document Object Model (DOM). Where the DOM operates on the document as a whole and takes more memory to store, SAX parsers operate on each piece of the XML document sequentially. Generally, SAX parsing is suitable more for large files.
Usually, Android applications need to call third-party service API's. We have so many data formats like json, xml, wddx, yaml, php, dump etc,. But we use mostly xml and json formats to transfer data.

XML Data Format:

XML was created to structure, store and transport data. It will be easily readable by the humans as well machines. Follow the sample XML format. I am saving this data named studentDetails.xml in  res/raw folder.

<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<no>1</no>
<name>sachin</name>
<class>Computers</class>
<phno>1234567890</phno>
<email>sachin@gmail.com</email>
</student>

<student>
<no>2</no>
<name>Ganguly</name>
<class>EEE</class>
<phno>1234567890</phno>
<email>Ganguly@gmail.com</email>
</student>

<student>
<no>3</no>
<name>Dravid</name>
<class>CSE</class>
<phno>1234567890</phno>
<email>Dravid@gmail.com</email>
</student>

<student>
<no>4</no>
<name>Laxman</name>
<class>CSIT</class>
<phno>1234567890</phno>
<email>Laxman@gmail.com</email>
</student>

<student>
<no>5</no>
<name>Kumble</name>
<class>MCA</class>
<phno>1234567890</phno>
<email>Kumble@gmail.com</email>
</student>

</students>



How to Parse XML data?

Now, we need to parse the above xml data in android. Follow the step by step process below.

First, Open or create your project.
Then, create an xml layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:paddingLeft="10dp" >
  
  <TextView
  android:id="@+id/SNoText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" />
  
  <TextView
  android:id="@+id/SNameText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textStyle="bold" />
  
  <TextView
  android:id="@+id/SClassText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
  
  <TextView
  android:id="@+id/SPhoneText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" />
  
  <TextView
  android:id="@+id/SEmailText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" />

</LinearLayout>



Now, start your activity code. Create an ListActivity named SaxParserDemoActivity. And follow the below code.



package com.prakash_saxparser;

import java.io.InputStream;

import java.util.ArrayList;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class SaxParserDemoActivity extends ListActivity {


      //Decalre String Arrays here

ArrayList<String> al_studentNo=new ArrayList<String>();
ArrayList<String> al_studentName=new ArrayList<String>();
ArrayList<String> al_studentClass=new ArrayList<String>();
ArrayList<String> al_studentPhno=new ArrayList<String>();
ArrayList<String> al_studentEmail=new ArrayList<String>();

SAXParserFactory spf;
SAXParser sp;
XMLReader xr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try{
          //Getting student data from Raw folder here.
        InputStream is=getResources().openRawResource(R.raw.studentdetails);
               
        spf=SAXParserFactory.newInstance();
        sp=spf.newSAXParser();
        xr=sp.getXMLReader();
       
        MyHandler mh=new MyHandler();
        xr.setContentHandler(mh);
       
        xr.parse(new InputSource(is));
        }
        catch(Exception e){}
setListAdapter(new MyAdapter());
       
}

//Created Adapter class.

class MyAdapter extends BaseAdapter{

@Override

public int getCount() {
// TODO Auto-generated method stub
return al_studentClass.size(); 
}

@Override

public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}

@Override

public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}

@Override

public View getView(int arg0, View arg1, ViewGroup arg2) {
LayoutInflater li=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View v=li.inflate(R.layout.saxlayout, null); //Applying layout.
//Setting data to layout.
TextView tv1=(TextView)v.findViewById(R.id.SNoText);
tv1.setText(al_studentNo.get(arg0));

TextView tv2=(TextView)v.findViewById(R.id.SNameText);
tv2.setText(al_studentName.get(arg0));

TextView tv3=(TextView)v.findViewById(R.id.SClassText);
tv3.setText(al_studentClass.get(arg0));

TextView tv4=(TextView)v.findViewById(R.id.SPhoneText);
tv4.setText(al_studentPhno.get(arg0));


TextView tv5=(TextView)v.findViewById(R.id.SEmailText);
tv5.setText(al_studentEmail.get(arg0));

return v;
}
   
    }
    //Creating MyHandler class.
    //starting......fill.......ending.....
    class MyHandler extends DefaultHandler{
    boolean is_studentNo=false;
    boolean is_studentName=false;
    boolean is_studentClass=false;
    boolean is_studentPhno=false;
    boolean is_studentEmail=false;
   
   
    @Override
    public void startDocument() throws SAXException {
    // TODO Auto-generated method stub
    super.startDocument();
    }
   
    @Override
    public void startElement(String uri, String localName, String name,
    Attributes attributes) throws SAXException {
    super.startElement(uri, localName, name, attributes);
    if(localName.equals("no")){
    is_studentNo=true;
    }
    else if(localName.equals("name")){
    is_studentName=true;
    }
    else if(localName.equals("class")){
    is_studentClass=true;
    }
    else if(localName.equals("phno")){
    is_studentPhno=true;
    }
    else if(localName.equals("email")){
    is_studentEmail=true;
    }
    }
   
    @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    // TODO Auto-generated method stub
    super.characters(ch, start, length);
    if(is_studentNo){
    al_studentNo.add(new String(ch,start,length));
    }
    else if(is_studentName){
    al_studentName.add(new String(ch,start,length));
    }
    else if(is_studentClass){
    al_studentClass.add(new String(ch,start,length));
    }
    else if(is_studentPhno){
    al_studentPhno.add(new String(ch,start,length));
    }
    else if(is_studentEmail){
    al_studentEmail.add(new String(ch,start,length));
    }
    }
   
    @Override
    public void endElement(String uri, String localName, String name)
    throws SAXException {
    // TODO Auto-generated method stub
    super.endElement(uri, localName, name);
   
    if(localName.equals("no")){
    is_studentNo=false;
    }
    else if(localName.equals("name")){
    is_studentName=false;
    }
    else if(localName.equals("class")){
    is_studentClass=false;
    }
    else if(localName.equals("phno")){
    is_studentPhno=false;
    }
    else if(localName.equals("email")){
    is_studentEmail=false;
    }
    }
   
    @Override
    public void endDocument() throws SAXException {
    // TODO Auto-generated method stub
    super.endDocument();
    }
    }
}


Result screen:



How to get Web Service Data?
The above example shows you how to read stored file in application. But if you want to read the data from outside the application like web-services. Replace below code to above one.

//URL
String ServiceURL="http://10.0.12.1/MySampleService/Service.asmx/GetStudentData?UserID="+1;

spf=SAXParserFactory.newInstance();

      sp=spf.newSAXParser();
      xr=sp.getXMLReader();
      URL sourceUrl = new URL(ServiceURL);  
      MyHandler mh=new MyHandler();
      xr.setContentHandler(mh);
     
      xr.parse(new InputSource(sourceUrl.openStream()));

 Add internet permission in AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Enjoy coding!!!!!!!!!!

Read More »

Wednesday, December 25, 2013

XML DOM Parsing in Android.

      The Document Object Model (DOM) is an API for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way of documents accessed and manipulated. It is a hierarchy-based parser that creates the object model for an entire model. It is highly recommended  for the small sized files or data because it store the data in memory. It is faster than the SAX parser.

XML Data Format:

  XML was created to structure, store and transport data. It will be easily readable by the humans as well machines. Follow the sample XML format. I am saving this data named studentDetails.xml in  res/raw folder.

<?xml version="1.0" encoding="UTF-8"?>
<students>
 <student>
  <no>1</no>
  <name>Tendulkar</name>
  <class>Computers</class>
  </student>

 <student>

  <no>2</no>
  <name>Ganguly</name>
  <class>EEE</class>
 </student>

 <student>

  <no>3</no>
  <name>Dravid</name>
  <class>CSE</class>
 </student>

 <student>

  <no>4</no>
  <name>Laxman</name>
  <class>CSIT</class>
  </student>

 <student>

  <no>5</no>
  <name>Kumble</name>
  <class>MCA</class>
  </student>

</students>



XML layout:
Create a xml layout to display the DOM results.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NOtext"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Nametext"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Classtext"
    />
</RelativeLayout>

DomParserActivity:


package com.prakash_domparserdemo;

import java.io.InputStream;


import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;

import android.os.Bundle;
import android.widget.TextView;

public class DomParserActivity extends Activity {

TextView notxt,nametxt,classtxt;  
 
@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.domparser);  
notxt=(TextView)findViewById(R.id.NOtext); 
nametxt=(TextView)findViewById(R.id.Nametext); 
classtxt=(TextView)findViewById(R.id.Classtext); 
try {  
InputStream is = getAssets().open("details.xml");  
 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
Document doc = dBuilder.parse(is);  
 
Element element=doc.getDocumentElement();  
element.normalize();  
 
NodeList nList = doc.getElementsByTagName("student");  
for (int i=0; i<nList.getLength(); i++) {  
 
Node node = nList.item(i);  
if (node.getNodeType() == Node.ELEMENT_NODE) {  
Element element2 = (Element) node;  
notxt.setText(notxt.getText()+"\nNo : " + getValue("no", element2)+"\n");  
nametxt.setText(nametxt.getText()+"Name : " + getValue("name", element2)+"\n");  
classtxt.setText(classtxt.getText()+"Class : " + getValue("class", element2)+"\n");
 
}  
}
    
} catch (Exception e) {e.printStackTrace();}  
 
}  
private static String getValue(String tag, Element element) {  
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();  
Node node = (Node) nodeList.item(0);  
return node.getNodeValue();  
}  
 
}  


Result screen:


Enjoy Coding!!!!



Read More »

Thursday, November 14, 2013

HTTP Requests to Rest-WCF/Web API service from C# MVC Apllication

      This tutorial explains you about the how to make HTTP requests to Rest-WCF/Web API service from C# MVC Client Application. HTTP is designed to enable communication between client and server. It works as a request-response between client and server. HTTP request methods are GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE and CONNECT. We use most commonly  POST, GET, PUT and DELETE methods. These methods correspond  to create, read, update and delete (CRUD) operations.

HTTP Post Method:
The HTTP POST is most-often utilized for creation of new resources. It simply submits data into specified resource.
I have created UserDetails model.

public class UserDetails
    {

        public int UserId { get; set; }
        public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email{ get; set; }
       public string Password{ get; set; }
       public string Phone{ get; set; }
    }



CODE:

//POST
public ActionResult SignUp()
        {
           UserDetails model = new UserDetails();
           WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
         
            model .UserId = 0;
            model .FirstName = "Teja";
            model .LastName = "Prakash";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"      

            DataContractJsonSerializer serializerpost = new                                                                                             DataContractJsonSerializer(typeof(UserDetails ));
         
            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/Signup",              "POST", streampost.ToArray());

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

            return View();
        }



HTTP Get Method:
The HTTP GET method is used to retrieve (or read) a representation of a resource. HTTP response codes- 200(OK), 404(NOT FOUND), 400(BAD REQUEST).

CODE:
   //GET
public ActionResult GetUserDetails(int userid)
        {

           UserDetails model = new UserDetails();

            string formatted_uri = string.Format("http://localhost:60273/PrakashSampleService.svc/{0}", userid);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(formatted_uri);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            string json_response = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                json_response = sr.ReadToEnd();
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            model  = serializer.Deserialize<model >(json_response);


            return View(model);

        }

HTTP PUT Method:
HTTP PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

CODE:
//PUT
public ActionResult UpdateProfile()
        {
           UserDetails model = new UserDetails();
       
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
       
            model .UserId = 1;
            model .FirstName = "Teja";
            model .LastName = "Prakash rao";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"  

            DataContractJsonSerializer serializerpost = new                                                                                            DataContractJsonSerializer(typeof(UserDetails ));

            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/UpdateProfile",  "PUT",streampost.ToArray());

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

            return View();
        }

HTTP Delete Method:
HTTP DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

CODE:
//DELETE
public ActionResult DeleteUser(int userid)
        {
         
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
     
            DataContractJsonSerializer serializerpost = new  DataContractJsonSerializer(typeof(String));
            serializerpost.WriteObject(streampost, userid);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/DeleteUser", "DELETE", streampost.ToArray());

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

            return View();


        }


This process works fine for both REST WCF and WEB API services.
Enjoy.....!!!!!
Read More »

Sunday, October 13, 2013

WCF Restful Service example.

      This tutorial explains you about a Restful WCF service. Windows Communication Foundation (WCF) is a tool usually used to implement and deploy a service-oriented architecture (SOA).Clients can consume multiple services; services can be consumed by multiple clients. Services are loosely coupled to each other.
WCF implements many advanced Web services (WS) standards such as WS-Addressing, WS-ReliableMessaging and WS-Security. With the release of .NET Framework 4.0, WCF also provides RSS Syndication Services, WS-Discovery, routing and better support for REST services.

ENDPOINTS:

A WCF service communicates with the world through end point only. Endpoints remember like 'ABC'.
A- Address
B-Binding
C-Contract

Address (WHERE): It specifies about the service location. Clients will use the URL to communicate with the service.
Address format of WCF transport schema look like below
[transport]://[machine or domain][:optional port]

WCF supports transport schemas like HTTP, TCP, IPC, MSMQ and Peer Network.
Examples:
HTTP address format: http://localhost/5124/service
TCP address format: net.tcp://localhost/5124/service
IPC address format: net.pipe://localhost/5124/pipe
MSMQ address format: net.msmq://localhost/5124/service


Binding (HOW): It specifies about communication type i.e. how client  can connect with the service or using which protocols finds the services (SOAP, HTTP, TCP, MSMQ etc.).
WCF supports 9 types of Bindings:
1. BasicHttpBinding: Basic Web service communication. This is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services. No security by default.
2. WsHttpBinding: It  uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
3. WsDualHttpBinding: It is similar to the Ws Binding except it also support the duplex contract.
4. WsFederationHttpBinding: It supports federated security and transaction.
5. MsmqIntegrationBinding: It communicates directly with MSMQ application. It supports transaction.
6. NetMsmqBinding: This uses MSMQ for transport and is designed to offer support for disconnected queued calls. It supports transaction.
7. NetNamedPipeBinding/IPC binding: This uses named pipes as a transport for same-machine communication. This binding won't accept the outside calls. It supports duplex contract and transactions.
 8. NetPeerTCPBinding: This uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it. It supports duplex contracts.
9. NetTcpBinding/Tcp Binding: Communication between WCF Service across computers. It supports duplex contracts, reliability and transaction.

Contract (WHAT): It specifies the interface between client and server. It identifies what is exposed by the service.
WCF defines 4 types of contracts

Service Contract: It describes which operations the client can perform on the service. There are 2 types of Service Contracts are:
1. ServiceContract: This attribute is used to define the interface.
2. OperationContract: This attribute is used to define the method inside the interface.

DataContracts: It defines the data types, that are passed from and to the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are 2 types of Data Contracts are
1. DataContract: This attribute is used to define the class.
2. DataMember: This attribute is used to define the properties.

Message Contract: It allows the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Fault Contracts: It define which errors are raised by the service, and how the service handles and propagates errors to its clients. It is easy to find, what errors has occurred.

Here, I have given info about Endpoints because it is very important for any WCF application.

How to create Basic WCF Service Application using VS 10/12:

1. Click on New Project. Then select WCF Service Application under WCF.



2. You will get solution like below


By default, you will get 'Hello' method with BasicHttpBinding. Now, you have to do your own work here.
The actual code starts from here. First, design your model by creating new class. We are using Data Contracts concept here. Have a look at below code.

 [DataContract]
    public class UserModel
    {
        [DataMember]
        public int UserId { get; set; }
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public int Phone { get; set; }

    }

Then create a interface for the service i.e. give the operations which is operated by clients. Here, we are using Service Contract concept. It supports POST, GET, DELETE and PUT modes.  Follow the below code.

[ServiceContract]
    public interface IPrakashSampleService
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/SignUp",
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool SignUp(UserModel user);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle =                         WebMessageBodyStyle.WrappedRequest, UriTemplate = "GetUserDetails/{UserId}")]      
        UserModel GetUserDetails(string UserId);


        [OperationContract]
        [WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json, BodyStyle =                 WebMessageBodyStyle.WrappedRequest, UriTemplate = "DeleteUser/{UserId}")]      
        UserModel DeleteUser(string UserId);

        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/UpdateUser",
         RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool UpdateUser(UserModel user);

    }


Now, do some required changes in WEB.CONFIG file for REST.
Create a connection string to your DataBase.

<connectionStrings>
   
    <add name="SampleServices" connectionString="data source=TEJA-PC;Initial Catalog=DBNAME;User ID=USERNAME;Password=PASSWORD;" providerName="System.Data.SqlClient" />
 
  </connectionStrings>

  Then change the binding to webHttpBinding and declaring address, binding and contract. Follow the below code.

<system.serviceModel>
    <services>
      <service name="Prakash_RestWcfSample.PrakashSampleService" behaviorConfiguration="ServiceBehaviour">

        <endpoint address=""  binding="webHttpBinding" contract="Prakash_RestWcfSample.IPrakashSampleService" behaviorConfiguration="web">

        </endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBinding" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp automaticFormatSelectionEnabled="false" helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
         <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
         </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>

Now, time to write service methods in PrakashSampleService.svc. I have used SQL Server STORED_PROCEDURES here. But, we can use LINQ queries also.

First, declare a connection string.
   
 string strcon = ConfigurationManager.ConnectionStrings["SampleServices"].ToString();
        SqlConnection con = null;
        SqlCommand cmd = null;
        SqlDataAdapter da = null;
        DataSet ds = null;

// POST METHOD

 public bool SignUp(UserModel userInfo)
        {

                using (con = new SqlConnection(strcon))
                {
                    cmd = new SqlCommand() { Connection = con, CommandText =                                     "Proc_SaveUserDetails", CommandType = CommandType.StoredProcedure };             

                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                        cmd.Parameters.AddWithValue("@UserID", userInfo.UserId);
                   
                        cmd.Parameters.AddWithValue("@FName", userInfo.FirstName);
                        cmd.Parameters.AddWithValue("@LName", userInfo.LastName);
                        cmd.Parameters.AddWithValue("@Email", userInfo.Email);
                        cmd.Parameters.AddWithValue("@Password", userInfo.Password);
                        cmd.Parameters.AddWithValue("@Phone", userInfo.Phone);

                        cmd.Parameters.Add("@Message", SqlDbType.VarChar, 50).Direction =                                                    ParameterDirection.Output;  
              
                        cmd.ExecuteNonQuery();
                       
                        string message = cmd.Parameters["@Message"].Value.ToString();
                        if (message == "Sucess")
                        {
                           
                            //do something here.

                        }
                        else
                        {
                            //do something here.
                        }
                    }
                    con.Close();

                }
                return true;
         
        }

//GET Method

 public UserModel GetUserDetails(string userid)
        {
            UserModel getuserdetails = new UserModel();
           
            using (con = new SqlConnection(strcon))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                    cmd = new SqlCommand() { Connection = con, CommandText = "Proc_GetUserDetails",  CommandType = CommandType.StoredProcedure };                          
                    cmd.Parameters.AddWithValue("@UserID", userid);
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {

                        getuserdetails.UserId = (int)reader["UserId"];
                        getuserdetails.FirstName = reader["FirstName"].ToString();
                        getuserdetails.LastName = reader["LastName"].ToString();
                        getuserdetails.Email = reader["Email"].ToString();
                        getuserdetails.Phone = (int)reader["Phone"];

                    }

                }
            }
            return getuserdetails;
        }



For help : your_service_url/help.You will find the all methods like below screen.
Ex: http://localhost:60273/PrakashSampleService.svc/help


The sample output in Json format:
Enjoy........!!
Read More »

Monday, September 9, 2013

Admob Ads SDK Integration in Android.

     This tutorial explains you that how to add Google mobile ads to your application. AdMob provides you text, image banners and full screen ads. The following steps are required to get ads..
1. First, you should have a Google account. If have already, then  login to AdMob site.
2. Add new app in AdMob site and get the Publisher ID.
3. Add AdMob SDK to your Android Apllication.
4. Some code required.

How to get your Publisher ID from AdMob Site?

First, you should have a Google account to add new app in AdMob site.
After logging, click on Sites & Apps and then select Add Site/App. Refer below pic.

Then select your platform and fill the fields to complete the registration.

                                                                                                       
                                               
Then Note down your Publisher ID from Manage settings.

Copy your Publisher ID and paste it in your code.


Add AdMob SDK to your Application.

First, check your AdMob SDK library installation in Android SDK Manager. If not installed then install it.


Open application properties. In JAVA Path, click Add External JAR. Get your AdMob JAR file from your Android SDK like D:\android-sdks\extras\google\admob_ads_sdk


After adding JAR file. Select Order and export and check the GoogleAdsAdmobSDK JAR. Click OK to finish.

Now, AdMob SDK added to your application.

Code:

 Android Manifest file:

Add Internet and Access Network permissions in manifest file.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Declare com.google.ads.AdActivity.

<activity 

android:name="com.google.ads.AdActivity"
                 android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" >
        
</activity>

Banner Ads:

Banner Ads used to display in small portion of screen. It available in different sizes for  different devices. See table for available sizes.

Create your Banner in XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <com.google.ads.AdView
     android:id="@+id/adView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentBottom="true"
     ads:adSize="SMART_BANNER"
     ads:adUnitId="MY_Publisher_ID"
     ads:loadAdOnCreate="true"
     ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" >
  </com.google.ads.AdView>
    
</RelativeLayout>

Either you can do it in Activity also.

MainAcitivity code:

public class MainActivity extends Activity {

private AdView adView;
String MY_AD_UNIT_ID = "a152xxxxx3bcb3";

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

adView = new AdView(this, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
 adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
           
}
}

The banner output looks like below screen.

 Interstitials Ads:

Interstitials ads will displays in full screen. But banners will takes a small portion of screen. Interstials ads are richer and heavy weight. It mostly used in loading pages.

Code:

public class InterstitialAdsActivity extends Activity implements AdListener{


String MY_AD_UNIT_ID = "a152xxxxxxbcb3";
private InterstitialAd interstitial;

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

// Create the interstitial
   interstitial = new InterstitialAd(this, MY_AD_UNIT_ID);

   // Create ad request
   AdRequest adRequest = new AdRequest();

   // Begin loading your interstitial
   interstitial.loadAd(adRequest);

   // Set Ad Listener to use the callbacks below
   interstitial.setAdListener(this);
  }

/** Called when an ad is received. */
   @Override
public void onReceiveAd(Ad ad) {
   Log.d("OK", "Received ad");
   if (ad == interstitial) {
     interstitial.show();
   }
 }

 /** Called when an ad is clicked and about to return to the application. */
@Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "onDismissScreen", Toast.LENGTH_SHORT).show();
}

/** Called when an ad was not received. */
@Override
public void onFailedToReceiveAd(Ad ad, ErrorCode arg1) {

   // Change the button text and disable the button.
   if (ad == interstitial) {
    
      Toast.makeText(this, "Failed to Receive Ad", Toast.LENGTH_SHORT).show();
   }
}

/**
   * Called when an ad is clicked and going to start a new Activity that will
   * leave the application (e.g. breaking out to the Browser or Maps
   * application).

   */
@Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
 if (ad == interstitial) {
     
       Toast.makeText(this, "Application ended", Toast.LENGTH_SHORT).show();
    }
}

/**
   * Called when an Activity is created in front of the app (e.g. an
   * interstitial is shown, or an ad is clicked and launches a new Activity).

   */
@Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
 if (ad == interstitial) {
     
                Toast.makeText(this, "Present Screen", Toast.LENGTH_SHORT).show();
    }
}
}  

The output looks likes below screen...

Note: Download samples from developers.google.

Frequent errors:

1.If you get Runtime Exception error, then check your JAR file version  or  make sure that your manifest file contains all the required details are correct.
2. Uncaught ReferenceError: AFMA_getSdkConstants is not defined : Ice Cream Sandwich won't allow network operations in Main thread. Load it in separate thread.

                adView = new AdView(this, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
adView = (AdView)this.findViewById(R.id.adView);

(new Thread() {
                public void run() {
            Looper.prepare();
   
  adView.loadAd(new AdRequest());
               }
               }).start();

Otherwise, check your network or internet connection once.

Enjoy with your ads............
Read More »

Sunday, September 8, 2013

Barcode Scanning in Android.

Let's see about the Barcode Scanning in android. There are so many SDK's present today for Scanning barcode like Zxing, Red-scanner and Zbar. Both Zxing and Zbar are open sources. We can integrate it easily. Zbar is more fast and simple than Zxing. I inspired with the Zbar scanner.

Here, we have a wonderful tutorial about the Zbar SDK  integration in Android. Follow the link.
https://github.com/DushyanthMaguluru/ZBarScanner

And for Zxing, https://code.google.com/p/zxing/.





Read More »