Thursday, December 30, 2010

2011's Six Month Book Reading Plan

Six Books for first half of New Year.

CLR via C# (Dev-Pro)
CLR via C# (Dev-Pro) is a very good resource to master the intricacies of the common language runtime (CLR) and the .NET Framework 4.0. I think it is time to master C# and .Net Framework and this is one of the most recommended books on stackoverflow.

C# in Depth, Second Edition
C# in Depth, Second Edition is by far the most recommended book for learning deeply about C#. It assumes that you are already familiar with C# and its syntax and doing that allows it to get rid of boring introductory material.

Head First Design Patterns
When people ask for design patterns book for .net, they get Head First Design Patterns. The book provides examples in java but they are relevant for .net developers as well. This book does not cover all the GoF Design Patterns but does a good job of explaining the patterns.

Professional ASP.NET Design Patterns
Professional ASP.NET Design Patterns is more about layered architecture than design patterns. This book covers a lot of ground and is more suited for beginners to mid-level developers. David Hayden has a good review of the book here.

Refactoring: Improving the Design of Existing Code
Refactoring: Improving the Design of Existing Code is kind of natural progression from design patterns. Every application I have worked so far could have used a bit of refactoring and I intend to learn more about it from this book.

The Art of Unit Testing: With Examples in .Net
The Art of Unit Testing: With Examples in .Net The only way I can make changes, refactor and still have confidence in my code is if I have a way of knowing that I haven't broken anything and Unit Tests are a way of doing just that - giving you instant feedback that all is well or NOT!

Tuesday, December 14, 2010

Zen Coding

For those looking to get more with less keystrokes, zencoding plugin is a must. You can write lightening fast HTML using its powerful abbreviation engine.

From its project site -

Zen Coding is an editor plugin for high-speed HTML, XML, XSL (or any other structured code format) coding and editing. The core of this plugin is a powerful abbreviation engine which allows you to expand expressions—similar to CSS selectors—into HTML code.
To appreciate its power you need to play with it. Its author Sergey Chikuyonok has very good article on smashing magazine - a speedy way of writing HTML code. Watch the 6 minute video and you will be a convert.

Here is an example of its power. The following expression

html:4t>div#header+div#main.content
expands to the following snippet -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html lang="en">
 <head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <title></title>
 </head>
 <body>
  <div id="header"></div><div id="main" class="content"></div>
 </body>
 </html>

Or the following example

ul>li#item-$*6
which expands to
<ul>
 <li id="item-1"></li>
 <li id="item-2"></li>
 <li id="item-3"></li>
 <li id="item-4"></li>
 <li id="item-5"></li>
 <li id="item-6"></li>
</ul>

Here is a link to the zencoding cheatsheet. For Resharper fans it is available as ZenCoding Powertoy and there is also a Visual Studio PlugIn


Wednesday, November 24, 2010

Sudoku Validation

In one of the interviews I gave recently, there was a question about sudoku validation (9x9). The logic to check itself is quiet simple -
  1. Check for existing value in row
  2. Check for existing value in column
  3. Check for existing value in block

Solution
Two dimensional array is a good data structure to use for it. My first solution involved using three loops but on refinement I was able to use only one loop for the validation. I find the start of block location first. In the loop checking row and column is quite straight forward. It is checking for value in a block that is a bit tricky and I had to play with LinqPad and Excel before I came up with correct statements.

public static bool Validate(int number, int row, int col)
{
    Console.WriteLine("Writing at pos {0},{1} - value {2}", row - 1, col - 1, number);

    var startBlockX = ((row - 1) / 3) * 3;
    var startBlockY = ((col - 1) / 3) * 3;

    for (int i = 0; i < 9; i++)
    {
        if (arr[i, col - 1] == number)
        {
            Console.WriteLine("found in col value {0}", arr[i, col - 1]);
            return false;
        }

        if (arr[row - 1, i] == number)
        {
            Console.WriteLine("found in row value {0}", arr[row - 1, i]);
            return false;
        }

        var mx = (i / 3) + startBlockX;
        var my = startBlockY + (i % 3);
        Console.WriteLine("block pos {0},{1}", mx, my);

        if (arr[mx, my] == number)
        {
            Console.WriteLine("found in block");
            return false;
        }
    }

    return true;
}

Checking
Using the following array and checking for highlighted spots in figure above for value of 9.

var arr = new int[9, 9];

arr[3, 6] = 9;
arr[3, 8] = 7;
arr[0, 8] = 9;
arr[1, 2] = 2;
arr[7, 7] = 9;
Validate(9, 3, 3);
Checking for pos 2,2 - value 9
found in block

Validate(9, 1, 5);
Checking for pos 0,4 - value 9
found in row

Validate(9, 3, 9);
Checking for pos 2,8 - value 9
found in col

Wednesday, November 17, 2010

SSW Sydney .Net User Group Meet

I just attended SSW Sydney .Net User group meet yesterday for the first time and thought would share a summary. The session was attended by a good crowd of about 50 people. Adam Cogan started the meeting with some industry news. The following wsj article "What They Know" was interesting and informative in showing how much of user tracking is being done even by some of the well respected brands.

The first talk was by Peter Gfader. It was good to see him explain object oriented principles and explain about SOLID which I have blogged about earlier. I had knowledge of Broken Window Theory but Boy Scout Rule was new to me and it was interesting. Peter also showed some examples of bad code and we could relate to it in our works. However because of time constraints he had to rush through showing tools like StyleCop, Code Analysis etc. which was a bit unfortunate. His blog post and presentation slides are available here.

The second talk was by TJ Gokcen and he created an apple iphone application using Monotouch. It was great to see a whole new application being developed using language we know pretty well. But I wonder how complicated native applications we can develop with that. I guess mostly sort of web applications which uses web browser but not heavy apps like games etc. The demonstration itself was very informative and I feel comfortable if I have to develop applications like that in iPhone.

Lastly, it was nice talking to people. I couldn't interact much because of my neck pain but it was good to see and listen to different developers. One gentleman I was talking to mentioned the difference between knowledge of a domain expert and coder and how he would rather teach a domain expert some coding than a coder some domain knowledge. I kind of disagree but that is for some other post. I will update this post with link to TJ's slides and code when it is available.

Takeaways

  • The Broken Window Theory
  • The Boy Scout Rule
  • SOLID Principles
  • StyleCop, Code Analysis
  • MonoTouch
  • Feature Pack 2
  • WSJ article "What They Know"
  • C# 5 CTP
  • Windows 7

Tuesday, November 16, 2010

Firefox Extensions for Web Developers 2010

Even though I use Google Chrome as my primary browser, Firefox is my browser of choice for web development - thanks to its wonderful extensions. This post will be useful to you if you are new to web development and want to know some of the best firefox extensions for web development. 

All the recommended extensions on this page are available in one place as a collection - Devnetfx Web Development

If you are short of time, you need to know just the following two extensions and you will be fine for 90% of your development - Firebug and Web Developer

Web Developer - Web Developer is the plugin of choice for style gurus. The toolbar gives you a lot of options for inspecting, validating and optimizing web-pages. 



Firebug - If Web Developer is the tool of choice for style gurus, Firebug is the tool of choice for back-end developers. It becomes a must when you are doing Ajax debugging. It allows editing, debugging, monitoring CSS, HTML, and JavaScript. Firebug is powerful by itself, but when you add other extensions like YSlow, XRefresh, Firecookie etc., it is unbeatable.


Other Extensions


View Source Chart - I love this extension because it allows you to see DOM structure visually.

MeasureIt - This extension sits in one corner and its when I need to check height and width that I call my friend.

ColorZilla is just like MeasureIt - does its job well and quickly. It is Advanced Eyedropper, ColorPicker, Page Zoomer.

iMacros For Firefox - Allows you to automate Firefox. Record and replay repetitious work. Recently I was doing some artwork uploading at a client which involved a combination of UI steps. Thank God I knew about iMacros for Firefox!

Html Validator adds adds HTML validation inside Firefox. The number of errors of a HTML page is seen on the form of an icon in the status bar when browsing.

YSlow analyzes web pages and why they're slow based on Yahoo!'s rules for high performance web sites. PageSpeed from Google is another one which does the same job of analyzing web pages for performance issues.

FireShot creates screenshots of web pages (entirely or just visible part). I just use the basic version and it does my need for taking snapshots easily.

XRefresh does the job of browser refresh for web developers (integrated into Firebug) You need to download software from binaryage to use it. With most developers using two monitors, it becomes an essential utility to see results instantly.

Dummy Lipsum generates "Lorem Ipsum" dummy text from http://www.lipsum.com.

Firesizer allows you to resize the window to specific dimensions - quickly.

X-Ray When I am too lazy to inspect using Firebug and Web Developer, X-Ray allows me to analyze page quickly.

Notable Omissions -
GreaseMonkey GreaseMonkey is one of the most downloaded extensions and it allows you to customize the way a webpage displays using small bits of JavaScript. Perhaps I will find some scripts to start using it in future.

Resources

The Best 50 Firefox add-ons for Web-developers! has a lot of good suggestion. Apart from XRefresh, View Source Chart, ShowIP it covers a lot of ground.


Firebug Extensions page has a list of extensions for firebug. Some firebug extensions are situation specific like FirePyhton, ColdFire etc. and some are generic which can be used in most cases like YSlow, FireFinder etc. I would recommend you to have a look and see if you can find some that meets your needs.

All the recommended extensions on this page are available in one place as a collection - Devnetfx Web Development. I hope you found some useful extension which will make your life easier as a developer.


Sunday, November 14, 2010

ReSharper For Fluent Development

Tools like Resharper and CodeRush are time savers and a must for fluent development. As they tend to overlap, I settled for Resharper just because of familiarity, though as the following poll shows they pretty much evenly balanced. However both of these has a learning curve and you need to learn few more shortcuts to be effective.

Import Symbol
It is a common to inherit from a class or  use a type which is in other projects and you need to import them before you can use them. In ReSharper there is Import Symbol (Shift+Alt+Space) which lets type completion much more easily. It also adds namespace automatically when you select a type.


Tuesday, November 9, 2010

Fixing Code Format

Just noticed that my code examples were not showing properly in Firefox.


The fix was simple. Added the following css property -
white-spacenormal;

However now IE was not happy -


The correct property in this case was -
white-spacepre-wrap;

With “white-space:pre-wrap”, it's like mix of “pre”, and “normal”.
- Repeated spaces are shrinked into just one space.
- Newline char will force a wrap.
- Very long lines will be automatically wrapped too, by the element's width.

I found the information at xahlee useful when fixing this style issue.

Wednesday, November 3, 2010

Covariance and Contravariance in C# 4.0

Variance is about being able to use an object of one type as if it were another, in a type-safe way. Variance comes into play in delegates and interfaces and are not supported for generic and non generic classes.
public class Person {}
public class Customer : Person {}
Covariance is about values being returned from an operation back to the caller. In the following example, the keyword out is used with generic parameter to support covariance. Contravariance is about values being passed in using keyword in.

delegate T MyFunc<out T>(); 

MyFunc<Customer> customer = () => new Customer();

// Converts using covariance - narrower type to wider type assignment 
MyFunc<Person> person = customer; 
delegate void MyAction<in T>(T t);

MyAction<Person> printPerson = (person)=> Console.WriteLine(person);

// converts using contravariance - assignment from a wider type to a narrower type
MyAction<Customer> printCustomer = printPerson;

Tuesday, November 2, 2010

Lets make it SOLID

One unfortunate aspect of working with object-oriented language is that people working with them think they are object oriented programmer just by using C#, Java etc. While design patterns do make you a better object-oriented programmer, they are also hard to learn especially when starting out. It is here that design principles come in handy. And the good thing is once you know design principles, you tend to find design patterns a natural fit into object-oriented programming.

SOLID Design Principles

Single Responsibility Principle (SRP)
SRP states that every object should only have one reason to change and a single focus of responsibility.

Open-Closed Principle (OCP)
A class should be open for extension but closed for modification.

Liskov Substitution Principle (LSP)
You should be able to use any derived class in place of a parent class and have it behave in the same manner without modification.

Interface Segregation Principle (ISP)
Clients should not be forced to depend upon interfaces that they do not use. Make fine grained interfaces that are client specific.

Dependency Inversion Principle (DIP)
Depend on abstractions, not on concrete classes.

Resources

Objectmentor has some good resources on design principles -

Thursday, October 28, 2010

Code Generation in Ruby

While doing the code generation exercise (chapter 3, code generators) in the book The Pragmatic Programmer, I realized it quickly that C# isn't the best language to do code generation. The main block was that it is too verbose to do regular expression on strings. I had to use Regex.IsMatch and then Regex.Split to get the the tokens. Thats when I looked into ruby.

Regular expressions is a built in feature of Ruby, put between two forward slashes (/). You can use =~ operator for a regex match which sets the special variables $~.  $& holds the text matched by the whole regular expression. $1, $2, etc. hold the text matched by the first, second, and following capturing groups. Some good info here.

class CSharpCode
 def BlankLine
  print "\n"
 end
 
 def Comment comment 
  print "// #{comment}\n"
 end 
 
 def StartMsg name
  print "public struct #{name} {\n"
 end
 
 def EndMsg
  print "}\n"
 end
 
 def SimpleType name, type
  print "\t#{type} #{name};\n"
 end
 
 def ComplexType name, type, size
  if(type == "char[")
   type = "string"
   print "\t#{type} #{name};\n"
  end
 end

end

if __FILE__ == $0
 unless ARGV[0]
  print "cml usage: cml Input.txt\n"
  exit
 end

 if(File.exist?(ARGV[0]))
  CG = CSharpCode.new
  File.open(ARGV[0]).each_line { |line|
   line.chomp!;
   
   if(line =~ /^\s*S/)
    CG.BlankLine
   elsif line =~ /^\#(.*)/
    CG.Comment $1
   elsif line =~ /^M\s*(.+)/
    CG.StartMsg $1
   elsif line =~ /^E/
    CG.EndMsg
   elsif line =~ /F\s*(\w+)\s*(\w+\[)(\d+)\]/
    CG.ComplexType $1, $2, $3
   elsif line =~ /^F\s+(\w+)\s*(\w+)/
    CG.SimpleType $1, $2
   else
    print "Invalid line"
   end
  }
 end
end

Input File
 # Add a product
 # to the 'on-order' list
 M AddProduct
 F id   int
 F name   char[30]
 F order_code int
 E
Output
//  Add a product
//  to the 'on-order' list
public struct AddProduct {
 int id;
 string name;
 int order_code;
}

Wednesday, October 27, 2010

Playing with Google Charts

I wanted to insert a quick chart in my blog using charts from Google Docs after reading about new editor features. It turned out to be very easy. The best thing is that the editor automatically suggests a chart for you when you select data. And with charts, it is easy to visualize that my blog postings are on rise!

Tuesday, October 26, 2010

Hello to RubyMine

As part of starting my adventures in Ruby, I thought an IDE is essential and so settled with RubyMine (on a 30 day trial.) As my first program in ruby I just wanted to print "Hello World" from a static method.


The trick to use was keyword self. The scope of self varies depending on the context. Inside an instance method, self resolves to the receiver object. Outside an instance method, but inside a class definition, self resolves to the class.

class Hello
  def self.SayHello()
    puts "Hello World"
  end
end

Hello.SayHello;

And self is not the only way to create class methods. Here is a list of more.

Thursday, October 21, 2010

Code Contracts

I recently downloaded Code Contracts from Microsoft. I got introduced to Code Contracts in Pragmatic Programmer and then got a better understanding of it from Jon Skeet's C# In Depth while the chapter was freely available (unfortunately, it is not now.) Code Contracts is another tool which should have been here a long while ago in .net world.

In Code Contracts, Preconditions are specified using Contract.Requires to specify constraints on the input to a method. Postconditions are used to specify express constraints on the output of a method using Contract.Ensures. Here is a code snippet from C# in Depth, Chapter 15, which shows code contract in action

static int CountWhitespace(string text) 

    Contract.Requires(text != null, "text"); 
    Contract.Ensures(Contract.Result() >= 0); 
    return text.Count(char.IsWhiteSpace); 
}

Sunday, October 10, 2010

From Nu to NuPack

At last Microsoft gave some good news in the series of bad technologies they rolled out recently - WebMatrix, Lightswitch, NuPack. NuPack is good. It will be used - both by newbies and the veterans. Why? Because it makes life easier for developers and doesn't dumb you down. Inspired from Ruby gems, Nu had gotten some traction as package management system. I have used it and loved it but its new avatar as NuPack is even awesome. Integrated into Visual studio as power shell, it is addictive and I bet, as a positive side effect, we will start using shell more. When you add a package, it adds a reference and merges everything it needs in web.config. For a detail Introduction please follow the scott hanselman's Introducing NuPack Package Management for .NET - Another piece of the Web Stack

NuPack arrived with an interesting debugging tale by Tatham Oddie. It was a great post the way he narrowed down the exception using WinDbg and Reflector.

When I downloaded NuPack, the first I wanted to download was castle ActiveRecord, which unfortunately is not in the package list but there are ELMAH, Castle.Core, Catle.Ioc etc. So start using it and start saving your time.

Scott Gu's Announcing NuPack, ASP.NET MVC 3 Beta, and WebMatrix Beta 2 gives some good links for NuPack and Rob Reynold’s “Evolution of Package Management on .NET” Post (Rob is one of the leaders of the Nu project and is on the NuPack team) gives a good account of whats happening with Nu and NuPack.

Tuesday, August 10, 2010

Microsoft Matrix

My experience with Ruby is that of porting some code to C#. One thing I learned during porting is ruby code seemed much shorter! The other experience came when I tried ruby gems like project management called "Nu" and was immediately sold. This is how easy things should be in .net as well.

When I read about the Jimmy Schementi and the news of lack of commitment to IronRuby, it was again an feeling of abandonment by Microsoft. Microsoft is mostly interested in getting new people to .net world rather developing the ones already on it to higher levels. This article, though related to Microsoft.Data, has what I want to describe. Read the paragraph Thought 3: Shakespeare had it right.
Every Shakespeare play operates on three levels. The first level is embodied in a jester, who entertains the onlookers (mostly children) who are ill-equipped to understand what's going on in the plot. The second level is the plot, which entertains the onlookers who are capable of longer spurts of self-guided attention. And the third level is metaphorical, which entertains the onlookers who are capable of extracting a bottomless stream of interesting, non-explicit symbolic themes from the play's unraveling. Now, here's the kicker of it all: each level entices the onlooker to "upgrade" to the next level.
Microsoft is interested in level one. And it wants its developers to be at level one. While researching for this article found this post by Ayende
John Lam, the guy writing IronRuby, cannot look at the Ruby source code. That is the way Microsoft works. This is setting yourself up for failure, hard.
The post is more than 2 years old and it seems some things never change in Redmond (like Steve Ballmer). On the whole, it seems community wants it to be part of CodePlex Foundation.  JB Evain has some of his thoughts on IronRuby. But the sad reality is, as one of comments say,
If Microsoft doesn’t want the Iron* to have a success for .NET it just won’t happen.
I am curious as to what will be Microsoft's response. Perhaps it is time to leave Microsoft's matrix. Perhaps Google's App Engine is calling. If only they had C# and Visual Studio Integration!

Tuesday, August 3, 2010

10 Blogs to follow for .net web developers

Recently a friend asked which blogs I follow and to answer his question I thought of writing this post. Say "Ahey" if you like the list.

1. Ajaxian - I would look at this first thing in my Google reader. Sadly "Dion and Ben" are not its editors anymore.
2. Ayende @ Rahien - One of the charismatic .net developers, involved in NHibernate, RhinoMocks etc. Must for C# developers.
3. ScottGu's Blog is a good blog for .net developments.
4. Scott Hanselman is another Microsoft guy you need to follow. His ultimate developers tools list is still awesome to find stuff.
5. nettuts+ is good for its articles on web, CSS, jQuery, Html5 etc. - good for the web part.
6. Googland [dev] gathers posts from all official Google development blogs. A great resource to keep track of what's happening in Google world.
7. I like Jon Skeet from his book C# in Depth. He is not regular in blogging but I like his approach.
8. Karl Seguin seems tired of Microsoft technologies but does a good job of opening your mind.
9. High Scalability has good articles if you are interested in, well, high scalability.
10. devnetfx is my journey to become a better (10x) developer.

After compiling my list I thought it would be a good idea to share with others. So here is a link to the bundle so that you can subscribe easily - "DevNetfx" bundle

The bundle has 11 feeds as I added "dion" as well. Ahey! 

Edit: I have a lot more "Subscriptions" which I follow but the above ones covers a lot of ground from different perspectives, and yes, I do follow Coding Horror, Joel on Software but you already had them, didn't you :)

Friday, July 30, 2010

Repeat - Don't Repeat Yourself!

I am reading The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas and I'm sharing my thoughts, questions, confusions and insights as I continue to read the book.

I have folders on my computer with same books, music, software, photos at more than one location. I routinely copy things (my idea of backup) and then would forget about it. Even my Linqpad queries (which I write to test and learn new code) are at more than one place (office, home, usb, Dropbox) and I can bet they are all different. When working on a active project I knew things start looking bad when I start repeating the same logic at more than one place. Now I have repeated myself a lot of times to make it clear that I do repeat things :)

I did attended object-oriented analysis and design classes in my uni days where you learned how to reuse code and good design principles. But, hey, no one told me to... well... not repeat myself! At least not in plain english. No one told me "DRY—Don't Repeat Yourself" when writing programs as that would have been a better advice.

At work the number one reason of repeating some things would be "Impatient Duplication" - time pressures - forcing us to take shortcuts. But, then again, I have spent many hours correcting something which could have been avoided by not repeating it. 

This is one of the first tips which seems to have influenced me. I did cleaned my PC today of duplicated folders. For stuff where I think I need history, I am making use of Subversion. Eliminating all duplication would be a hard task, but I am on it. Now repeat 10 times "DRY—Don't Repeat Yourself", as you know, repetition is the mother of learning!

Thursday, July 22, 2010

This is what we do

I am reading  The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas and the very first page strikes a chord with me. I hope to learn and share few things as I read the book.

Programming is a craft.

At its simplest, it comes down to getting a computer to do what you want it to do (or what your user wants it to do).

As a programmer, you are part listener, part advisor, part interpreter, and part dictator. You try to capture elusive requirements and find a way of expressing them so that a mere machine can do them justice.

You try to document your work so that others can understand it, and you try to engineer your work so that others can build on it. What's more, you try to do all this against the relentless ticking of the project clock.

You work small miracles every day.

It's a difficult job.