Micro Performance optimisation using If-Else

This post is actually a question I asked on Stackoverflow,

The question is Which performs better if or if-else ?, this might seem to be a silly question for a few because of 2 reasons.

  • If block will have relatively less lines of code, if both the blocks are having the same code, it is apparently a matter of commonsense.
  • And if they are not having the same code then we should not compare them in the first place

The If Block

    public long WithOnlyIf(int myFlag)
   {
          Stopwatch myTimer = new Stopwatch();
          string someString = "";
          myTimer.Start();
          for (int i = 0; i < 1000000; i++)
          {
              string height = "80%";
              string width = "80%";
              if (myFlag == 1)
              {
                  height = "60%";
                  width = "60%";
              }
              someString = "Height: " + height + Environment.NewLine + "Width: " + width;
          }
          myTimer.Stop();
          File.WriteAllText("testif.txt", someString);
          return myTimer.ElapsedMilliseconds;
      } 

The If-Else Block

    public long WithIfAndElse(int myFlag)
    {
          Stopwatch myTimer = new Stopwatch();
          string someString = "";
          myTimer.Start();
          for (int i = 0; i < 1000000; i++)
          {
              string height;
              string width;
              if (myFlag == 1)
              {
                  height = "60%";
                  width = "60%";
              }
              else
              {
                  height = "80%";
                  width = "80%";
              }
              someString = "Height: " + height + Environment.NewLine + "Width: " + width;
          }
          myTimer.Stop();
          File.WriteAllText("testifelse.txt", someString);
          return myTimer.ElapsedMilliseconds;
      } 

So Which one actually performs better, well lets look into the  results

When Condition is true, the If Block took 1700 milliseconds to execute the 1000000 iterations, where as the if-else block took only 1688 milliseconds

When the conditions fails, the if scored 1677 Milliseconds which is still a bit late than the If-Else block’s 1664 Milliseconds

So the results  say that If-Else performs better than If and guess according to most of SO posters the If-Else block is more readable too


Sql Query to get domain Name from email column

The following T-SQL Query will retrieve anything that is after the @ symbol, the query can be very useful for retrieving the domain of an email address
SELECT SUBSTRING(T.Email,(CHARINDEX('@',T.Email)+1),LEN(T.Email) - (CHARINDEX('@',T.Email))) as DomainName FROM EmailTable T


A simple C#class to implement rijndael encryption

For all those paranoids out there who fear there data might be stolen :) here is a simple helper class to implemnet rijndael encryption in C#.net.

I found this code long back on the net, i added some coments and made it int a class, so if you find it usefull and know the original coder, just post a comment and let me know.

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace EasyCipher
{
    public class EC_Rijndael
    {

        #region Encryption Stuff goes here

        /// <summary>
        /// Encrypts a given string using Rijndael algorithm, salted
        /// </summary>
        /// <param name="plain_text">The string you want to encrypt</param>
        /// <param name="password">Password used for encryption</param>
        ///<returns></returns>
        public static string Encrypt(string clearText, string Password)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
            //Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return Convert.ToBase64String(encryptedData);
        }

        /// <summary>
        /// Encrypts a given string using Rijndael algorithm
        /// </summary>
        /// <param name="plain_text">The string you want to encrypt</param>
        /// <param name="password">Password used for encryption</param>
        /// <param name="salt">Salt value in bytes to stop dictionary attack, remember the same salt value must be used to decryption</param>
        ///<returns></returns>
        public static string Encrypt(string plain_text, string password, byte[] saltvalue)
        {
            byte[] plain_bytes = System.Text.Encoding.Unicode.GetBytes(plain_text);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
            byte[] encrypted_data = Encrypt(plain_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return Convert.ToBase64String(encrypted_data);
        }

        /// <summary>
        /// Encrypts a byte array, instead of string
        /// </summary>
        /// <param name="plain_bytes">byte array to be encrypted</param>
        /// <param name="password">password for encryption</param>
        /// <param name="saltvalue">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
        /// <returns>Encrypted byte array</returns>
        public static byte[] Encrypt(byte[] plain_bytes, string password, byte[] saltvalue)
        {
            PasswordDeriveBytes pwd = new PasswordDeriveBytes(password, saltvalue);
            byte[] encryptedData = Encrypt(plain_bytes, pwd.GetBytes(32), pwd.GetBytes(16));
            return encryptedData;
        }

        /// <summary>
        /// Encrypts a byte array, instead of string, salted
        /// </summary>
        /// <param name="plain_bytes">byte array to be encrypted</param>
        /// <param name="password">password for encryption</param>
        /// <returns>Encrypted byte array</returns>
        public static byte[] Encrypt(byte[] clearBytes, string Password)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return encryptedData;
        }

        #endregion

        #region Decryption Stuff Goes here

        /// <summary>
        /// Decyphers an encrypted string, salted
        /// </summary>
        /// <param name="cipher_text">Encrytped string to be deciphered</param>
        /// <param name="password">password used for encrypting string</param>
        /// <returns>Plain deciphered string</returns>
        public static string Decrypt(string cipherText, string Password)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            //Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        }

        /// <summary>
        /// Decyphers an encrypted string
        /// </summary>
        /// <param name="cipher_text">Encrytped string to be deciphered</param>
        /// <param name="password">password used for encrypting string</param>
        /// <param name="saltvalue">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
        /// <returns>Plain deciphered string</returns>
        public static string Decrypt(string cipher_text, string password, byte[] saltvalue)
        {
            byte[] cipher_bytes = Convert.FromBase64String(cipher_text);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
            byte[] decrypted_data = Decrypt(cipher_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return System.Text.Encoding.Unicode.GetString(decrypted_data);
        }

        /// <summary>
        /// Decyphers an encrypted byte array, salted
        /// </summary>
        /// <param name="cipher_bytes">Encrytped byte array to be deciphered</param>
        /// <param name="password">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
        /// <returns></returns>
        public static byte[] Decrypt(byte[] cipherBytes, string Password)
        {
            //Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return decryptedData;
        }

        /// <summary>
        /// Decyphers an encrypted byte array
        /// </summary>
        /// <param name="cipher_bytes">Encrytped byte array to be deciphered</param>
        /// <param name="password">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
        /// <param name="saltvalue">Plain deciphered byte array</param>
        /// <returns></returns>
        public static byte[] Decrypt(byte[] cipher_bytes, string password, byte[] saltvalue)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
            byte[] decrypted_data = Decrypt(cipher_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return decrypted_data;
        }

        #endregion

        #region Private Encryption Methods

        private static byte[] Encrypt(byte[] plain_bytes, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(plain_bytes, 0, plain_bytes.Length);
            cs.Close();
            byte[] encrypted_data = ms.ToArray();
            return encrypted_data;
        }

        private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherData, 0, cipherData.Length);
            cs.Close();
            byte[] decrypted_data = ms.ToArray();
            return decrypted_data;
        }

        #endregion

    }

}


2010 in review

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads This blog is doing awesome!.

Crunchy numbers

Featured image

A helper monkey made this abstract painting, inspired by your stats.

A Boeing 747-400 passenger jet can hold 416 passengers. This blog was viewed about 3,300 times in 2010. That’s about 8 full 747s.

 

In 2010, there were 10 new posts, growing the total archive of this blog to 16 posts. There was 1 picture uploaded, taking a total of 33kb.

The busiest day of the year was October 27th with 60 views. The most popular post that day was Implementing oauth twitter search in C# and JSON.

Where did they come from?

The top referring sites in 2010 were in.answers.yahoo.com, google.co.in, google.com, ead.ipleiria.pt, and mail.live.com.

Some visitors came searching, mostly for oauth twitter c#, twitter oauth c#, check domain availability in c sharp, coderbuddy, and c# twitter search.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Implementing oauth twitter search in C# and JSON August 2010
8 comments

2

C# code to publish, delete, retrieve tweets using oauth August 2010
1 comment

3

Changing array length at runtime in C#.net October 2009
3 comments

4

A simple C# class to get whois information October 2010
4 comments

5

C# code to extract Email October 2009
2 comments


Auto increment using identity in SQL Server

Auto increment feature can be implemented very easily in an SQL server table using the IDENTITY property.

The following query can be used for creation of one such table that can implement auto increment feature on one of its columns

CREATE TABLE EMPLOYEE(EID INT IDENTITY(1,1), ENAME VARCHAR(30), E_DOB DATETIME)

when the above query is executed, a table with the name EMPLOYEE is created with a column EID whose values are auto incremented.

Syntax
The syntax of the identity property is very simple

DataType IDENTITY [ (seed ,increment) ]

DataType : Identity only supports INT, BIGINT, SMALLINT, TINYINT, DECIMAL data types

seed: seed is the value that is assigned for the first row that is loaded into the table

increment: Is the incremental value that is added to the identity value of the previous row that was loaded.

seed and increment are optional, but not individually, that means we have to either specify both the values or none of them.

If the values are not provided for seed and increment than the default values of (1, 1) are taken

For more information on IDENTITY property visit  http://msdn.microsoft.com/en-us/library/aa933196(SQL.80).aspx


Domain name search in C#

I always wondered how the big domain registration companies searched for domain availability, but thanks to the advice of Anthony of  http://bruteforcenaming.com who kindly responded to my childish question of how do you do it ?

Based on his advice of using the whois lookup to search for domain availability, i wrote a C# class to lookup whois information and a domain search class, which i am sharing with you now

Note: this class uses the whois lookup class, i posted earler on my blog at http://coderbuddy.wordpress.com/2010/10/12/a-simple-c-class-to-get-whois-information/, so for all of you who want to use this class, first go check my post on whois class or you can download the complete source code by clicking the download button at the bottom of this post.

 public class DomainSearch
    {
        /// <summary>
        /// Check whether a given domain name is available or not
        /// </summary>
        /// <param name="domainname">daomain name to be verified</param>
        /// <param name="whois_server_address">use null value (that is "") or "whois.internic.net" if you dont know any whois servers</param>
        /// <returns></returns>
        public static bool isAvailable(string domainname,string whois_server_address)
        {
            List<string> ws = Whois.lookup(domainname, Whois.RecordType.domain, whois_server_address);
            return ws[7].Contains("No match for domain \"" + domainname.ToUpper() + "\".");
        }    }

Click the download button bellow to download the complete source code (Visual studio 2005, C#.net, Windows Class Library Project) including the whois lookup class.

Download button


A simple C# class to get whois information

I have searched on the web and found C# classes to obtain whois information, but none of those classes has addressed my issue of obtaining only the domain information, for example if i search for whois information of microsoft.com using the code available on the net you will also get all the name servers that have microsoft in the name.

None of the code i saw addressed the issue of excluding the name servers from the list and only obtaining the whois information for the domain name. So after a bit of research and coding this is what i got, i am sharing it with you. I will be very happy if it is of some use to anybody

using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

namespace WebTools
{
    /// <summary>
    /// A class to lookup whois information.
    /// </summary>
    public class Whois
    {
        public enum RecordType { domain, nameserver, registrar };

        /// <summary>
        /// retrieves whois information
        /// </summary>
        /// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <returns>The string containg the whois information</returns>
        public static string lookup(string domainname, RecordType recordType)
        {
            List<string> res = lookup(domainname, recordType, "whois.internic.net");
            string result = "";
            foreach (string st in res)
            {
                result += st + "\n";
            }
            return result;
        }        /// <summary>
        /// retrieves whois information
        /// </summary>
        /// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <param name="returnlist">use "whois.internic.net" if you dont know whoisservers</param>
        /// <returns>The string list containg the whois information</returns>
        public static List<string> lookup(string domainname, RecordType recordType, string whois_server_address)
        {
            if (whois_server_address == "")
                whois_server_address = "whois.internic.net";
            TcpClient tcp = new TcpClient();
            tcp.Connect(whois_server_address, 43);
            string strDomain = recordType.ToString() + " " + domainname + "\r\n";
            byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
            Stream s = tcp.GetStream();
            s.Write(bytDomain, 0, strDomain.Length);
            StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
            string strLine = "";
            List<string> result = new List<string>();
            while (null != (strLine = sr.ReadLine()))
            {
                result.Add(strLine);
            }
            tcp.Close();
            return result;
        }
    }
}

You can use obtain the whois information by simple using the following code

string info = Whois.lookup("google.com", Whois.RecordType.domain);

or you can alternatively use

List<string> info = Whois.lookup("google.com", Whois.RecordType.domain, "whois.internic.net");

This post is first published on coderbuddy.wordpress.com.

I will try and post a entry about whois queries, for those who are interested go to coderbuddy Home


Update

Click the download button bellow to download the complete source code (Visual studio 2005, C#.net, Windows Class Library Project) including the C# class to search for domain name search using whois information.

Download button
Related Articles


C# code to publish, delete, retrieve tweets using oauth

The following C#.net class can be used to update statuses, delete, retweet statuses, obtain information regarding a particular status and any body who retweeted a particular status using status id.

This class implements all the methods that are under the “Tweets Resources” section in Twitter API documentation

using System;
using System.Text;
using System.Collections.Generic;

namespace TwitterAPI
{
    public class Tweets
    {
        #region Class-Level-Declarations

        private oAuthTwitter OAuth;
        /// <summary>
        /// Create, Update, retrieve, delete tweets(status messages) using this class
        /// </summary>
        /// <param name="_oauth">An authorized and authenticated oAuth token</param>
        public Tweets(oAuthTwitter _oauth)
        {
            this.OAuth = _oauth;
        }
        public enum ResponseFormat { JSON, XML };

        #endregion

        #region Show:ID

        /// <summary>
        /// Returns a single status, specified by the id parameter below. The status's author will be returned inline.
        /// This does not require authentication as long as the status is not protected
        /// This is a rate limited call
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_By_ID(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/show/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the authenticating user's status. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates.
        /// Authentication is required and this call is not rate limited
        /// </summary>
        /// <param name="tweet_message">The text of your status update, up to 140 characters.</param>
        /// <param name="reponse_format">The format in which you want twitter to respond</param>
        /// <param name="optionalparameters">Any optional paramters you want to pass</param>
        /// <returns>Response string from twitter in user selected format </returns>
        public string UpdateStatus(ResponseFormat reponse_format, string tweet_message, string optionalparameters)
        {
            if (string.IsNullOrEmpty(tweet_message))
                throw new ArgumentNullException(tweet_message, "The status message cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/update." + reponse_format.ToString(), "status=" + tweet_message + optionalparameters);
        }

         #endregion

        #region Destroy:Id

        /// <summary>
        /// Destroys the status specified by the required ID parameter.In other words deletes the specified tweet
        /// Requires authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Destroy_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/destroy/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Retweet:Id

        /// <summary>
        /// Retweets a tweet. Returns the original tweet with retweet details embedded.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Retweet_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/retweet/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweets:Id

        /// <summary>
        ///Returns up to 100 of the first retweets of a given tweet.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweets_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/retweets/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user objects of up to 100 members who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user ids of up to 100 users who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by/ids." + response_format.ToString(), optionalparameters);
        }        #endregion
    }
}

This class file uses OAuth implementation by shannon whitley (for more information see my previous post Implementing oauth twitter search in C# and JSON).

You can download the complete source code along with this class from https://sites.google.com/site/coderbuddy/downloads/TwitterAPI.zip?attredirects=0&d=1


Implementing oauth twitter search in C# and JSON

To implement twitter search in C# that uses oauth for authentication, first we need a C# oauth implementation, and a JSON parser for extracting results. For oauth implementation I’m using Twitter oAuth with .NET by Shannon whitley and for parsing the results JSON parser by Procurious and i have to say that this post is just a bit refined implementation of Parsing Twitter JSON data in C# by Jamie’s Digital Blog.

To get started with twitter needs you to authenticate your application before you could use twitter API’s search feature, to authenticate an application initialize a oAuthTwitter object so that it is accessible through out the class like

oAuthTwitter oauth = new oAuthTwitter();
//Replace the vlues with the one's provided by twitter
oauth.ConsumerKey = "Your-twitter-oauth-consumerkey";
oauth.ConsumerSecret = "Your-twitter-oauth-consumersecret";
//Launches your default browser for requesting //authentication
System.Diagnostics.Process.Start(oauth.AuthorizationLinkGet());
//Copy the pin provided after you authenticating and save to a string
//I am assuming you store it in a string twitterpin
//Now the real authentication takes place
//you will exchange the authtoken and pin for Access token
oauth.AccessTokenGet(oauth.OAuthToken, twitterpin);
//remember twitterpin is the object in which we stored the //pin value

Now since we have obtained the authentication we can use this oAuth to search twitter


//Replace the term search_keyword with a term you want to search
//rpp=100 in the url means results per page is 100, and lang=en means
//Language is english
string result = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://search.twitter.com/search.json", "q=" + search_keyword + "&rpp=100&lang=en");

Now we have the 100 search results stored in a string result in JSON format, we will use JSON parser for extracting the values of each tweet


//The following code is a straight copy from jamiedigi.com
HashTable jsonHash = (Hashtable)JSON.JsonDecode(jsonCode);
ArrayList jsonResults = (ArrayList)jsonHash["results"];
foreach (object objResult in jsonResults)
{
Hashtable jsonResult = (Hashtable)objResult;
System.Diagnostics.Debug.WriteLine("User ID: "
+ jsonResult["from_user_id"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet text: "
+ jsonResult["text"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet date: "
+ jsonResult["created_at"].ToString());
System.Diagnostics.Debug.WriteLine("User name: "
+ jsonResult["from_user"].ToString());
System.Diagnostics.Debug.WriteLine("Language: "
+ jsonResult["iso_language_code"].ToString())
}

You can download the complete source code along with oauth and JSON parser implementations from https://sites.google.com/site/coderbuddy/myReserach.zip?attredirects=0&d=1

You may need to make some modifications to the code like providing the consumer key and consumer secret before working with the code

Subscribe to feed


Microsoft releases WebMatrix Beta

Microsoft has released WebMatrix Beta, it is a collection of tools that will be help you develop a web application with minimal effort.The tools included in this package are IIS Developer Express (a development Web server), ASP.NET, and SQL Server Compact (an embedded database). A web server, a Web Framework, a database that’s almost everything a developer may need to create a simple dynamic web pages.

Microsoft also introduces a new way to embedding C#/VB code directly into your HTML with a new Viewing Engine called Razor or APS.net Razor

An example code using razor will look something like this

<h1>Razor Example Code</h1><br/>
Hello @name, the year is @DateTime.Now.Year

The equalent ASPX code may look something like this

<h1>ASPX Page Example</h1><br />
Hello <%=name %>, the year is <%= DateTime.Now.Year %>

For more on this topic visit WebMatrix, Introduction to Razor and to download webmatrix go to http://www.microsoft.com/web/webmatrix/

Microsoft has also selected a few web hosts that can host web pages using this new technology, to see the list go to http://www.microsoft.com/web/webmatrix/learn/ and scroll down to the section called “Recommended web hosts”.Since this is still in beta you may experience some bugs, so use it with caution.


Follow

Get every new post delivered to your Inbox.