Heart of Angel

Archive for the ‘en’ tag

Tutorial: Authenticating with Google OAuth

without comments

Recently I’ve been trying to get Google OAuth to work with my small tool but try as I might, I found no tutorial on the Internet on how to authenticating with Google OAuth using .NET Desktop application. With a few efforts I’ve been able to get it working and decide to share the knowledge with people who still have difficulty.

Authenticating with Google OAuth is similiar to other OAuth application, but there’s a few tricks to get it working with desktop application because of the nature of windows form. Some few main points you need to remember:

– ConsumerKey and ConsumerSecrets should be “anonymous”

– You should have a personal host lying around (free one is ok) as a callback to get verification code (I will get to that later).

What you need ?

– Scope of data you want to get. Generally a URL which define the data scope of Google service (Contacts, Calendar..) you wish to access. You can find sample data scopes here.

– DevDefined’s OAuth library. You can get it here.

For the purpose of this example, I will use “https://www.google.com/m8/feeds/” as I need to access user’s contacts.

Step 1: Get unauthorized request token.

string requestUrl         = "https://www.google.com/accounts/OAuthGetRequestToken";
string userAuthorizeUrl   = "https://www.google.com/accounts/accounts/OAuthAuthorizeToken";
string accessUrl          = "https://www.google.com/accounts/OAuthGetAccessToken";
string callBackUrl        = "http://yourhost.com/callback.htm";
                              //Blank callback HTML page on your host

 var context = new OAuthConsumerContext()
 {
     ConsumerKey = "anonymous",
     ConsumerSecret = "anonymous",
     SignatureMethod = SignatureMethod.HmacSha1,
     //Remember to use SignatureMethod.HmacSha1 because we're desktop application
 };

 var session = new OAuthSession(context, requestUrl, userAuthorizeUrl, accessUrl, callBackUrl)
  .WithQueryParameters(new { scope = "http://www.google.com/m8/feeds", xoauth_displayname = "Sample Google OAuth application" });
//xoauth_displayname will be your application name displayed on Google confirmation page, so choose carefully.
 var requestToken = session.GetRequestToken();

Step 2: Now we have the unauthorized request token, next step is get Authorization Url so user can grant us access

var loginUri = new Uri(session.GetUserAuthorizationUrlForToken(requestToken));

GoogleLoginForm form = new GoogleLoginForm(loginUri, callBackUrl);

The idea is you create a form which consist of one WebBrowser control, direct user to AuthorizationUrl and parse the verifier code in your callback’s url, here’s the whole code behind for that form:

    public partial class GoogleLoginForm : Form
    {
        private Uri _loginUri;

        string _callBackUrl;
        string _OAuthVerifierToken;
        public string OAuthVerifierToken
        {
            get { return _OAuthVerifierToken; }
        }

        public GoogleLoginForm(Uri authUri, string callBackUrl)
        {
            _loginUri = authUri;
            _callBackUrl = callBackUrl;
            InitializeComponent();
        }

        private void GoogleLoginForm_Load(object sender, EventArgs e)
        {
            wbGoogleLogin.Url = _loginUri;
        }

        private void wbGoogleLogin_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            string fullPath = e.Url.ToString();
            if (fullPath.StartsWith(_callBackUrl))
            {
                string key = "oauth_verifier=";
 //callback.htm?oauth_token=CKF50YzIHxCT85KMAg&oauth_verifier=fERNOO3NfWph90CPCeIutmFA
                int index = fullPath.IndexOf(key);
                if (fullPath.IndexOf(key) != -1)
                {
                    int length = fullPath.IndexOf("&", index) == -1 ? fullPath.Length - (index + key.Length) : fullPath.IndexOf("&", index) - (index + key.Length);
                    _OAuthVerifierToken = fullPath.Substring(index + key.Length, length);

                    DialogResult = DialogResult.OK;
                }
                else DialogResult = DialogResult.Cancel;
            }
        }

    }

The idea is we will try to parse verifier code when we detect user redirected to our callback url, then:

Step 3: Exchange request token for access token

IToken accessToken;
var dr = form.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
    accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, form.OAuthVerifierToken);
}

You see, it’s just that easy, if we have access token then everything just go straight forward:

Step 5: Connect to Google

var request = new ContactsRequest(new RequestSettings("Sample Google OAuth application", "anonymous", "anonymous", accessToken.Token, accessToken.TokenSecret, "", ""));

That’s it. Now you can use your request like everyday use. If you don’t know how to working with Google Data API .NET then refer here.

Written by Tung Linh Le

November 24th, 2010 at 10:13 pm

Posted in Development

Tagged with , , , ,

Games I have finished

with one comment

The world ends with you

I played a lot of game, and, mind you, own quite a collection. Sometime I have the patient to finish some of them, but mostly they’re left somewhere in the middle, just because I don’t have enough time to play everything I bought. Games in Vietnam is dirt cheap, I know. That’s a part of the reason I have too many games in my hand to play.

In Vietnam you can’t just go out and buy a legal version of the game you want. No one sells it because majority of the population don’t have enough money to spend 60$ on each game released. Games are generally sold for about 1$/DVD/game here (yes we price game by the number of DVDs it takes, 4 or 5 years ago it’s priced by CDs). I have about 10-20games lying around and only managed to completed 1 or 2 games I really like. The only console which have games selling legally is PlayStation 3, just because it’s unhackable. If Gamestop have a store here they will go bankrupt because their pricing on used games can’t compete with stores in Vietnam. Generally customers can just bring old game to store which they bought their PS3s and have another game in exchange for like 6$, as opposed to Gamestop where you lose like 20 or 30$ when you sold it back. I dare you enter our realm, Gamestop !

Read the rest of this entry »

Written by Tung Linh Le

October 17th, 2009 at 11:26 pm

Posted in DaysGoneBy

Tagged with ,

Leopard versus Win 7

with one comment

DSC_0003

For a few days I have been trying to install Leopard to my new PC.

At first it proves to be difficult, which should not be, because theoretically Intel Mac and PC are running on the same architecture.  After a week of trying to have Kalyway version of Leopard boot with no success, i decided to search around, and it turns out that my particular mainboard, Asus P5Q Pro , need to update a modded Bios firmware to be able to successfully boot into Mac OS.

So I went ahead and flashed new firmware into my computer (WARNING: kids don’t try this at home), and the rest of the process turn out to be much simpler, except, Leopard doesn’t like my PS/2 keyboard, not-one-bit. It’s 8:30 PM and I rode to my nearest computer shop, which is 4kms away from my house, just in time to buy a 10$ Dell keyboard before they closed.

And from dust it booted. Leopard is great, even better with a 22″ LCD. Only a few drivers need to be installed and it runs at its full glory. No wonder Macs still hold a considerable install base among home PCs. User interface is beautiful, from interface elements to transition effect, everything just blend nicely with each other. Before Win7 (more on that later), no Microsoft OS can hold a candle to Mac OS X. Apple’s designers sure need to be the greatest guys from all over the world to be able to design such a masterpiece.

It’s all about details. You click on an icon, it “bounces” nicely until the application is loaded. You push the Expose button, and all open windows are laid nicely before you for your switching needed (believe me, I really miss it when I get back to Windows). You click on minimize button, and your window “minimizes” with a nice animation, both please to the eyes and at the same time provide you a visual “cue” where your windows minimize to, nice.

That’s really something Microsoft missed when they release Windows Vista. The concept is good, the OS is solid, but it’s like rough diamond. Everything feel like XP with a new sugar coat. It’s rough. No one like it. It’s nice to see but painfully to use. But Microsoft really changes the game with Windows 7. And I can say that’s it’s the most polished Windows ever. Dare I say that Windows 7 is even better than Leopard. Much better.

I will get back about Windows 7 later.

Written by Tung Linh Le

September 11th, 2009 at 11:24 pm

Posted in DaysGoneBy

Tagged with ,

Stair to the sky ?

without comments


Góc nhìn khác chợ hoa hồ Hoàn Kiếm

Written by Tung Linh Le

September 6th, 2009 at 1:57 pm

Posted in DaysGoneBy,Photos

Tagged with ,

PRO WC !

with 2 comments



Written by Tung Linh Le

August 22nd, 2009 at 12:10 am

Posted in DaysGoneBy,Photos

Tagged with ,

Google Contact Sync 1.0

with 3 comments

Warning:

GCS now has a dedicated page here. Please check back for more info and updates

Written by Tung Linh Le

August 20th, 2009 at 3:07 am

Posted in Tools

Tagged with , , , ,

Faces of life

with 10 comments

DSC_0190

Dreamy...

DSC_0182

Deep Sea...

DSC_0187

Colour of Life

Ngứa tay quá up mấy cái ảnh hôm mới sang Denmark đầu tháng. Cũng không đến nỗi tệ lắm nhỉ? :D.

Written by Tung Linh Le

May 26th, 2009 at 3:37 am

Posted in DaysGoneBy,Photos

Tagged with , ,