Almost Code Complete

It is my belief that every good developer must have read or is reading or atleast intends to read Steve McConnell’s Code Complete. The book essentially is considered to be a bible for software developers. For those focusing more on the coding part of software construction process, reading from Chapter 6 onwards makes sense. I have tried to select some important points out of the chapters focused on coding aspects. Although the whole book is made of important points I just want to underline some key thoughts to take away.

  • A class is a collection of data and routines that share a cohesive, well-defined responsibility.
  • Tap into the power or being able to work in the problem domain rather than at the low-level implementation domain.
  • Abstraction is the ability to view a complex operation in a simplified form.
  • Each class should implement one and only one abstract data type. If a class implements more than one type or you can’t figure out what ADT a class implements then reorganize  that class into more organized classes.
  • When you design a class, check each public routine if there is a need for its complement.
  • Each interface consists of a programmatic part and a semantic part. Programmatic part consists of the data types and other attributes of interface that can be enforced by compiler, semantic part contains assumptions about how the interface will be used which cannot be enforced by compiler. Look for ways to convert semantic interface elements to programmatic interface elements using Asserts or other techniques.
  • Don’t put a routine into a public interface just because it uses only public routines.
  • Code is read far more times than it is written even during initial development.
  • To avoid tight coupling, make data private in base classes rather than protected.
  • Be critical of classes containing more than about seven data members.
  • Follow the Liskov Substitution Principle, which in simple words state that, all the routines defined in the base class should mean the same thing when used in each of it’s derived classes.
  • Minimize indirect routine calls, if a object A instantiates an object B, then a routine in A can call routines on object B but should not call any routines of objects provided in object B.
  • For better readability, put the parameters in an input modify output order. List the parameters in input only, input and output, and output only order.
  • Don’t use routine parameters as working variables, store it in a local copy and use that for modification.
  • Use error handling code for conditions you expect to occur, use assertions for conditions that should never occur.
  • Use access routines instead of global data. It just makes it easy to modify them at a single place.
  • Don’t dump all the global data at a single place. Make sure that information hiding and ADT are maintained, which might result into global data stored into their meaningful classes.
  • Don’t make up phony variables to be used for a case statement. Since they are confusing, use if then statements instead.
  • If you have a loop, put any initialization required by the loop just before the loop to make it more readable.
  • Loop should follow the rule of a routine, they must perform one and only one function. Its better to break a loop into two to perform unrelated things.
  • It is bad practice to use the last value of an index of a loop in the code after the loop. Never assume that a loop will be executed until it’s last step.
  • The fact that a design uses inheritance and polymorphism does not make it a good design. Table driven methods sometimes can produce elegant solutions instead.
  • Use terms named true and false to check boolean value, using 0 and 1 makes code confusing in some cases.

An Interview with Thoughtworks

Recently I had been in a job search mode, got interviewed by Thoughtworks and Microsoft(when I was in US). I was keen in focusing on the “fundu” companies if you know what I mean. Lots of people know how Microsoft Seattle interview process goes, I would certainly like to belabor on Thoughtworks India process. I would say it was a fascinating experience where I learnt quite a few things like test driven development, pair programming and no cubicle culture. Also it did refreshed my old school problem solving techniques, white boarding etc.

So it all started by receiving an email from an HR person about an opportunity at Thoughtworks. Since I already followed Martin Fowler’s blog I knew quite a bit about them. They set up a informal like conversation with a HR person that week. We discussed a lot about what I do, I want to do, about my blog, projects on my resume. It was really a conversation about me marketing myself and the HR person doing his part for Thoughtworks. It went for about one and half hour which ended with he asking about my salary expectations.

After about 2-3 days I got a call from the same person explaining me the next step. He sent me an email which consisted of 2 problem statements Mars Rover problem and Sales Tax problem. You could certainly find these statements by surfing on the net. Here is a link to the sales tax statement I found http://www.experts-exchange.com/Programming/Languages/Java/Q-23985207-SALES-TAX-Java-problem-solution.html. I chose the Mars Rover problem just thinking it was more interesting to solve. It is important to that this stage really decides many things about your onsite interview. They do not just need a working solution, anyone could write one in less than an hour. What makes a good solution is how well the objects are designed, the naming convention and an overall decent to good OOPS knowledge implementation. I mean how well encapsulated your objects are, do you program too much to the implementation rather than to an interface, is your solution extensible because in an onsite interview you would be asked to extend this solution with a more complex requirement. I would suggest you to get a design patterns book just to improve the object design strategy in your solution, I do not say that design patterns must be used but they do help in achieving good object oriented code most of the times :).

After this, I got a call in 3-4 days for an onsite interview in their Pune office. The office, as I expected after reading few blogs, was different than my earlier offices. No cubicles, just one big room with round tables surrounded by chairs, people working on their laptops, a ping pong table at one side and nice lunch room. It was a really innovative idea to have such an office structure. I reached there a little early and I asked for restroom just to get my bearings! I asked a person working there,whether the restroom had cubicles atleast, thank god he took it lightly. The onsite process was designed as follows –:

- A self assessment test – 50 super easy questions in 12 minutes. These consists question like Miner and Minor, are they 1) same meaning, 2) contradictory, 3) Neither.

- A logic test – 11 flowchart questions in 1 hour 15 min. These problems are like following a flowchart, executing the instruction at each step and writing a final output. You just need utter concentration for this one but its fun.

These tests are by no means show stoppers, I think everyone gets through these unless you are really dumb. So no worries until now.

- Pair programming – Here a well seasoned person for Thoughtworks would pair with you and go about refactoring your code submission. This has to be an interactive session where we have to put our own ideas in improving the design and that person would do his part. Make sure you think about some improvements in your design if possible before getting in this stage. You should not be really adamant on your idea if you have any about solving some issue, pair programming is about good interactive programming. At the same time you should not be too submissive and agree to everything for obvious reasons.

- 1st technical interview – This involves 2 Thoughtworkers interviewing you at the same time. There would be discussion about technical expertise you possess, for me lots of questions on .NET were asked. I had to white board some of them to explain some code. There is OOPS design problem to be solved, here they see your capability of creating a decent high level design on the fly within the time span given. The problem could be something like design a video store library application or something on those lines. I kinda screwed up during this stage, my solution for the problem was not really good as far as I know. White boards do make me uncomfortable sometimes :) This interview lasted for like more than 1 and half hour.

- 2nd technical interview – This is a similar interview like the earlier one. I guess its another chance to see if a candidate can show better performance this time. By the way I left my home in Mumbai at 6 in morning and it was 7 in the evening for this interview. I was fucked up pretty much talking all day but I did experience such a day with Microsoft too. There is nothing really different to talk about this interview since it basically is targeted again on OOPS concepts and some problem solving techniques like creating a XOR gate from AND and OR gate.

So that was my experience and I guess it resonates with any other person who went until the final stage. I think it was a good experience knowing a different culture in the software field. Also to be honest it did help me to improve my coding skills by coding for some fun problem statement and getting it reviewed by a coding ninja, getting their insight on improving the design. So let me know if any of you guys need any more “up close” insight on the interview process.

Best of Luck!

RSS Reader using NSXMLParser

I was working on building a slick RSS reader for my iphone since last week. As you might guess, the core problem in building an RSS reader is to create a way to read the XML feed data. For a newcomer, this might sound straigtforward but once they rub nose with it, it would soon be clear that the various forms of feeds that are available now, makes it a tricky task. Above that, iPhone does not support the good guys of XML world, namely NSXMLDocument etc. This class in the Cocoa framework is really helpful with its XPath support to parse XML feeds easily. The NSXMLParser is the sole fighter in the XML arena on the iPhone device (as far as I know). Some folks have tried building wrapper classes to support iPhone, an example is TouchXML which is available at http://code.google.com/p/touchcode/. The class used by this method is CXMLDocument which is kinda on the same lines of NXMLDocument, but with much lesser support for parsing. It turned out that it was not good enough for what I needed to do.

So… I wrote a NSXMLParser! Now lets be honest here, not many people are lovers of Event driven xml programming and I am no exception. It just seems really tedious to take care of all the conditions in such a model when used for parsing. Enough bashing, here is some code to show how it can be used to parse an XML feed at a url.

- (NSMutableArray *)parseXMLFeedAtURL:(NSURL *)URL parseError:(NSError **)error 
{
channelFlag = NO;
mainTitleFlag = 0;
itemFlag = 0;
linkFlag = 0;
feedFlag = NO;
entryFlag = 0;
appDel = (iBlogReaderAppDelegate *)[[UIApplication sharedApplication] delegate];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[parser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
NSError *parseError = [parser parserError];
if (parseError && error) {
*error = parseError;
}
[parser release];
return tempArray;
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{
if (qName) {
elementName = qName;
}
if([elementName isEqualToString:@"channel"])
{
// Seems like a normal RSS feed.
channelFlag = YES;
return;
}

// More code here.

}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
if([elementName isEqualToString:@"feed"] || [elementName isEqualToString:@"rss"] )
{
[parser abortParsing];
}

// More code here.

}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{
if(tempArray != nil)
{
if(charString == nil)
{
charString = [[NSMutableString alloc] init];
}
if(mainTitleFlag == 1 || linkFlag == 1)
{
[charString appendString:string];
}
}
}


The above function acceps a NSURL object which is created using a url string and a pointer to pointer to an NSError object. To use NSXMLParser, the best thing would be to create a new NSObject class. In that class add the above methods so that this implementation stays away from your other application code. NSXMLParser needs didStartElement, didEndElement and foundCharacters methods to read values within elements. More methods are available if you refer to the reference library provided by Apple.



Every time a new tag is encountered, the didStartElement event is triggered, when it ends didEndElement is triggered, and when characters are found between tags the foundCharacters event is triggered. So you see the main issue is here to maintain the flow across events. It is very common to have nested “title” elements in an RSS feed, so care must be taken while parsing them. I use flags to check if certain element has been encountered by the parser or not. Well this method may vary according to your needs. In my app, I support both Atom and RSS feeds so I had to give option for the user to select which feed they need to subscribe to. Below is a snap of that view.



Picture 1



On Done, I loop through the selection list and parse each feed using my parser. Now the way I got these three feeds is by parsing the url entered in the textbox. It would be something like



<link rel="alternate" type="application/rss+xml" title="RSS" href="http://feeds.feedburner.com/codinghorror/" />


I would like to share my XCode project if anyone needs it, although I am not sure where can I upload those files. But that can be figured out later. Let me know if you need any help is using the infamous NSXMLParser :).



Happy Programming!



 

RSS Reader for iPhone

If you have read my blog description just below the blog title you would realize where I am hanging out these days. [object message] is a way to send a message (method) to an object in objective C. I have been working on iphone sdk for a week, going through the online reference library at http://developer.apple.com and stumbling over blogs explaining some code. Let me tell you, this week was full of new learning in terms of a language, a framework and frustrations! Here are a few snapshots of an RSS reader I built for the iphone.

Picture 8 Picture 1Picture 2 Picture 3

Picture 4 Picture 6 Picture 7 Picture 5

Before I delve into the major discussion about the app, let me frustrate those guys who are just entering the world of iphone development. In the XCode editor, which is used for writiing apps on Mac, there are 2 options to debug an application. One is in the iPhone Simulator whose snapshots are seen above. This is available to everyone who installs the iphone sdk. Other option is directly on the device, iPhone or iTouch. Hold On… You can debug and install apps created on an iphone ONLY IF YOU ARE A REGISTERED IPHONE DEVELOPER PAYING $99 TO APPLE EVERY YEAR. smirks!!! The account used for downloading the sdk is not the one used here. You will notice this when you would try to build the application and install it on your iPhone/iTouch and get an error saying something like Unable to Verify device 0X160434fuc@##$#shi#$#$ :), I learnt the hard way, if you want to know more about this mess read the blog post by Ralf Rottman here.

Anyways, if you are done pulling your hair off, here are some functionalities of the Reader –:

- Add and Remove a feed. The feed data gets stored in a property list which are basically a nice way to store application data.

- A refresh button causes s refresh of all blogs and displays the first post of each of them on the first screen.

- Read the post in a browser window itself. This is done using the UIWebVIew class which allows to open a url in a Safari browser window.

Another word of caution for guys trying to build something which would need to parse XML. The NSXML library which is the one used to parse XML in Mac applications does not work on the iphone/itouch but works on the simulator! I have not personally checked this but there are lots of blogs talking about it. So instead I used TouchXML which is an open source library on http://code.google.com/p/touchcode/. More information about how to use the parser in this library is well explained on Dean’s blog http://dblog.com.au/general/iphone-sdk-tutorial-building-an-advanced-rss-reader-using-touchxml-part-1/. Some good references for beginners are here –:

1) Aaron Hillegas book on Cocoa Programming for MacOSX. – This is an awesome book for guys like me who have been working on Windows platform for a while and want to shift gears for some time and get some Cocoa! The book really helps a lot to make us understand several aspects of the Cocoa framework and Objective C. For ebook lovers, there is an online version of this book somewhere in the cloud, I have it, just search for it.

2) http://developer.apple.com Apple has provided extensive coding how to’s and other references which I found helpful.

3) http://theappleblog.com has good tutorials.

The iPhone sdk uses the MVC pattern, so its a good idea to follow that while building our apps.Create a separate View and View Controller for each different screen you wish to see in your app. If you righr click on the project in the left had side tree view panel of XCode you would see an option to add a Group. Click that and add a UIView and a UIViewController in it. This way you just have a clean separaion of all the files. When you create a project like a Utility Application Project or a Navigation project etc you would see some groups already created. So in short, an iPhone/iTouch app at one time displays a single View added as a subview to the main window. To change the screen, remove the view already there and add a new one. Thats how any application on iPhone/iTouch works.Since I use property lists to store the feed data, it becomes really easy to read and write to them. But do not use these lists if you expect the data to grow too much. Property lists are good for few hundred bytes. They are just XML format files which can be added to a project.

I will be posting some code snippets in my subsequent posts since its the code that matters! By this time in a week time or so I have pretty decent understanding on how the View Controllers, Views and other elements of an iPhone application interact with each other. Ill be talking a bit about using UINavigationControllers, sharing data among views and other important things which are used more often. Please let me know if you have any questions, Ill be glad to help.

Happy Programming!

New .NET Logo

I believe I am a little late in talking about the new .NET logo Microsoft showcased at the PDC 2008.

White background

Snapshot 2008-11-10 12-40-10

You could certainly get more on msdn but Scott Hanselman has posted some of them on this blog post.

Peopleware: Aren't we missing it?

I am sure most of the IT guys, especially managers are familiar with the word Peopleware. For those who don’t, it originated from a popular book called Peopleware: Productive Projects and Teams by Tom DeMarco and Timothy Lister. It actually underlines the constant conflicts between individual work and corporate ideologies, something most of the software developers face, but hardly speak about. Its a concept which if understood and followed by managers, can result in great work culture, lesser employee turnovers and higher productivity. If you intend to know just what the heck I have scribbled here, then jump to the conclusion below, although please read the book if you haven’t.

I have been a full time employee in India and later in US, which has inspired me a lot to write this post. An important factor which affects the productivity of a developer is the attiture of their manager towards them in day to day activities. There is a startling difference between the companies based in India and those in US (Well other countries too but I have had experience of US only). I would quote a statement from the book mentioned above,

“Managers are not supposed to make people work, but make it possible for them to work.”.

This statement has such a deep meaning in its own sense. I could expand on this giving my own experience at work. While in India, I constantly had a feeling that the manager to whom I was reporting, was really difficult to approach to. The extremely vertical structure of the Indian software industry results in the developers being less communicating and more bullied by the managers. If you imagine a organization structure chart, the white spaces between these levels signify the place where learning should occur. But in most of the Indian firms I feel this space is void or close to void. The result is the manager thinks of the developers as nothing more than replaceable parts of a working machine. When such a feeling is in the air, developers have a depressing attitude towards their work and company. In this case, either the developer’s performance degrades and they eventually leave. Most of the managers would get on with that by hiring a new developer in that place and life moves on. Only good managers realize that this will cost the company much more than spending some on the efforts for retaining that developer. The main theme of the book is quoted as,

“ The major problems at our work are not so much technological in nature than they are sociological in nature”.

Nature of an outsourced job in India

Honestly I feel there is heck of a difference in the kind of job done in majority of software firms in US and in India. The Indian office of an US counterpart is an offshore development place wherein the work is “supposed” to be done quicker and cheaper. This is the mantra of a global service firm. Although, the offshore office is not an exact counterpart of its western office since things are dealt slightly different here. A developer has to manage his/her everyday tasks along with maintaining communication with the manager. At the end of 8 hours of code crunching, he/she might have to attend a phone or video conference with the client since it is day time at the client, the client needs to talk personally what is going on in the codeville. So you see, typically in a IT service firm in India, a developer has much longer day than usual. Most of the developers have put this in their routine but they know it unknowingly, that they are losing precious amount of time of their life which is just one per person. Overtimes, late night drops are a real common thing among the IT firms here. Well the sad thing is, its the nature of the job which seem to demand it.

Go Startup

Frankly, many people have seen this dieffrence between big fat companies and startups. Most startups or small companies are more open cultured, flat due to its size with a well managed office and the meat of the dicussion, the managers have a closer relation with the team members. For me atleast, if the job does not give me the joy of work I need, the salary ain't worth sqaut. I do not say that all startups and small companies are better to work for than big companies, but as a budding developer I feel more interesting and challenging to be in a small pond rather than an ocean. Talking about startups, people interested in starting a new business, may be in IT or something else must read the blog post about The Art of Bootstrapping by Guy Kawasaki.

Conclusion

IT managers in India have to realize that developers are real asset to a project and not replaceable parts. Low quality software product, delayed projects, scrapped out projects are a result of sociological problems in a team rather than a technical one. The book mentioned above openly explains the mistakes manager have been doing until now, some still do. Good managers spend time and money in hiring good people and trust their capabilities rather than telling them what is to be done at each point of time.

Developers need to realize that the reason you intend to work hard is because you like it and evetually wanna have a better life. But what is the point of that life if you spend your twenties and thirties in a cubicle or an office doing overtime crunching millions of lines of code. Most of us do realize this fact and just keep going, but when you eventually feel like stopping its all over.

Slow down you crazy child,

And take the phone off the hook and disappear for a while.

Its all right, you can afford to lose a day or two,

When will you realize … Vienna waits for you?

-- Billy Joel.

Unlocking iphone 2G safely and correctly



I know I know I am a PC guy! But I could not stop myself buying an iphone as soon as it was released in 2007 being a techjunkie. I enjoyed legally using it when I was in US. Like a honest buyer I used the AT&T sim, paid the bills blah blah. But I had this big question in my mind, what the f*** would I do when I move to India. When I returned here earlier this year iphone was not yet released and the only way to use it was unlocking it. But yet again like an honest buyer I played the wait and watch game, I thought Apple would certainly come up with a plan for people changing their region with the old 2G iphone. But instead they released iPhone 3G here for country which is yet to have a 3G network! So I was left with 2 options, either buy a new iphone in India or unlock my 2G iphone. Hah, like I was gonna be honest anymore!

Thus began my tryst with the hackers. I followed lots of blogs about unlocking it and came across lots of folks with horrible error messages on their iphone sometimes rendering the iphone in recovery mode. No doubt unlocking is a risky business but I had to do it. I spent 2 nights figuring out the error messages I used to get while unlocking it for the first time. Finally I got it right with the following steps for 3 different updates which makes it a pretty much foolproof method. Frankly Pwnage tool is really made for a non-technical person and the errors which we get are some exceptional cases only. Again, these are the steps that have worked for me for all updates until the latest 2.2 update.

Steps for unlocking iphone 2G –:

1) Remove the SIM card. I have found this step important for later activation. Take a backup of your iphone.

2)This is a step many people might not follow but I have found doing this step avoid the 1600 error we get at the end of the process. If the iphone is never unlocked then jump to step 5, if it is, restore the iphone with a .ipsw file downloaded from apple. For ex. while updating to 2.2 my iphone was already pwned to 2.1.1 version. So I restored it to the 2.1 ipsw file I had from apple. If you do not have that file you can look on the internet for it, lots of guys have kept copies of these files. Same procedure must be applied for further updates.

3) Restoring the iphone to an earlier version as described above will take some time. TO restore, connect the iphone, once iTunes fires up. cancel any message boxes for updating the iphone to new versions. Hold Option and click Restore. I think it is Alt on Windows. This will allow you to select a .ipsw file to restore with. While restoring the iphone will restart several times, you would see the apple logo indicating we are using a valid .ipsw file from apple.

4) Once restoration is complete you would get a message of no SIM card installed which is a good sign.

5) Now exit iTunes completely and fire up Pwnage tool. Select iPhone, expert mode and click Next.

Picture 2

6) Allow the tool to search for the restore bundle you downloaded from apple. By default the .ipsw file is in Library/iTunes/iphone software updates on a Mac. I generally transfer this file to a folder on a desktop to make the process easy. I have all the earlier restore bundles in this folder.

Picture 3

7) Select the restore bundle you need, mostly you would select the latest version in this case 2.2 version. Click next. On the next screen you would see several customization options. Select General and click next.

Picture 4

8) If you have a legitimate iPhone contract with your carrier (for instance, and iPhone contract with AT&T), you will need to uncheck the box next to “Activate”

If you don't have one, like me since I am in India with a US iphone I have left it checked.

Change Root Partition size to 1000MB for updating to 2.2.

Picture 5

8) Keep clicking Next until you reach the Build screen again. In between steps include changing icons etc which can be left as it is.

Picture 6

9) Let the tool build the Custom bundle for you, have a drink till then! Store the custom restore file on your machine somewhere. This file will be used to restore the iphone.

Picture 7

10) Once complete, you would get a message asking if your iphone was pwned before. Now since we have restored the iphone in the first step with a legal .ipsw file it is not pwned anymore and hence select No. In either case, if your iphone is pwned earlier or not select No in this step, of course assuming step 1 is done. Click Yes has resulted in 1600 error for me at least.

Picture 8

11) Now are the easy steps. Follow the instructions to get the iphone in recovery mode. You can use iTunes to do this but I prefer to use Pwnage. Once you get a message saying successfully in DRU mode or something, the Pwnage tool job is done!

Picture 10

12) Now move to iTunes. Since iPhone is in recovery mode, you will get an option of clicking the Restore button on iTunes. Hold Option and click Restore to select the Custom Restore bundle just built by Pwnage tool.

13) Now its time to sit back and relax. If anything was done wrong, you would get a 1600 error message just after extracting the bundle. This error message is such a piece of s#$$ that it does no help in understanding what the problem was.

14) I am assuming here that there were no errors till now and the iphone is getting restarted several times with a pineapple logo.

15) Once everything is done, the iphone will show off its home screen. Insert SIM card now. Restore the iphone with the latest backup you took.

16) You should have an unlocked iphone with all your data as before!

I have a feeling that even Apple enjoys playing this “cat and mouse” game with the hackers out there. If you are interested in what the great “Woz” has to say about this please watch this video http://news.bbc.co.uk/1/hi/programmes/click_online/7742797.stm.

Please let me know if you are stuck with some step. Hail the iphone dev team!!

Happy unlocking!! Someone's gonna get PWNED!!

Returning to India!

“ Wherever you wander, wherever you roam 
Always remember you are missed back home ”

Its been a while I wanted to blog about my experience of coming back to my home, India. Living in US was awesome, the time I spent for my Masters, the work I did with an American firm was a lifetime experience. But India was at the back of my mind all the time. When I decided to leave US for good, I was kinda dreading my thought. It is one heck of a big decision in my life. Quite frankly, staying away from home, studying there alone, working there and managing all the day to day things certainly makes us really smarter than before. May be some of us have already had that experience here in India, but I was always in my house during my graduation. I never stayed in a hostel or anything of that kind.Every night after work I used to search for blogs about guys who have already made their move to India. These blogs, and few of my friends who returned to India before me, really helped me make my decision.

It is really a personal choice whether to stay there or come back. I do not think there is anything unpatriotic about not being in India. But there is certainly a clear difference between the lifestyles. In US you will certainly earn well, of course expense is more but still the savings are more than done here. The work culture in American firms is just awesome. I enjoyed working every day for my company in Chicago. But you miss your family at other end. Being such a rich cultural country you certainly miss the festivals every year. I especially missed Diwali, it being such a vibrant festival :). Of course no need to mention the different cuisines we have here. Food is something Indians love from the bottom of their hearts and I bet there is no single restaurant, atleast in Chicago, which can make the kind of pav bhaji the guy at the corner of the street here in my city makes. If you love spicy fast food, Mumbai is the place to be baby!

Things that are different here

Internet Connection – Man, I was so much attached to my wireless since I was on my Mac all the time. Blogging, “ Youtube”ing, checking out pubs to hangout etc was a routine for sure. I was using 6Mbps Comcast high speed internet which was awesome. But in India, it is hard to find such luxury since wireless is not that penetrated in people’s lives. I found it really difficult to not use internet as I was using before. But now I use MTNL’s package which is uncharacteristically pretty fast and not really expensive. I brought my Linksys router with me which I use here in my house. So I am cruising on the internet these days. My package allows me to use unlimited internet after midnight which kinda works for me.

Pollution – This factor is especially for those returning to Mumbai. Pollution due to traffic has soared like hell. I had sore throat for first few days. I also had a viral infection, may be due to the vada pav I had, which went on for a week. It was just irritating being on bed all the time. After living in US for a while, my resistance power had reduced like anything which actually makes us vulnerable to infections here. But how much ever we complain about infection, fever, pollution blah blah blah, Mumbai is always missed, comon be true to yourself!

Parents :) – Yup, parents. I am currently living with my parents and brother in Mumbai. Let me tell you, after living with friends and doing all kinds of “stuff” in US, it is not very easy to give away all that freedom suddenly. Imagine to stop all that frequent pubbing and playing beer pong and what not. But all this comes with a little reward too. We are pampered like little kids all day. I do not need to do laundry, no need to cook, just get what I want. Uber cool!!

Job Search – This is something everyone would be thinking first before moving to a place after a while.  To be honest, having a Masters on my resume, with some cool projects done on campus, and the work experience really boosts the chances of getting an awesome job here. May be this is obvious to everyone, but having such experience on the resume certainly makes it better than the majority, so you are in a much better position in finding a job you want here.

There are so many other things to talk about being back home. I really hope this experience of mine would help you make your decision to stay there or come back. Close yourself in your room and talk to yourself about this in front of a mirror. I am sure the only person who can solve this dilemma is the one looking at you. I am sure there will be a million people telling you what to do and what not to do. In my case people settled in US did persuade me in staying back. Finally I did what was in my mind all the time and I do not think my decision is the right decision. As I said, it is a personal choice after all!

Best of Luck!

Recommended Readings

I love reading books. I try to add a new book in my collection every 2 weeks or so. It’s just one of those things that I cannot quit until I die. The books I recommend are a mixture of technical and non technical books since I think it’s essential for a developer to be enlightened in all aspects of programming. Being a .NET guy my focus is mostly on C# and ASP.NET. The books are not in any particular order but I have loved reading each and every book in this list.I have provided ebook download links for some of them, go ahead and try downloading them.

.NET books

1) C# in a nutshell – O’reilly ( For a beginner in C#)  Download Here

2) CLR via C# – Jeffrey Richter ( For an experienced C# developer, highly recommended to gain in depth knowledge of the .NET runtime.)

3) Professional ASP.NET – Evjen, Hanselman, Rader ( A must have reference book for ASP.NET)

4) Essential ASP.NET – Fritz Onion  (Must have book for clearing concepts in ASP.NET)

5) Essential ASP.NET with examples in C# – Fritz Onion (Must have book for clearing concepts in ASP.NET)  Download Here

6) ASP.NET Ajax in Action – Gallo, Barkol, Vavilala ( Great book for beginner and experienced in ASP.NET Ajax framework)  Download Here

7) Windows Presentation Foundation Unleashed – Adam Nathan ( I think it is the bible for WPF developers)  Download Here

8) ASP.NET 2.0  Website programming – Marco Bellinaso ( Good ASP.NET book with a practical project example in the book)   Download here

General Programming books

1) Introduction to Algorithms – Thomas Cormen ( Must have book to refresh algorithm knowledge if preparing for interviews :))

2) The Algorithm Design Manual – Steven Skeina ( Good book with examples on algorithm applications)

3) Head First Design Patterns – Freeman and Freeman ( My favourite book on design patterns, fun and work approach to teach design patterns, highly recommended for beginners to intermediate)

4) Design Patterns , Elements of reusable object oriented software – Gamma, Helm, johnson, Vlissides  ( The bible for design patterns, although go through the head first book before reading this book, thats my personal experience though).

5) Code Complete – Steve McConnell ( My favourite book, a must have book for every developer on this planet!)

6) Rapid development, Taming wild software schedules – Steve McConnell ( An excellent book for good development practices)  Download Here

7) A pragmatic programmer – ( A must have book for those who wanna be better programmers)  Download Here

8) Programming Interviews exposed ( A nice book for preparing for interviews with companies like Microsoft).

9) Thinkertoys ( A nice book on creative thinking)

Some of these books have been taken from recommended reading sections of the blogs I follow.  I can assure that all of these books have been “tested OK” by many important guys in the programming world. So go ahead and read them!

Happy programming!!

 

 

 

Iphone like unlock screen

Frankly speaking since WPF was introduced every thing I do I feel its an animation!!
I used Kevin's (A guy who worked with me in my earlier company) Kinetic scrolling in my card game to display player names which was cool. I also used similar model to create a iphone like slider(the one which is used to unlock iphone).
Following is an excerpt from the code. Other events are similar to Kevin's scrolling example.
Here the endposition is the x coordinate of the rectangle which contains the sliding canvas.

protected override void OnPreviewMouseMove(MouseEventArgs e)
{
if (slidecanvas.IsMouseCaptured)
{
end = e.GetPosition(this);
if (end.X >= endposition)
{
slidecanvas.ReleaseMouseCapture();
story1.Begin(this);
return;
}

double diff = end.X - start.X;
if (diff > 0)
{
TimeSpan time = etime - stime;
story = (Storyboard)FindResource("Timeline2");
DoubleAnimation anim = (DoubleAnimation)story.Children[0];
anim.To = start.X + diff;
anim.Duration = time;
story.Begin(this);
}
}
}

WPF Basics

Recently I have been working part time on a card game (simplified version of poker) using WPF. I had built some 2D games using Windows forms earlier but let me tell you, WPF is picture perfect for such applications. I have used Expression Blend for designing the game and Visual Studio 2008 for the code behind logic. (That’s a killer combination!). I would point out some important things which I feel WPF beginners would face while building a 2D game.

WPF Animation in code-behind

A 2D game made in WPF with no animation is hard to imagine to me. Expression Blend facilitates with hooking up events to a particular timeline(animation) created. But several times we might need to animate things in the code-behind. Here is a way to do it which I use a lot of times in my code.

C#

Storyboard story1 = (Storyboard)FindResource([key]);

Story1.Begin(this);



That was easy.



Mixing Windows forms with WPF forms.



Since I had few windows forms developed earlier which would be useful in this game, I thought of starting the application with a already existing windows form. This is not that difficult. A WPF application starts from the Main function located in the App.g.cs file (if C# environment) which is at the path projectrootdir/ obj/Debug. This Main function instantiates an object of class App,which is inherited from Application class, and runs it. The App.xaml file contains a StartupUri property to set the start form. Remove that property and a set an eventhandler for the Startup event of App class. In this event handler one can instantiate a form object as needed. The Application xaml tag looks somewhat like this:




xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Startup="Application_Startup">









I will be continuing this blog in later posts diggin into more complex parts. Be in touch.

Some cool stuff!

I am working on building a website consisting of some “cool stuff” using some of the Microsoft features like Silverlight and ASP.NET Ajax. I have pretty simple but handy chat on the web using update panel control. I think with the same structure multiple chat rooms can be built. I also made a customized listbox in Silverlight. The listbox can be modified as you want just by putting in some extra code.


Custom Silverlight ListBox


I have used the Listbox control provided in the Silverlight.Samples.Controls.dll which is located in the Silverlight 1.1 installation directory. The complete path might look like this

C:\Program Files\Microsoft Silverlight 1.1 SDK Alpha Refresh Sept 2007\Tools\SilverlightControlsStarterKit\SilverlightUIControls\ClientBin

To get this path, you would have to build the project file in the directory. Sometimes Visual studio does not allow to reference a dll which is hidden under many diectories. If you add a reference to such a dll you might get an error like the reference path is too long. So copy the dll into your project Bin directory and then add a reference to it. There is a small bug in this Listbox control which was mentioned and fixed as per Vivek Dalvi’s blog. Find the UpdateLayout function in the Listbox.cs file and locate the

Clip = clip;

statement. Replace this by ActualControl.Clip = clip; That’s it. I should have told you this before asking you to reference the dll :).

Now is the time to create items which could be added. The ListBox.Items.Add accepts parameter of FrameworkElement. So the default xaml controls could be added to it but I have not tried all of them. I created a custom control to be added as an item to the listbox. I wanted to display textblocks with rounded corners inside this listbox. To begin with add a Usercontrol item to a Silverlight project. You could see in its code-behind a class inheriting from Control class is generated and some logic in its contructor. Observer the first line.

Stream s = this.GetType().Assembly.GetManifestResourceStream("Silverlightanim.BlogItem.xaml");


To successfully run the GetManifestResourceStream function the item which is given in the string must be marked as an Embedded Resource. If not, you might not get an error but it is just not executed. Following is the xaml code for the BlogItem which I add in the listbox.



Its really nothing heavy, its just has a rectangle with rounded corners and a textblock . Following is the code-behind file.


namespace Silverlightanim

{

public class BlogItem : Control

{

Canvas rootCanvas;

TextBlock block;



public BlogItem()

{

Stream s = this.GetType().Assembly.GetManifestResourceStream("Silverlightanim.BlogItem.xaml");

rootCanvas = (Canvas)this.InitializeFromXaml(new StreamReader(s).ReadToEnd());

block = (TextBlock)rootCanvas.FindName("content");

this.Height = rootCanvas.Height;

this.Width = rootCanvas.Width;

}



public string BlogContent

{

get

{

return block.Text;

}

set

{

block.Text = value;

}

}

}

}



As you see a public property has been declared which sets the text property of the textblock.

Now the final act of using the listbox and this blog item control on a silverlight page. For my project I am getting the data from an xml file which makes it easier to maintain later. Here is a sample xml file

xml version="1.0" encoding="utf-8" ?>

<ContentList>

<Block Content="Hey John!!">Block>

<Block Content="Hey Jerry!!">Block>

<Block Content="Hey Nick!!">Block>

<Block Content="Hey Peter!!">Block>

<Block Content="Hey Charlie!!">Block>

ContentList>



I would not go in detail explaination for the following code since its all obvious. It is the code-behind for the Page.xaml file.


Using Silverlight.Samples.Controls;

ListBox list;

public void Page_Loaded(object o, EventArgs e)

{

// Required to initialize variables

InitializeComponent();



InitializeList();

}



void InitializeList()

{

System.IO.Stream str = this.GetType().Assembly.GetManifestResourceStream("Silverlightanim.Data.xml");

//Initialize Listbox

list = (ListBox)this.FindName("listbox");

XmlReader xr = XmlReader.Create(str);

while (xr.Read())

{

if (xr.IsStartElement("Block"))

{

BlogItem item = new BlogItem();

item.BlogContent = xr.GetAttribute("Content");

list.Items.Add(item);

}

}



list.UpdateItems();

}



Make sure that the xml file is marked as an Embedded Resource and give its complete resource name i.e. namespace.Data.xml for the GetManifestResourceStream function to work. You might have to adjust the width and height properties of the listbox to fit in the items.

Ajaxifying the Web

Web based Chat with Ajax


Having a little chat window with a list of friends connected in the chat room is awesome! But the important thing is it should not be at the expense of the overall performance of the website. I created a website with other silverlight stuff on it and this Chat area as a side thing. I have used the ASP.NET Ajax framework which is pretty simple to use.

Follow the steps and at the end you would be enjoying a chat area on a web page.


Step1 : Creating the Chatter List

Drag a Script Manager on an ASP.NET page. If you create an ASP.NET Futures website, a script manager is already present.

Drag an UpdatePanel on the page and name it,say, chatterUpdatePanel. Drag a ASP.NET listbox control in the Update Panel. Behind the scenes a contenttemplate tag is created under the Update Panel. This is the area for the chatter names which will get update asynchronously.

I thought of having some basic authentication required before chatting. So I created a username and password textbox and a Sign In button outside the Update Panel. The click event of the Signin button must update the chatter listbox. To do this we need to specify a trigger to the update panel.

<asp:UpdatePanel ID="chatterUpdatePanel" UpdateMode="Conditional" runat="server">

<ContentTemplate>

<div id='hello' style="overflow:auto;width:146px" >

<asp:ListBox ID="listChatters" runat="server" Height="180px" Width="200px"

BackColor="White" Font-Names="Verdana">

asp:ListBox>

div>

ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="ChatterTimer" EventName="Tick" />

<asp:AsyncPostBackTrigger ControlID="signin" EventName="Click"/>

Triggers>

asp:UpdatePanel>


The signin controlID is the Sign In button I used for signing in users. You can see another trigger with the control ID of ChatterTimer. Now if some friend of yours signs in at his house, everyone needs to know he signed in so I update the chatter listbox every 10 seconds. For this drag a ASP.NET Timer control on the page outside the update panel. Add a Async trigger to the chatterupdate panel with the event name as “Tick”. Thus every 10 seconds the listbox is updated without refreshing the whole page.


Step 2 : Creating the Messages Listbox

To display messages that are being sent, I use a listbox control. This listbox has to be updated independently of the Chatterlistbox. For this drag another Update Panel on the page and add a listbox in it. Call it say MessagesUpdatePanel.

There has to be an area where a chatter can type his statements and send them. I created a textbox and a button “Send” under the messages listbox. Make sure these two controls are outside the MessagesUpdatePanel. Add an async trigger to this update panel with controlid of the Send button and the event name as Click. Also since the messages come more frequently an update is required in a lesser interval. So drag a timer control and assign interval of 1 second and add an async trigger to the MessagesUpdatePanel with the control id of this timer control and event name “Tick” as follows:

<asp:UpdatePanel ID="messagesUpdatePanel" UpdateMode="Conditional" runat="server">

<ContentTemplate>

<asp:Label runat="server" Text="" ID="labelWelcome" ForeColor="#006699">asp:Label>

<asp:ListBox ID="listMessages" runat="server" Height="280px" Width="392px"

BackColor="Black" ForeColor="limegreen" Font-Names="Verdana">

asp:ListBox>

ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="sendButton" EventName="Click" />

<asp:AsyncPostBackTrigger ControlID="ChatTextTimer" EventName="Tick" />

Triggers>

asp:UpdatePanel>



Please be aware that the textbox which would be used to type statements must be outside the update panel since we do now want to update anything in it.

Step 3 : Storing chat data.

Now since we have the desig ready we need to have a way to store the chatters which have valid accounts. Also for my website I display the latest 10 messages in the messages listbox just for the heck of it I think :). I added a Global.asax file to my project to manage application level data. I have created a List<> of chatters in the global.asax.cs file as follows:

List<Users> chatters = new List<Users>()

List<string> messages = new List<string>();

In the Application_Start event I do the following:

Application.Add("chatters", chatters);

Application.Add("chats", messages);

Now since the Application object can be accessed in the Page too, I add any user which is created on the site into this list. Also as a messages is sent I add it in the messages list.

In the Page_Load event I load the chatters and the messages in the respective listboxes.

Following is a simple way to display List items in a listbox

List<string> messgs = (List<string>)Application["chats"];

listMessages.DataSource = messgs;

listMessages.DataBind();

Similar procedure can be followed for chatter listbox too.

Integrating Windows Live Authentication in your Website

This week Microsoft launched Windows Live Tools for Visual Studio 2008 and Visual Web Developer Express. Its been an exciting experience for me to work on this project. Since I worked on these controls, I thought of sharing my ideas with you about effectively using these controls in your website. I would specifically focus on IDLogin and IDLoginView controls.


1) Download the Windows Live Tools installer from here. The dll’s are installed in Program Files/Windows Live Tools/ directory. Once installed a new tab of Windows Live Tools is created in the Visual Studio toolbox which contains the Live controls.


Design View errors in visual studio

Since Visual Studio 2008 is in beta stage there might be different experiences depending on the configuration of the machines. For some reason if you have problems seeing these controls in the toolbox or there is an error in the design view saying error creating control or something like that, close the IDE, open the visual studio command prompt and issue a command devenv /setup. This will reset IDE environment and possible get rid of the errors.

2) Open Visual Studio 2008 and click New Website. Here you would find a new website template called ASP.NET Windows Live Website. This template has all necessary settings for running Windows Live controls on a page. If you don’t want to use this template for some reason, make sure you have necessary settings on your existing website before using the controls.

For IDLogin control first add a Script Manager to the page since the IDLogin control is an Ajax server control and uses an Update Panel internally to do asynchronous postbacks. IDLoginView has to specific requirements. For specific requirements for Silverlight Media and Contacts control please refer to the Live website here.


Using IDLogin for Windows Live Authentication


This control can be used to authenticate users with their Windows Live ID account. This account is same account used for passport authentication.

Drag the IDLogin control on the page. This control needs a Live Application ID and Secret Key. To get this, click the action list button (little arrow button)on right top control of the control in the designer view.

Click the Create new Application ID link which opens a browser control. Click register an application and fill the details. After submitting those details an Application ID is provided by Windows Live which is unique to your application. Escape key closes the window.

The new Application ID and Secret is stored in an Appsettings section in your web.config file. The control uses this section all the time to authenticate your application so do not delete this section.


If you already have a registered application, paste the Application ID in the value field for wll_appid key and Secret in the value field for the wll_secret key. Save the Web.config file.

The control is ready to go live :). Run the website, a SignIn link is displayed on the page which when clicked takes the user to the Windows Live login page.

The control supports two client side events as OnClientSignIn and OnClientSignOut and two server side evens OnServerSignIn and OnServerSignOut. Further information about these events can be found here.


Important points to remember:

After Windows Live redirects to the return url you provided, the IDLogin control performs a redirect to itself. This is done to avoid firing of the sign in and sign out events every time a page refresh is done by the user. Thus you need to be aware of this fact that a redierct is happening because of the control which you might want to handle in your code. Ill post more such points if I come across while I continue working on them.

Make sure you read the Known Issues section on this link. These issues would be resolved in later releases of the controls.

In the next post I will show how to use IDLogin and IDLoginView control to effectively use ASP.NET membership account and Windows Live account and create associations between them.

Custom Powershell Cmdlets

Command line tools have always been my favorite, whether its a linux box or a windows machine. Its way cooler!! (don't know why). I use Powershell on Windows Vista and I really like for the fact that its designed in .NET environment which makes it easy to extend as you want. I am assuming you have basic information about Cmdlet and Snap-In classes for Powershell. If not, please refer to the the documentation which comes with Powershell installation.

I wanted a simple program to run in Powershell to display the temperature given the zipcode. I am going to show you how easy it is to add a new command in Powershell. A command like dir, ls etc. is called as a Cmdlet in Powershell. To use a new command in Powershell you need to do the following:

1) Create a .NET class which inherites from PSCmdlet. Add the functionality as required. This will be the custom Cmdlet class.

2) Create a new class in same namespace as the above class. The base class for this class should be PSSnapIn. This will be the custom Snap In class which is required to insert any Cmdlet in Powershell.

3) Register the Cmdlet using the SnapIn class we created.

That's it!!

Creating a Custom Cmdlet class

Nothing makes it more clear than a piece of code right. Here it goes!

using System.Management.Automation;
using System.Management.Automation.Provider;

[Cmdlet(VerbsCommon.Get,"temp")]
public class TempCmdlet : PSCmdlet
{
private string zip="60606";
[Parameter(Mandatory=false,Position=0)]
public string ZipCode
{
get
{
return zip;
}
set
{
zip = value;
}
}

public object[] GetData()
{
Service1 service = new Service1();
object[] data = service.GetWeather(ZipCode);
return data;
}

protected override void ProcessRecord()
{
object[] data = GetData();
if (data.Length == 3)
{
WriteObject("Location : " + data[0].ToString());
WriteObject("Condition : " + data[1].ToString());
WriteObject("Temperature : " + data[2].ToString()+ " F");
}
}
}

This is my custom Cmdlet class. Observe the attribute to the class. This attribute shows that the command I would issue at the prompt would be Get-temp. The first part has to be a predefined verb in the VerbsCommon definition. The second part could be anything meaningful to you.

I am using a webservice to get the weather data by passing a zipcode to it. By default its 60606. Of course you could use a data store for the same thing. If you need any parameters to your Cmdlet you should create a Property and assign an attribute called Parameter. There are a bunch of values for this attribute but I used some common ones. The important function to look out is the ProcessRecord. This function is executed when the user invokes the Cmdlet at the prompt. Writeobject function actually writes the data to the output pipeline which is displayed to the user. There are several other functions which can be effectively used to improve the output but I did not go in that detail.

Creating a SnapIn class.

To register the Cmdlet , you need a custom SnapIn class. Here it goes again.

[RunInstaller(true)]
public class TempSnapIn : PSSnapIn
{
public TempSnapIn() : base()
{
}

public override string Name
{
get
{
return "TempSnapIn";
}
}

public override string Vendor
{
get
{
return "Microsoft";
}
}
public override string VendorResource
{
get
{
return "TempSnapIn,Microsoft";
}
}

public override string Description
{
get
{
return "This is a PowerShell snap-in for the Get-temp cmdlet.";
}
}

public override string DescriptionResource
{
get
{
return "GetTempSnapIn,This is a PowerShell snap-in for the Get-temp cmdlet.";
}
}
}

Make sure you override all these properties, if not you would get some error when you try compiling this class. Place this class in the same namespace as the Cmdlet. Although I am not sure if different namespaces would work but you can try that.

Register the Cmdlet

We are ready to register our little Cmdlet created. This is the mose exciting part since we need to hit some commands in Powershell. Yessssssss!!

Open Powershell prompt.

Give the following commands.

PS> $ref = "$Env:ProgramFiles\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll"
PS> $compiler = "$env:windir/Microsoft.NET/Framework/v2.0.50727/csc"
PS> &$compiler /target:library /r:$ref Codefile.cs

Codefile.cs should be the .cs or .vb file for your classes. This is the step to compile the code, you could obviously use the IDE to do this step.

Now to actually register the Cmdlet, use the InstallUtil program.

PS>set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil
PS> installutil Codefile.dll

Replace the Codefie.dll with your dll created in earlier step.

Now add the Snap In we created to the shell

PS>add-pssnapin SnapInclassname
We are done!! You could check by doing Get-temp at the prompt. Do not close the windows since you would lose all the settings you just did. Instead to save the session export the console as below.
PS> export-console MyCustomShell

If you have any particular questions about the code or anything else please reply to this post.

Using IDLoginView with IDLogin Windows Live Control

The IDLoginView control shipped with the Windows Live Tools control is a pretty good control for developers who want to customize the web page look depending on the Sign In status of the user. Normally, you would use a Login control on the page and once signed in with it, you could write a piece of code to display some items on the page which you want to display only to Windows Live Signed In users. Even more, if you plan to use ASP.NET Forms authentication for your website and customize the display for the users after being authenticated with it, you would write your own code to display them. IDLoginView control takes a step ahead and makes it way easy for the developer to assign templates depending on the status of the user visiting the page.

The IDLoginView control has 5 templates defined as follows:

  • Anonymous : Not signed in Windows Live and not authenticated by ASP.NET website
  • Loggedin : Authenticated by ASP.NET but not signed in Windows Live.
  • LoggedInId : Signed in Windows Live
  • LoggedInAll : Signed in Windows Live and ASP.NET website.
  • AssociatePrompt : A template used to prompt the user to associate the windows live ID with the ASP.NET user account.

The templates are self-defined here but the interesting one is the Associate Prompt. This prompt if defined for the control, will prompt the user whether to create an association between their windows live account and ASP.NTE website account. Of course for this template to appear one has to create a website account using the ASP.NET security configuration. Once an association is created, any time later if the user signs in Windows Live they will be automatically authenticated for the ASP.NET website.

Follow the following simple steps to use these controls on your page.

  • Drag a IDLoginView control on the page. In the designer view, click the small arrow button over the control to view all the templates.
  • Drag a ASP.NET Login control and the IDLogin control in this template.
  • Since you would need to see the status of the user all the time, copy these Login and IDLogin control in all the templates.
  • The AssociatePrompt template displays a message with Yes and No buttons. You could change this template as you want, but make sure that there is a button which has a command name as associate_yes and another button with a command name as associate_no.

You could test your application by running the website and signing in Live and ASP.NET website. The prompt appears when you are signed in one of the accounts and then sign in the other account. To this to work you need the PromptOnAssociation to true.

Internally when you give an affirmative response to the prompt, a single row is added in the aspnet_LiveIDAssociation table in ASPNETDB database. You can see this database if you do show all files for the project. If you no longer want this association to take place delete this row from the table, for now, there is no UI to remove the association for the control.

I avoided thorough details about the control since you can find them here.

Cannot Open User Default database Error.

Bug: If you open the table to view the association entry, and then again try running the website you might get an error like Login failed for the default user. This bug is been posted on ASP.NET forums and many other places. I tried closing the IDE and reopening it. The website works, I think this is a bug with the SQL express since when it is open in the IDE, the error appears.

Google gears on iphone, Ohh yeahhh!!

Google announced the Google Gears api which can be used to manage a site data offline. Once the website is in online state, the whole site data will be refreshed with the data that was added while offline. Such a feature is really compelling to me since it happens a lot of times that I have some idea while travelling and need to blog about while fresh in my mind. Google Gears is made purely in HTML and javascript. That brings me to the talk for iphone. Steve Jobs mentioned about iphone not able to run 3rd party applications on it. But I think it would be really interesting to develop an application using Google Gears for such smart phones without installing any other applications on it. The only caveat is the local storage. Being offline, the data entered in the site has to be stored on the phone somewhere. Cookies, not a good idea since they would be cleared sometimes.

SQLite database(the one I know of) can be accessed perfectly from javascript using Ajax and its also possible to store objects like images and other HTML elements.

I really hope Apple and Google comes up with some storage mechanism on the iphone which would allow developers to really create applications which can be "online while offline".

Clickonce Deployment

Recently I had an opportunity to deploy a Desktop application which I was working on for few months into a production server. Microsoft has made the deployment procedure really simple and thus the name. But following the simple steps for the deployment may not succeed all the time(that is my experience). And that's why I sometime call it Click(More than) once deployment!! In general follow the steps as given below which consider some special conditions.

1) Right click the startup project properties. Clickonce deployment cannot be done without signing the manifest. Assembly signing is not required. In the Signing tab, the checkbox for Sign Clickonce manifest is automatically checked when you publish the app. The app is signed with a key (.pfx) created in the project.

2) Click Application Files to make sure all the files you need to be deployed in the project are present in the list. For ex, if you have added a .htm file somewhere in your solution, change its build action to Content. Since the startup project needs a link to this file to be deployed, add a link to the .htm file created in this project. To do this, click Add existing item in startup project. Select .htm file and click Add as link( a small arrow besides Add button).

Set the destination publish address(virtual directory). Click Publish Wizard to customize the folders if needed or Click Publish Now.

Some Caveats :

1) If prerequisites are required by your application, then proper bootstapper package need to be created for the same. To do this the quickest and cleanest way would be to use the Bootstrap Manifest generator. This creates the necessary files in the required location. You can find a step by step guide to use this tool here. Many other customizations could be done like adding Registry checks, file checks etc but those are not needed frequently. Restart VS editor and you should see the created package in the prerequisite list on the publish page. Select that and publish your project again.

2) Make sure that you have access to the virtual directory where you wish to publish this application. If for some reason you don't, publish them in some other folder where you have access and give this accessible folder's path to the virtual directory.

3) There is a publish.htm file created which by default is the starting page for the application. This is the page users will use to install the app. Make sure that the href value of the Install button is set to "setup.exe". Sometimes the value is set to the Application file which does not make sense since the whole reason for using clickonce is to bind the application and all other prerequisite packages into one file which is the executable "setup.exe".

4) There is a known bug in clickonce which I experienced too. On some machines which are used to deploy the application, once the app is published, clicking the RUN button on the publish page opens the setup dialog correctly but after that it opens a message dialog box with no text in it (wierd stuff!!). There is some discussion about this bug on this microsoft forum.

I have not covered the basics of this process assuming that you would know them. Although if you have any other questions, do leave a comment so that I can reply to it.