Monday, February 18, 2013

jTwitter Authorization in Android with AsyncTask

In this post we ll see how to authorize an android app using jTwitter library for Twitter. We are going to use AsyncTask to achieve this because from Honeycomb you are not allowed to do network operations in the main thread. So we ll create an asynctask which will run in the background to do this. jTwitter is a library which is simple and easy to use. I assume that you know basics of android application development.
Lets get started.

Main_Activity.xml
The layout is pretty simple we just have a button which ll initiate the authorization process.


<RelativeLayout 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" >


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView1"
        android:layout_marginTop="89dp"
        android:text="Authorize" />


</RelativeLayout>


AndroidManifest.xml

In the manifest we just add some permissions required and an intent filter for callback.

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

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="myapp" android:host="twitt"/>
            </intent-filter>


MainActivity.java

In the java class we just create an onClickListener for our button in which we ask our AsyncTask to start the execution. We also create our AsyncTask which has three methods. They are self explanatory. One important thing that you got to remember is never do any UI related operation in the doInBackground() function. If you need to do some UI operation do it in preExecute() or postExecute(). Doing UI operations in  doInBackground() will throw exceptions.
And about the consumerKey and consumerSecret, you will get them when you register your application with twitter in dev.twitter.com.

import oauth.signpost.OAuth;
import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SampleActivity extends Activity {

Twitter twitter = null;
private Button postBtn = null;

private OAuthSignpostClient client = null;
private String CALLBACK_URI = "myapp://twitt";

private String authUrl = null;
String[] accessTokenandSecret=null;
String consumerKey="place consumer key";
String consumerSecret="place consumer secret";
String verifier;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postBtn=(Button)findViewById(R.id.button1);
postBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
new MyTask().execute();
}
});

}
private class GetToken extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "pre execute get token", Toast.LENGTH_LONG).show();
}

@Override
protected Void doInBackground(Void... arg0) {
try{
client.setAuthorizationCode(verifier);
accessTokenandSecret=client.getAccessToken();
client=new OAuthSignpostClient(consumerKey, consumerSecret, accessTokenandSecret[0], accessTokenandSecret[1]);
}
catch(Exception e)
{
Log.d("Exception token", ""+e.getMessage());
}
return null;
}

@Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "post execute get token ", Toast.LENGTH_LONG).show();
}
}

private class MyTask extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "pre execute", Toast.LENGTH_LONG).show();
}

@Override
protected Void doInBackground(Void... arg0) {
client = new OAuthSignpostClient(consumerKey ,consumerSecret, CALLBACK_URI);

authUrl = client.authorizeUrl().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
return null;
}

@Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "post execute", Toast.LENGTH_LONG).show();
}
}
protected void onNewIntent(Intent intent) {

super.onNewIntent(intent);
Uri uri = intent.getData();
//Check if you got NewIntent event due to Twitter Call back only
if (uri != null && uri.toString().startsWith(CALLBACK_URI))
{
try
{
verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Toast.makeText(getApplicationContext(), "inside verfier", Toast.LENGTH_LONG).show();
new GetToken().execute();
}
catch(Exception e){
Log.d("exception", " "+e.getMessage());
}
}}
}




Sunday, January 20, 2013

Function to convert 'mm/dd/yyyy' to 'dd-mon-yy' in c#


string da=datePicker1.SelectedDate.ToString().Split(' ')[0];
                    //MessageBox.Show(da);
                    string dat = da.Split('/')[1];
                    if (dat.Length == 1)
                    {
                        dat = "0" + dat;
                    }

                     string y = da.Split('/')[2];
                    string mont = null;
                    int mon = int.Parse(da.Split('/')[0]);
                    switch (mon)
                    {
                        case 1:
                            mont = "Jan";
                            break;
                        case 2:
                            mont = "Feb";
                            break;
                        case 3:
                            mont = "Mar";
                            break;
                        case 4:
                            mont = "Apr";
                            break;
                        case 5:
                            mont = "May";
                            break;
                        case 6:
                            mont = "Jun";
                            break;
                        case 7:
                            mont = "Jul";
                            break;
                        case 8:
                            mont = "Aug";
                            break;
                        case 9:
                            mont = "Sep";
                            break;
                        case 10:
                            mont = "Oct";
                            break;
                        case 11:
                            mont = "Nov";
                            break;
                        case 12:
                            mont = "Dec";
                            break;
                    }
                    char[] y1 = y.ToCharArray();
                    string y2 = y1[2].ToString() + y1[3].ToString();
                    string daSearch = dat + "-" + mont + "-" + y2;

Sunday, July 1, 2012

Passing Data From One Form to another in C#, THE EASIER WAY.

This is how you pass data from one form to another in c#. There are lot of methods to do this and this one is the easiest of the lot.
USING CONSTRUCTOR

In Form1 in the function where you move to the other form pass the value you want to send to the other form while instantiating the Form Object.


  private void button1_Click(object sender, System.EventArgs e)
  {
    Form2 frm=new Form2(textBox1.Text);
    frm.Show();
  }

In Form2 add a paramaterized constructor to receive that data that was sent from Form1.

  
  public Form2(string strTextBox)
   {
   InitializeComponent(); 
   label1.Text=strTextBox;
   }

And that is it you have passed data from one form to another.


Tuesday, June 26, 2012

Database operations select, insert, update and delete in c# with SQL


There are basically four functions each one for a database operation. Parameters are used in insert, update and select. 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace AddressBook
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();


        }


        //INSERT
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Thangamani\Documents\visual studio 2010\Projects\AddressBook\AddressBook\Database1.mdf;Integrated Security=True;User Instance=True";
                string na = textBox1.Text;
                int ag = int.Parse(textBox2.Text);
                string ci = textBox3.Text;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {


                    using (SqlCommand insertCommand = connection.CreateCommand())
                    {
                        insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (@na,@ag,@ci)";
                        insertCommand.Parameters.AddWithValue("@na", na);
                        insertCommand.Parameters.AddWithValue("@ag", ag);
                        insertCommand.Parameters.AddWithValue("@ci", ci);




                        insertCommand.Connection.Open();
                        insertCommand.ExecuteNonQuery();
                        insertCommand.Connection.Close();
                        MessageBox.Show("Data Successfully Inserted");


                    }
                    
                    //connection.Close();
                }


            }
            finally { }


        }


        //SELECT
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string s = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Thangamani\Documents\visual studio 2010\Projects\AddressBook\AddressBook\Database1.mdf;Integrated Security=True;User Instance=True";
                SqlConnection a = new SqlConnection(s);
                a.Open();
                SqlCommand comm = new SqlCommand("SELECT * FROM address");
                comm.Connection = a;
                SqlDataReader re = comm.ExecuteReader();
                while (re.Read())
                {
                    textBox1.Text = re["name"].ToString();
                    textBox2.Text = re["age"].ToString();
                    textBox3.Text = re["city"].ToString();


                    MessageBox.Show("Data Selected");
                }
            }
            finally
            {
            }
        }


        //DELETE
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Thangamani\Documents\visual studio 2010\Projects\AddressBook\AddressBook\Database1.mdf;Integrated Security=True;User Instance=True";
                string na = textBox1.Text;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {


                    using (SqlCommand insertCommand = connection.CreateCommand())
                    {
                        insertCommand.CommandText = "DELETE FROM address WHERE name LIKE @na";
                        insertCommand.Parameters.AddWithValue("@na", na);






                        insertCommand.Connection.Open();
                        insertCommand.ExecuteNonQuery();
                        insertCommand.Connection.Close();
                        MessageBox.Show("Data successfully Deleted");


                    }




                }
            }
            finally { }
        }


        //UPDATE
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Thangamani\Documents\visual studio 2010\Projects\AddressBook\AddressBook\Database1.mdf;Integrated Security=True;User Instance=True";
                string na = textBox1.Text;
                int ag = int.Parse(textBox2.Text);
                string ci = textBox3.Text;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {


                    using (SqlCommand insertCommand = connection.CreateCommand())
                    {
                        insertCommand.CommandText = "UPDATE address SET age=@ag, city=@ci WHERE name LIKE @na";
                        insertCommand.Parameters.AddWithValue("@na", na);
                        insertCommand.Parameters.AddWithValue("@ag", ag);
                        insertCommand.Parameters.AddWithValue("@ci", ci);




                        insertCommand.Connection.Open();
                        insertCommand.ExecuteNonQuery();
                        insertCommand.Connection.Close();
                        MessageBox.Show("Data successfully Updated");


                    }




                }
            }
            finally { }
        }
    }
}