Tuesday, April 6, 2010

A Short History of Nearly Everything

A short history of nearly everything is Bill Bryson's guide to scientific history which any layman could understand but that doesn't mean that the book is just too simple. It in fact goes on to discuss topics like Big Bang, General and special relativity, E = mc square, brownian motion, fossils, methods for finding the age of Earth etc. etc. but it's more about how masterfully Bryson has covered and explained all this. From scientific laws to personal details of scientists, it tells everything in an interesting style. And it managed to did what none of my Physics teachers could do, it made me understand Einestine's General law of relativity!

When I was reading the book, I ended up making all these charts and hierarchies of how different scientist over a certain period managed to come across a discovery and it was just too much fun to not to share it here. So here's what I have decided, using this book, I'll chart out that how a certain discovery was made and some details about the scientist involved.

I see three advantages here,

1. It will make me remember all the information.

2. You or I can always refer back to these posts whenever in a hurry.

3. It would save you the time to do all this work, you'll get to the details directly!

It will be a slow and tedious process but I know I'll enjoy it and I hope you would too.

Saying all this, if you have to read just one book in your life then make sure that it's 'A short history of nearly everything'

Sunday, March 28, 2010

Twitter OAuth Login - Part 3

1. Part 1
2. Part 2

Note : As mentioned in part 2 , we will be using Elliot Haughin's twitter library for this article. Please note that library uses codeigniter framework.

So the actual coding integration is actually consist of totally three functions or actions.

1. Create a Twitter login Button.

All you need to do is this,

<a href="index.php/login/twitterLogin" >
<img style="border: 0px none ;" src="images/connenct-twitter.jpg" />

2. Create a function to handle Twitter button click

In our above code, that function or page is, 'index.php/login/twitterLogin'. So when the user will click the link, this function will be called.

This function will redirect the user to Twitter along with sending the consumer key and consumer secret key information. Now from where to get these keys ? If you remember in the last part we registered an application with Twitter, so when Twitter registers an application, it assigns the application a consumer and consumer secret . You can get this information from the application page.


Our function will look like this

function twitterLogin()
{
try
{

$consumer_key = $this->config->item('twitter_consumer_key');
$consumer_key_secret = $this->config->item('twitter_consumer_secret');

$this->load->library('twitter');
$this->twitter->oauth($consumer_key,$consumer_key_secret);
}
catch(Exception $ex)
{
log_message('error', $ex->getMessage());
$error = 'Unable to connect to Twitter, please try after a while.';
}
}
That's all! User will be redirected to Twitter where he will be asked to authorize your application. Once the user allows or denies the access, he will be redirected back to your website. This url will be the 'callback' url you provided at the time of application registration.

3. Create a function to handle User redirection from Twitter

In this function, you will know if the user allowed the access or denied. If allowed then you will talk back to Twitter to send you access token for user. You may want to store this access token in database in order to to use it for future actions like updating his twitter status from your application.

function twitterCallBack()
{
try
{

if(isset($_GET['denied']))
{
header('Location: ' . $this->config->item('base_url'));
return;
}

$consumer_key = $this->config->item('twitter_consumer_key');
$consumer_key_secret = $this->config->item('twitter_consumer_secret');

$this->load->library('session');

$tokens['access_token'] = NULL;
$tokens['access_token_secret'] = NULL;

// GET THE ACCESS TOKENS

$oauth_tokens = $this->session->userdata('twitter_oauth_tokens');

if ( $oauth_tokens !== FALSE ) $tokens = $oauth_tokens;

$this->load->library('twitter');

$auth = $this->twitter->oauth($consumer_key, $consumer_key_secret, $tokens['access_token'], $tokens['access_token_secret']);

if ( isset($auth['access_token']) && isset($auth['access_token_secret']) )
{
// SAVE THE ACCESS TOKENS

$this->session->set_userdata('twitter_oauth_tokens', $auth);

if ( isset($_GET['oauth_token']) )
{
$uri = $_SERVER['REQUEST_URI'];
$parts = explode('?', $uri);

// Now we redirect the user since we've saved their stuff!

header('Location: '.$parts[0]);
return;
}
}

header('Location: ' . $this->config->item('base_url').'index.php/dashboard');
}
catch(Exception $ex)
{
log_message('error', $ex->getMessage());

}

}
...And you are done!

Friday, March 26, 2010

Twitter OAuth Login - Part 2

The part 1 of this post can be checked here

1. First Step : Get a Twitter Account


If you already have a twitter account then you can ignore it else you need to create one at twitter.

2. Second Step : Register your application with Twitter

a. Log in to Twitter.
b. On the top menu, click 'settings'
c. On the settings page, you will see another menu, click 'connections.'
d. On the right hand, you will see a heading 'Developers' with a link to manage your application, click it.

e. You will be redirected to a page with a link to 'register new application,' click it.

f. Fill in the application registration form, it asks for some general information about your website like name and website url. Some important fields you need to fill in correctly are,
  • Call back URL - That's the page user will be redirected to once he will provide twitter his authentication details. This url will eventually be talking back to Twitter in order to get the access token for the user.
  • Application Type : Select 'browser.' 'Client' in other words desktop applications are out of the scope of this document.
  • Default Access Type : If you want to allow user to update his Twitter status right from your application then select 'Read & Write' else just 'Read.'
  • Use Twitter for login : Select it.



g. Once the form has been filled, submit it. If the application has been registered successfully, it will start appearing on Manage Applications page.

3. Third Step : Integrate it into your website

In order to integrate Twitter, you need a Twitter library with OAuth support. You may decide to write everything from scratch but hopefully you wouldn't want to reinvent the wheel. The one that I used is written by 'Elliot Haughin' and you can download it from here : http://www.haughin.com/code/twitter/

He developed it mainly for codeigniter framework but it would work just fine if used otherwise, you may just have to replace some codeigniter keywords. If you want to use a non codeigniter library then check out this one : http://github.com/abraham/twitteroauth

I would be using Elliot's library in rest of the article.

The next post will be the last in the series and would be discussing the code we need to write.

1. Part 1
2. Part 2
3. Part 3

Thursday, March 25, 2010

Twitter OAuth Login - Part 1

You must have noticed that lately a lot of sites have started to use login via Twitter and you migt already have used a screen like the following,



So that's what we will be discussing today, that's how to integrate Twitter login.

Why should we go for login via Twitter (or for that matter any other service like FaceBook)?

Login using a popular third party website is a good option both for the site and the user. User wouldn't have to go through the pain of entering all the sign up details and thus site wouldn't loose a user just because he was too lazy to fill in the sign up information. But offcourse no user wouldn't want to give their Twitter login credentials to just about any site who may end up storing your details in their database and misuse it or their database get hacked. Twitter understands it and therefore supports OAuth.

So what's OAuth and how does this address this issue?
If you're storing protected data on your users' behalf, they shouldn't be spreading their passwords around the web to get access to it. Use OAuth to give your users access to their data while protecting their account credentials.
If you want to understand the A-Z of how OAuth works, go here : http://www.oauth.net/core/1.0/

Let me give you a short summary in plain English. In order to understand how OAuth works, let's define two terminologies in terms of integrating Twitter login,

Consumer - This is the site which wants to integrate Twitter login.
Service provider - Twitter.

Here's the OAuth cycle.

1. Consumer sends a request token to Service provider.

2. Service provider grants a request token. This token is mainly to authorize the consumer using an id and secret key combination. It would be use to get Access token for user.

3. End user gets redirected to service provider's website.

4. User authorizes and gets redirected back to the consumer site

4. Consumer site requests service provider for a access token.

5. Service provider grants the token.

6. User is redirected to protected site pages.

So how could we integrate Twitter login to our website ?

Twitter is a good service but when it comes to API it's quite a pain mainly because it doesn't really have an official library, so you are left with two options: either to build one yourself or try to find a good an reliable library on the net. Twitter suggests some libraries but they aren't official. Secondly Twitter OAuth login is still a ...... beta! And beta services mean only one thing : they can change anytime! But as everybody is using it these days so I hope Twitter will not make any ground breaking changes.

So this post was to give you all the introduction. In next post we will be discussing the actual integration.

1. Part 2
2. Part 3

Codeigniter

I have some experience with cakePHP and I eventually get to play with code igniter - another php framework and I think it's just too brilliant!

It's faster, flexible and much easier than cakePHP but the best part is their detailed guide, just about everything is in there. A codeigniter site is installed as soon as you copy and paste it and writing it's hello world program hardly takes 30 seconds. Learning it is not really a dedicated job, you could learn it on the go thanks to it's extremely well written guide.

Most of the helper functions like emails engine is already there and you don't really have to install any pear library. Unlike cakePHP it is much optimized, eg. it supports persistent db connection by default while cakePHP's default option is non persistent.

So if you are into php coding, this is one framework which you must check : http://codeigniter.com/downloads/

Monday, December 28, 2009

How to be a better programmer

Most of us think that we are very good developers but honestly speaking, it's quite a bit other way round. It's very common to see following piece of code,

bool myFlag;
if(MyFunction() == true)
{
myFlag = true;
}
else
{
myFlag = false;
}
If you write this kind of code then.....you obviously need help some hard work. If you don't and you are actually a decent developer, even then there is always room for improvement. So here's a guide for all those who believe in improving themselves.

Just like any other craft, there is no shortcut to becoming a better programmer, it's all good old classic hard work. Here are some tips which I have gathered over the years and which many other top coders recommend,

1. Read the Code

Read , read and read the code you write. Just like a normal essay writing, code gets better when you review it over and over. Reading the code helps in understanding the overall structure and catching errors which may come during run time. It infact directly affects your unit testing time as chances are that you will pass the testing in first attempt. My personal experience says that reading the code makes me catch errors which would otherwise be very tough to be produced by normal QA testing, mostly because of complex scenarios.

2. Read the Code....that's others Code

Going everyday to your job and writing code all day long doesn't make you a better developer. You would have to see what others are doing. Take up others code, that's of people who have a good reputation as a programmer and read their code. Internet is full of open sourced projects, many companies have opened the source code of many of their products, pick any product that you might have enjoyed using or about which you might have wondered that exactly how it was done and just read the code and play with it. This will teach what smart techniques people are using.

Apart from that, reading others code is an art which isn't that common. Some developers say that it's a gift. If you disagree with me then recall the last time when your manager tried to give you an existing code base and asked to change one of the major functions, chances are that it wasn't your favorite assignment. I believe, the fear of reading others code is more to do with the fear of unknown than anything else. So kill that fear of yours by reading codes of other developers including your colleagues, but just for the sake of keeping your social ranking intact, don't be too emphatic in terms of pointing their mistakes or rather don't point them at all unless you think that it's critical to the project.

3. Join an open source project

By joining an open source project you can get to experience many things very early in your career such as participating in more than one phase of SDLC, direct interaction with the client that's end user in this case, and a coding approach of your choice that's you don't really have to follow the red tapped process of the company. You could also see the results of your efforts much more quickly than normal long term projects which usually come software houses way. Overall open source project not only gives you first hand experience in terms of working with a team with a more active role than a normal junior or mid level developer and it also helps you in getting your communication skills fine tuned and understand end users requirements better.

You may say that it's not important to get to know end user in order to sharpen coding skills, but it in fact gives another perspective to your work because now you also have an idea of how the users are using your applications and what other future expansions are expected.

4. Learn more than one language

I can't emphasize more that how important it is to know more than one language. And if you are a computer science graduate then learning a new language should be second to your nature. Knowing more than one language gives you a new perspective in terms of approaching a problem and figuring out a solution. Every language has it's own constructs but it's always possible that a concept of Java can be used in some form in Dot Net. Similarly, your ASP.Net will definitely see a boast if you know how the underlying response/request process works.

So don't make the mistake of sticking to one language, try to keep your language profile diverse.

5. Basics first

If the only data structure you use is ArrayList or Hashtable then shame on you (seriously!). Keep your knowledge of basic data structures always updated, using a B+ tree instead of a binary tree might make all the difference in the performance of your algorithm but in order to do that you need to know what exactly B+ tree is. Similarly it's also good to know basic algorithms.

With the ultra fast machines we have these days, it's not really critical to have highly optimized code and any efforts in that regard would eventually make it difficult for you to maintain the code. But you still would have to keep a check e.g. O(N square) is definitely something to avoid. So you should be able to do some basic code profiling.

Enjoy programming!

Visual Studio 2010 and .NET Framework 4 Beta period extended

Dr. Somasegar, senior vice president of Microsoft recently mentioned on his blog that the release of VS 2010 has been moved back by a few weeks, as they are focusing on including user feedback after Beta 2 release. The fact is that VS IDE consumes alot of memory and has a habit of getting slow which kills the whole purpose of the IDE that's making programmers productive. And this is pretty much the problem users faced with VS 2010. The virtual memory usage has a lot of problems (IDE crashes are an evidence in that direction) and that's what Microsoft wants to look at and fix. I think it's better to delay the release and get it right than meet the deadline and push over the shit to the poor programmers.

Here's the note,
At the same time, you have also given us feedback around performance issues, specifically in a few key scenarios including virtual memory usage. As you may have seen, we significantly improved performance between Beta 1 and Beta 2. Based on what we’ve heard, we clearly needed to do more work. Over the last couple of months, our engineering team has been doing a push to improve performance. We have made significant progress in this space since Beta 2.

With these improvements in the product, we do want to make sure that they truly address the performance issues while continuing to maintain a high quality bar. As a result, we are going to extend the beta period by adding another interim checkpoint release, a Release Candidate with a broad “go live” license, which will be publicly available in the February 2010 timeframe.

Since the goal of the Release Candidate is to get more feedback from you, the team will need some time to react to that feedback before creating the final release build. We are therefore moving the launch of Visual Studio 2010 and .NET Framework 4 back a few weeks.
Link to Post : Visual Studio 2010 and .NET Framework 4 Beta period extended

Friday, December 11, 2009

Google Vs. Facebook

Google and Facebook are probably not competitors in the truest sense but they are definitely two sites which are always open on my desktop. A few weeks back, I was in Thailand on vacations and well I figured out that in terms of being smart, Facebook somewhat beats Google or GMail to be exact.

As soon as I logged into the two services for the first time from Thailand, here's what happened,

1. FaceBook took me to a new page stating that current location of my login is alot different from my usual login locations, so I need to submit my date of birth (along with year) in order to verify that I am actually Beenish. In contrast GMail must have noticed but didn't bother to raise the issue. So that's extra security measure on FB's part.

2. Once I verified, FaceBook then wondered if I know Thai and would like to switch to Thai, which is again a plus point. FaceBook was offering a functionality on the basis of demographic data, so now user can get advantage of it even if they didn't know about it. And no, GMail didn't mention anything.

3. The point where FaceBook completely outclassed GMail was the speed. As soon as FB identified my new location, it started fetching data from the servers near to that location and not servers near to Pakistan (my previous or default location.) All the members of my party complained that something is wrong with the internet, GMail is just not working and then I identified from the footer bar that GMail is trying to reach the servers which are near to Pakistan (or may have been dedicated for Pakistan)!!!! The service difference was just so obvious, GMail pages were taking like 5 minutes to load during which you are perfectly done with checking FaceBook and writing on a few walls.

So FaceBook is definitely smarter than Google or GMail to be exact :).

Saturday, August 29, 2009

There is no place like 127.0.0.1 :) - errr....come again

Q : 'There is no place like 127.0.0.1 :)' ....errr...come again

Chances are that either you are a techie, and you exactly know what this statement mean, which means that you can totally understand how true it is. And there is also a chance that you are not-so-techie, you saw this statement and thought, 'uh huh, some other stupid, stinky, meaningless tech/mathematical gibberish - oh God! why don't we just keep the technology but get rid of the tech crowd.' In that case, let me explain the statement to you.

We all have heard and believed the phrase that 'There is no place like home.' In the tech world, what's your home ?....mmm....your PC. And in simple, plain English, 127.0.0.1 == your personal PC. For a more technical definition,

127.0.0.1 is a special Internet Protocol (IP) address that points to your own computer. It is also referred to as the local host or loopback address. Local host is sometimes commonly referred to as My computer.
So..now...you see...it wasn't such a meaningless gibberish :) There is definitely no place like my personal computer 127.0.0.1


Q : ...mmmmk...so did you really came up with this statement all by yourself ?

Good Question. Though I do like to think that I can come up much cooler statements, but still, I didn't came up with this one. It's quite a well known saying in the tech crowd. I saw it on a website selling T-Shirts for geeks, and there were some other shirts with statements like 'I failed the Turing test' or 'No, I won't fix your computer!' and yes it took some gigantic efforts on my part to not go ahead and place an order for each and every one of them....:S

Q : .Okay, whatever! I always knew you are a geek.

Nopes, I'm still not a geek! Here are my reasons,

1. I have never watched Star Trek (though I do have a feeling that I'll love it if I ever got to watch it :s)

2. I have no interests in Diana sours, animated or real, never even watched Jurassic Park!

3. I do not have any weird collection of comic characters

4.I never played the quiz 'The one super hero who could become your life partner.'

So...nopes...not a geek!

Microsoft Architecture Journal - Business Intelligence - Call for Paper

First thing first, If you work on Microsoft technologies and don't know about Microsoft Architecture Journal, then you should definitely go ahead and immediately get all the necessary information from their site. Here is a small excerpt from their site,

The Platform Architecture Team is composed of architects focused on architecture guidance and research on upcoming technologies and trends. We are committed to providing thought leadership in order to help every stakeholder in this value chain (users, business managers, IT managers, developers, etc.) understand how today’s business challenges are being addressed by the upcoming wave of technologies and practices. Our intention with all these is to help you get better software that is timely, more maintainable and evolvable.
More details can be found here . And every quarter, they issue a really very valuable magazine, comprising of articles addressing a specific concept from the perspective of different stake holders. You can see all their past magazines on their site and I'll recommend you to take out time and go through them all. They are truly informative.

So, they are making a call for articles for their upcoming issue, it's main theme is 'Business Intelligence'

Dear architect,

We are pleased to announce the call for papers for the 22nd Microsoft Architecture Journal.

Information is at the core of a business's ability to make effective decisions. Architecture initiatives that increase the quality, timeliness, and usefulness of information have a direct correlation to increased revenue and competitiveness. As a result, Business Intelligence is top of mind for business and technology leaders.

For this edition of the Microsoft Architecture Journal, we are looking for interesting, thought-provoking, and insightful articles about effective architecture and Business Intelligence.

Some suggestions for Business Intelligence focus areas include (but are not limited to):
Enterprise Business Intelligence strategy and architecture: Effectively reconciling the explosion of data across Operational Data Stores (ODS) and Data Warehouses (DW), building BI solutions that consolidate and work across heterogeneous data sources, successfully leveraging MOLAP, ROLAP and HOLAP for analysis, and integrating enterprise data with integration services, and Information As A Service (IaaS) across on-premises and cloud models.
Embedding business insights into your applications: How to embed reports and analysis capabilities into your custom and line of business applications.
Infrastructure and performance: Architectural considerations for BI & data warehouse solutions with high-volume, low-latency, low-cost access to data.
End-user and self-service Business Intelligence: Empowering end users to build BI solutions with little to no dependence on IT while enabling IT to maintain monitoring & management of end user built solutions. Helping people access, visualize and model disparate data to improve their ability to quickly make decisions and take action.
Delivering an effective Business Intelligence project: Structuring an effective BI project, including building an effective team, requirements gathering, change management, customer-connected engineering, success criteria, etc.
If you like to share your wisdom and experience with Business Intelligence with the architecture community, this is your chance. To submit your proposal, please send the following before September 11, 2009:
An abstract of between two and four paragraphs.
A short list (2-3 items) of reader's takeaways from business and technical perspectives. This determines the relevance of your value proposition.
A short bio (1-2 paragraphs).
A list of previously published articles, if any.
Submissions must be made to archjrnl@microsoft.com (we receive many submissions for each issue, so we encourage you to put time and thought into yours).

After the call for articles has ended, everyone who has submitted an idea will be notified via e-mail as to whether their submission was accepted or not. If it is accepted, your article must follow this schedule:
September 18. Acceptance notified.
October 8. A first draft (possibly unfinished) is due.
October 22. Final draft is due.*
Mid December. The Journal containing your article is ready and published.
* We recommend that articles be between 2,500 and 3,500 words in length.

For more information, check out this link or contact us at archjrnl@microsoft.com. Good luck!



Sincerely,
Diego Dagum
Editor-in-chief
So if the topic comes under your expertise and you do feel like writing a paper then this might be a chance of addressing a large number of reader. Best of luck!

Weekly Article Recommendation

1. Multi-Targeting Support (VS 2010 and .NET 4 Series) from ScottGu's Blog

Microsoft's Scott Guthrie talks about the improvements in VS 2010 with regards to multi targeting of Dot Net version's.

2. Distributed Caching On The Path To Scalability

An article in MSDN, discussing pretty much everything major about distributed caching for large size applications.

3. Cloud Computing with Amazon Web Services

All that you need to know about cloud computing with Amazon web services.

That's all for this week.

Tuesday, August 18, 2009

Extension less URLs in ASP.Net

Problem Statement
Your Web Server :
IIS 6 or below

You need extension less URLs, like they have in twitter, eg. www.twitter.com/beenish ,. If you notice, it doesn't have any extension like PHP or ASPX, so IIS won't know which dll to call and execute this request, it will simply show you a Page not found - 404 error.

Note : IIS7 supports this feature and Apache has a very simple rewrite module for it.

Solution
Your best bet would be to use an ISAPI rewriter. Ionic ISAPI rewrite is probably the best free one out there. The one drawback it has is the regex formats used, which are a little different from the ones used in Apache, so if you are use to Apache's rewrite module, you might have to make some adjustments. I found it's installation to be quite simple.

You can find all the help at their site.

Apart from this, Scott Guthrie has discussed some nice tips and tricks for URL rewriting, which you can check here : URL Rewriting - Tips/ Tricks

ASP.Net - Single Sign On & Session Handling

The part 1 of this post can be read here.

Problem Statement
So single sign on is all up and running and users are able to login once and access all the sub domains. Now, if you are saving any user data in session then you should remember that every time the user jumps to another sub domain, application reloads the session, which means that your application would be performing the tasks added to any session based event every time user changes the domain. This can become a performance nightmare depending on how much data you are storing and if you are making any db calls.

Another problem would be that you won't be able to share data across sub domains like some kind of flag etc., because session is getting initialized every time the sub domain changes.

Solution
The simplest solution is that you share the session across all sub domains. Here's what you need to do,

1. Make your custom session class by simply inheriting the

System.Web.SessionState.SessionIDManager, System.Web.SessionState.ISessionIDManager

and implement the ISessionIDManager interface's methods. Here's what the end result will be,

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public class MySession : System.Web.SessionState.SessionIDManager, System.Web.SessionState.ISessionIDManager

{

#region ISessionIDManager Members

string System.Web.SessionState.ISessionIDManager.CreateSessionID(HttpContext context)
{
return base.CreateSessionID(context);
}

string System.Web.SessionState.ISessionIDManager.GetSessionID(HttpContext context)
{
return base.GetSessionID(context);
}

void System.Web.SessionState.ISessionIDManager.Initialize()
{
base.Initialize();
}

bool System.Web.SessionState.ISessionIDManager.InitializeRequest(HttpContext context, bool suppressAutoDetectRedirect, out bool supportSessionIDReissue)
{
return base.InitializeRequest(context, suppressAutoDetectRedirect, out supportSessionIDReissue);
}

void System.Web.SessionState.ISessionIDManager.RemoveSessionID(HttpContext context)
{
base.RemoveSessionID(context);
}

void System.Web.SessionState.ISessionIDManager.SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
{
base.SaveSessionID(context, id, out redirected, out cookieAdded);
HttpContext.Current.Response.Cookies["ARSessionCookie"].Domain = FormsAuthentication.CookieDomain;
}

bool System.Web.SessionState.ISessionIDManager.Validate(string id)
{
return base.Validate(id);
}

#endregion
}


2. Add the following to your web.config

[sessionState sessionIDManagerType="MySession" cookieName="MySessionCookie"][/sessionState>]

Note : Replace [ with <> .

You are done! Now user's session will be shared across all the sub domains (considering that it's the same server) .

Friday, August 7, 2009

Binary Search

The Algo as I can recall

So this quick discussion about Binary search is because one of the readers namely 'alifnoon' on my other blog wanted to see how many software engineers can actually write a correct binary search algorithm, which we all feel is quite simple. I agreed to do the exercise and post the results on this blog.

This code piece is something which I studied in Robert Sedgwick's book some years back,

public bool SearchItem(object itemToSearch, object[] itemList)
{
int leftIndex =1;
int rightIndex = itemList.Length;
int median=0;

while(rightIndex >= leftIndex)
{
median = (leftIndex + rightIndex) / 2;

if(itemToSearch == itemList[median])
return true;

if(itemToSearch < itemList[median])
rightIndex = median - 1;
else
leftIndex = median + 1;

}

return false;

}
I believe this is the code which follows divide and conquer approach. I stayed true to my words and gave you what I had in my mind.

My Two Cents
In the second part of this post, let me add a few things. I went ahead and searched around and came across this

http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

where the writer has mentioned that there is a major flaw in binary search.

So alifnoon, I do want to give my two cents. I don't think that this is a flaw in the algo , it's more about scope definition. We can easily add the information to algo that it will work for values up to XYZ. It's understandable that they couldn't cover such scenarios mainly because they never really had to deal with such large values. If I look in this direction then right and left indexes are defined as int, and their values can become too large to beat an int.

If we would try to come up with applications which would work for every scenario and would have undefined scope then I doubt there is any chance of making one.

So just like any other field, algorithms are continuously evolving depending on changing requirements. That's how I feel :)

Conclusion
Thanks alifnoon for raising this issue, I sort of enjoyed this exercise and have decided to do some exercises out of programming pearls, it's almost an year that I last touched it.

Friday, June 19, 2009

ASP.Net - Single Sign On

Task : As soon as user logs into the website, he remains logged in even if he move across sub domains.

eg. if user logged in to the website using www.domain.com, now via a link, he moves to subdomain.domain.com then he should not be required to re login.

Solution :

In order to achieve this, you need to take two actions,

1. Make the following changes in web.config :

Within System.web element, add the following,

<authentication mode="Forms">
<forms path="/" name=".cookieName" cookieless="UseCookies" domain=".domainname.com"/>

</authentication>

If your site's domain address is "www.sitename.com" then domain will be set as ".sitename.com"

2. Add the following code piece to the code which runs on logout,

HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (cookie != null)

{

cookie.Domain = FormsAuthentication.CookieDomain;

cookie.Expires = DateTime.Now.AddDays(-360);

Response.Cookies.Add(cookie);

}

FormsAuthentication.SignOut();

If you use a single domain then it's not required that you explicitly expire the authentication cookie, a simple ForsmAuthentication.SignOut() should work fine, but once the cookie domain is set then you will need to expire the cookie explicitly, otherwise your user will remain logged in.

Once you have done both the actions, your job is done and your user's login should work for the main domain and all the sub domains.

Next Problem >> Though this solution will keep the user logged in but every time when he will move to a new sub domain, his session will renew, any information which you placed into the session at the time of logging in will be lost too. The informatino can be refilled but more than that it's a performance issue.

Let's discuss this in Part 2.

Monday, June 15, 2009

ASP.Net - Calculate label width dynamically using the text

Sometimes, we have to calculate a label's width dynamically , depending on the provided text. In order to do that, use the following,

float width = Graphics.FromImage(new Bitmap(1, 1)).MeasureString("Hello world!", new Font("Verdana", 14)).Width

You will have to mention the font family and the desired size.

ASP.Net Menu Control - Rounded Corners

So it's a little hard to play with ASP.Net's menu and there is no simple way to have tab with rounded corners unless you decide to do something with the render method of menu control, which is time consuming. And it doesn't help that menu item class is sealed and you can't do anything to it.

So here is this simple hack which will make the selected item's corner as image based, but with this simple trick, you can do alot of other creative things.

The whole idea is to set the selected item's text and you can specify any type of HTML using this!

Handle the menu's databound event and add the following code, as a side note, the HTML used here is not good and is not the suggested way of doing it, go for div based HTML with everything handled via CSS

protected void mainMenu_DataBound(object sender, EventArgs e)
{

if (!Page.IsPostBack)

if (mainMenu.SelectedItem != null)
{
MenuItem selectedItem = mainMenu.SelectedItem;

if (mainMenu.SelectedItem.Parent != null) //assuming two level menu
selectedItem = mainMenu.SelectedItem.Parent;

if (selectedItem != null)
{
string imgBg = "images/menubg.jpg";
string imgLeft = "images/menuleft.jpg";
string imgRight = "images/menuright.jpg";

_width = 240; //You may want to calculate it dynamically

selectedItem.Text = String.Format
(@"<table width='{5}' border='0' cellspacing='0' cellpadding='0'>
<tr>
<td width='6px' valign='top' background=''><img src='{1}' width='6' height='41' style='border:0px;' /></td>
<td width='{4}px' align='center' background='{2}' class='links'><div align='center'><strong>{0}</strong></div></td>
<td width='11px' valign='top'><img src='{3}' width='11' height='41' style='border:0px;' /></td>
</tr>
</table>", selectedItem.Text, imgLeft, imgBg, imgRight, _width, _width + 20);

}
}
}

Not the best solution out there, but it's definitely quick and dirty.

Update : As one of my friends just mentioned to me, apart from tables/div, you can also use JQuery to get rounded corners (which is actually the preferred approach these days,) but the approach of getting the rounded corner could be anything you want, using the selectedItem.Text property will allow you to set the Item's HTML according to your desire as you can't inherit MenuItem control and overwrite it's Render method.

Latest Move : Dot Net 2.0 to Dot Net 3.5

So we moved one of our products from Dot Net 2.0 to Dot Net 3.5. Our move planning was simple,

1. Study the breaking changes list and see if anything is critical to our application - apparently nothing was.

2. Make a copy of application and export it to VS 2008 - This worked fine too

3. Provide a copy to QA for testing and see that how it works.

And with some minor issues, everything turned out to be quite fine. Here let me tell you a few more things ,

1. If you have installed 3.5 on your machine and then went to IIS >> ASP.Net tab, and surprisingly version 3.5 was not there, then don't be surprised. Version 3.5 actually uses 2.0 engine, there is no change with regards to IIS, so leave the version at 2.0.

2. You'll need to change the compilation version to 3.5, for that you just need to add the following to your web.config

<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<provideroption name="CompilerVersion" value="v3.5">
</provideroption>
</compiler>
</compilers>
</system.codedom >

And your job is done!