Twitter API With OAuth (Automatic Post your tweet system)

Hi There. It's been a long time since my Last post. You didn't forget about me, is that right?

Many of you've been asking me about my lastest project (ICTbookplus). My Twitter Feature
which will post tweet by your account on twitter.com saying that the user has bought a book
from my website (wicked marketing, right?). Try It! (sign in with twitter for full detail!).

Summary of what you need to do!

 

  1. Use your twitter account to  add new Application to the twitter pool.
  2. Download Twitter oAuth example from here
    (Credit http://apiwiki.twitter.com/http://www.voiceoftech.com/swhitley/?p=681)
  3. Coding!
Sounds easy! Let's begin
  1. On your twitter account home, follow these steps.

  2. Fill in your website information (Real internet Url on Callback URL)

  3. Now Remember your consumer key and Consumer secret
  4. Now, use  oAuth from example above to program here

  5. Include two file in your Project (oAuth.cs and oAuthTwitter.cs)
  6. Code your call back page like this

    1.         protected void Page_Load(object sender, EventArgs e)
    2.         {
    3.             string url = "";
    4.             string xml = "";
    5.             oAuthTwitter oAuth = new oAuthTwitter();
    6.  
    7.             if (Request["oauth_token"] == null)
    8.             {
    9.                 //Redirect the user to Twitter for authorization.
    10.                 //Using oauth_callback for local testing.
    11.                 Response.Redirect(oAuth.AuthorizationLinkGet() + "&oauth_callback=");
    12.             }
    13.             else
    14.             {
    15.                 //Get the access token and secret.
    16.                 oAuth.AccessTokenGet(Request["oauth_token"]);
    17.                 if (oAuth.TokenSecret.Length > 0)
    18.                 {
    19.                     //We now have the credentials, so make a call to the Twitter API.
    20.                     url = "http://twitter.com/account/verify_credentials.xml";
    21.                     xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
    22.                     //apiResponse.InnerHtml = Server.HtmlEncode(xml);
    23.                    
    24.                     XElement x = XElement.Parse(xml);
    25.  
    26.                     //POST Test
    27.                     url = "http://twitter.com/statuses/update.xml";
    28.                     xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("I've just bought TextBook From ICTBook+ at http://cmmadnat.theblogfor.net/user"));
    29.                     //apiResponse.InnerHtml = Server.HtmlEncode(xml);
    30.                  }
    31.               }
    32.         }

This page will simply encode your request with your Consumer Key and Consumer secret, send
it to twitter for user authentication. Then it retrieve token (in XElement x) which contains user
identity.

On the post test, our code uses token to post status to twitter website.

7. Configure web.config, insert your website Consumer key and secret key.

  <appSettings>
    <add key="consumerKey" value="fuBAODgxjpS16FNSskUw" />
    <add key="consumerSecret" value="4CECc7JaclVtmXTzRmdZXUZpiegdUXqRP42cRE"/>
  </appSettings>

8. upload your page to website specific in your twitter application. ! Yeah

Thank you !!!

Categories:   .NET ASP.NET C# | Tip(s)
Actions:   E-mail | del.icio.us | Permalink | Comments (2) | RSS


Dependency chain resolution using IoC container

When you have a dependency between two modules, that modules are not well-separated with each other which are not good when design a large application that needs to be modularized and independent. IoC (Inversion of Control or Dependency Injection whatever), as name suggested, comes to rescue us and resolve the problem by injecting an external dependencies to our modules and using the container (that is injected) to decouple the dependencies between modules, so now the dependencies are inverted to our container and that container will control and manage the rest.

Ok, it sounds confusing. Let's me show you some examples..

 

So our solution from IoC pattern suggestion'd be:

 

But if we'd like to input some parameter such as connectionString (not only connectionString, also other inputs as you wish!), above figure example cannot solve this problem without create dependency between modules, and if there are chains of those dependencies that could be very bad.

Our hero is IoC container (provider), it can resolve the dependency chain problem by automatically calling the MemberPayment constructor method and support its parameter. We have to just tell them some information about those Concrete class that we want to instantiate without concerning about the dependencies between each module, that's amazing.

One of popular IoC containers is Castle Windsor, http://www.castleproject.org.

The code below demonstrates the use of Castle Windsor library to resolve the problem of Shop and MemberPayment in our previous examples but let's me explain more about my requirements. Since we're building a small shopping service that users come and pay money, we have to know who are our customers so that we can compute special prices for them. In another word, we need to connect with the MembershipProvider database that are far away (assumed).

//all these classes belong to theBlogFor namespace. interface IPaymentService { double CalculateTotalPrice(); } public class NonMemberPayment: IPaymentService { #region IPaymentService Members public double CalculateTotalPrice() { throw new NotImplementedException(); } #endregion } public class MemberPayment: IPaymentService { public string ConnectionString; public MemberPayment(string connectionString){ ConnectionString = connectionString; } #region IPaymentService Members public double CalculateTotalPrice() { throw new NotImplementedException(); } #endregion }

 

public class Shop { bool isMember = true; WindsorContainer container; public void BuyItems(/*...items...*/){ container = new WindsorContainer(new XmlInterpreter(new Castle.Core.Resource.ConfigResource("castle"))); if (isMember) { MemberPayment serviceForMember = container.Resolve<IPaymentService>("MemberPayment") as MemberPayment; System.Windows.Forms.MessageBox.Show(serviceForMember.ConnectionString); } else { NonMemberPayment serviceForNonMember = container.Resolve<IPaymentService>("NonMemberPayment") as NonMemberPayment; } } }

 The point is; container.Resolve<IPaymentService>("MemberPayment"), "MemberPayment" is an ID that you specified in XML config file (see it later). You may have a question how WindsorContainer knows my initial value of the connectionString for MemberPayment. That's because we describe the default parameter of connectionString in config file (that's all). In conclusion, when we call Resolve method, container'll look up the XML (since we tell them to do so by XmlInterpreter(...) ), then it'll know from that config file which components it has to instantiate and give those the parameters they require. After this process, we'll get IPaymentService obj, as expected, and finally the MessageBox'll be shown out with the connectionString message (sound boring..).

Not only you can specify the default connectionString in config file, you can also input the anonymous-type arguments as parameters too : container.Resolve<IPaymentService>("MemberPayment", new { connectionString = "ok! that 's enough, stop this lesson." }). 

container = new WindsorContainer(new XmlInterpreter(new Castle.Core.Resource.ConfigResource("castle"))); from this line, we tell WindsorContainer that there is some xml code that it has to concern when building a container as you can see :

<configuration> <configSections> <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/> </configSections> <castle> <components> <component id="NonMemberPayment" service="theBlogFor.IPaymentService,theBlogFor" type="theBlogFor.NonMemberPayment,theBlogFor"/> <component id="MemberPayment" service="theBlogFor.IPaymentService,theBlogFor" type="theBlogFor.MemberPayment,theBlogFor"> <parameters> <connectionString>Data Source=MYCOMNAME\SQLEXPRESS;Initial Catalog=theBlogForMembershipProvider;Integrated Security=True;Pooling=False</connectionString> </parameters> </component> </components> </castle> </configuration>

We support parameters for MemberPayment since it needs to identify database that keeps members, but for NonMemberPayment, it doesn't care about this at all. You can specify the parameters like above, or specify them inside the property for future use :

<properties> <connection>YourConnectionString</connection> </properties> <component id="xxx" service="yyy" type="zzz"> <parameters> <connectionString>#{connection}</connectionString> </parameters> </component>

Concept of IoC container is very pervasively used in real world app including in MVC that can be combined with ControllerFactory to create sophisticated Controller obj. Examples of MVC can be easily obtained on the Internet. Hope you get something from this article : - )


kick it on DotNetKicks.com     Shout it

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (3) | RSS


 

Tag Cloud