Wednesday, 5 August 2015

Asp.Net Post for Get Home screen tweets from twitter using API and store into SQL Server Database

Get Home screen tweets from twitter using API and store into SQL Server Database




My first Asp.Net article  for the twitter tweets related to display latest less than 200 tweet for home screen in ASP.NET page and store in the database table.

Introduction

i search a lots of things related twitter tweets,i found lots of solution on internet using this information and i devlop a one Asp.net application for Display latest tweets on my page and store the tweets in my sql server database and use Visual studio 2010 withe .Net Framework 4.0

Background

First of sign in to twitter using this link https://apps.twitter.com/ and follow the step and Get the
"ConsumerKey"
"ConsumerSecret"
"TokenKey"
"TokenSecretkey"
After get all the twitter key the create a database in MS SQL Server and create a table

code

first Design the Default.aspx page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id=Head1 runat="server">
    <title></title>
 
    <style type="text/css">
        #myTitle
        {
            color: Black ;
            font-weight :bolder ;
            font-style :normal ;
        }
        
        #myDiv
        {
            background-color: #FFFFFF;
        }
        
    </style>
 
</head>
<body>
    <form id="form1" runat="server">
    <div id="myDiv" runat="server">
     
    </div>
    </form>
</body>
</html>

now next set the key and connection string in Web.config file

<connectionStrings>
    <!--put your connection string here-->
    <add name="conString" connectionString="Data Source=ServerName/IP;Initial Catalog=dbname;Integrated Security=false;User Id=username;Password=password;Persist Security Info=true; Connect Timeout=1000;Max pool size=25"/>
  </connectionStrings>
  <appSettings>
    <add key="ConsumerKey" value="hMYnAWt4fkZuirxDKvsH2yXe"/> <!--"insert here...";-->
    <add key="ConsumerSecret" value="763lji0wK3hrjSgAdC4Jz2XyfIs4nOK4cOo1BHNsBnTvr2vGU"/><!--"insert here...";-->
    <add key="TokenKey" value="3171598760-1mfuPn7YpzXRqDnj3Jnm6dg7YkYdN9J8qw7rZ"/><!--"insert here...";-->
    <add key="TokenSecret" value="DPjzDM8zy4DUDwtvYSRI4QeCWY9b6AEvP74fySyRc"/><!--"insert here...";-->

  <add key="Twitterizer2.EnableStatisticsCollection" value="false"/>
  </appSettings>


Now write this code in Default.aspx.cs code file

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
    private SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
    //public string query = "mca_krunal";
    public string query = "";
    //    public string url = "https://api.twitter.com/1.1/users/search.json" ;
    //public string url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; //Display my tweet
    public string url = "https://api.twitter.com/1.1/statuses/home_timeline.json"; //display home tweet with my tweet
  
    public Int16 cnt = 200;
    protected void Page_Load(object sender, EventArgs e)
    {
        findUserTwitter(url, query);
    }
      
    public void findUserTwitter(string resource_url, string q)
    {
        // oauth application keys
        var oauth_token = ConfigurationManager.AppSettings["TokenKey"]; //"insert here...";
        var oauth_token_secret = ConfigurationManager.AppSettings["TokenSecret"]; //"insert here...";
        var oauth_consumer_key = ConfigurationManager.AppSettings["ConsumerKey"];// = "insert here...";
        var oauth_consumer_secret = ConfigurationManager.AppSettings["ConsumerSecret"];// = "insert here...";
        // oauth implementation details
        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";
        // unique request details
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        //var oauth_nonce = "8314576e2324d3c9a55bf3f021fd2965";
        var timeSpan = DateTime.UtcNow
            - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
        //var oauth_timestamp = "1429954519";
        // create oauth signature
        var baseFormat = "count={7}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
        "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
        //var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
        //"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
               var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version,
                                    Uri.EscapeDataString(query),
                                    cnt.ToString()
                                    );
       baseString = string.Concat("GET&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(baseString));
        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
        "&", Uri.EscapeDataString(oauth_token_secret));
        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
        oauth_signature = Convert.ToBase64String(
        hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }
       // create the request header
        var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
        "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
        "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
        "oauth_version=\"{6}\"";
        var authHeader = string.Format(headerFormat,
        Uri.EscapeDataString(oauth_nonce),
        Uri.EscapeDataString(oauth_signature_method),
        Uri.EscapeDataString(oauth_timestamp),
        Uri.EscapeDataString(oauth_consumer_key),
        Uri.EscapeDataString(oauth_token),
        Uri.EscapeDataString(oauth_signature),
        Uri.EscapeDataString(oauth_version)
        );
        ServicePointManager.Expect100Continue = false;
        // make the request
        var postBody = "screen_name=" + Uri.EscapeDataString(query) + "&count=" + cnt.ToString();//
        //var postBody = "screen_name=" + Uri.EscapeDataString(query) ;//
        url += "?" + postBody;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        var response = (HttpWebResponse)request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());
        var objText = reader.ReadToEnd();
      
        myDiv.InnerHtml = objText;/**/
        string html = "";
        try
        {
            JArray jsonDat = JArray.Parse(objText);
            html = html + "<b id='myTitle'>Total Tweet Cout :</b>" + jsonDat.Count().ToString() + "<br/><br/><hr>";
            for (int x = 0; x < jsonDat.Count(); x++)
            {
                html = html + "<b id='myTitle'>ID :</b><br/>" + jsonDat[x]["id"].ToString() + "<br/>";
                html = html + "<b id='myTitle'>Tweet :</b><br/>" + jsonDat[x]["text"].ToString() + "<br/>";
                html = html + "<b id='myTitle'>Created On :</b><br/>" + jsonDat[x]["created_at"].ToString() + "<br/><br/><hr>";
                InsertTweetIntoDB(jsonDat[x]["id"].ToString(), jsonDat[x]["text"].ToString(), jsonDat[x]["created_at"].ToString());
             }
            myDiv.InnerHtml = html;
        }
        catch (Exception twit_error)
        {
            myDiv.InnerHtml = html + twit_error.ToString();
        }
    }

    //Firest create table into in your db name"Table_Tweet"
    public void InsertTweetIntoDB(string ID, string TweetTXT, String Created_AT)
    {
        con.Open();
        //Query to insert images path and name into database
        SqlCommand cmd = new SqlCommand("Insert into Table_Tweet(ID, TweetTXT, Created_AT) values(@ID, @TweetTXT, @Created_AT)", con);
        //Passing parameters to query
        cmd.Parameters.AddWithValue("@ID", ID);
        cmd.Parameters.AddWithValue("@TweetTXT", TweetTXT);
        cmd.Parameters.AddWithValue("@Created_AT", Created_AT);
      
        cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        //Close dbconnection
        con.Close();
    }
    public void UpdateTweetIntoDB(string ID, string TweetTXT, String Created_AT)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("update Table_Tweet set ID=" + ID + ", TweetTXT='" + TweetTXT + "', Created_AT='" + Created_AT , con);
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

Interest

i have learn lots of new things from this demo and thank all the guys who help me for this assignment,i hope this is helpful for needy people...
Thanks
My Popular post click on Link to view


2 comments: