Thursday, March 31, 2011

Default constructor can be suppressed. But it is required for XAML instantiation

Well the title really say it all doesn't it. If you create a class with a constructor that takes any parameters then the compiler will not create the default constructor for you. In such a case if you try to create the object in XAML your code will compile (actually the BAML will be made so the compiler really doesn't know that you tried to call a default constructor when there isn't one) but you will get a runtime error in InitializeComponent(). Just so you know.


WPF / Silverlight showing content in ControlTemplates

While styling the control template for TabItem for wpf I noticed that the content required to be displayed in the TabItem is actually the header property.

For this in the template ContentPresent with ContentSource="Header" was used.

But ContentSource is not present for Silverlight 4. So I decided to see how silverlight did it. Turns out it is simply ContentControl bound to the Header using TemplateBinding :

Seems obvious in retrospect.


Binding Sources

The syntax of Binding is a source of much confusion to a lot of people (pun intended). But it is really not that hard. Especially once you look at all the possible sources:

  • ElementName (based on an element name present in the scope)
  • RelativeSource (based on a logical tree walk)
  • Source (based on resources)
  • If none of these properties is specified the path will be on the DataContext
Of course if no path is specified then you are binding directly to the source. 

In any case feel free to use the VisualStudio / Expression Blend databinding dialog to have software generate the syntax for you. 

Easy isn't it?

Wednesday, March 30, 2011

Riagenic's RentConnect TabControl style (copy)

A friend of mine (who used to do winforms previously) saw the RentConnect application's image and fell in love with the look and feel instantly. Check out the original application image here :

So I started showing how one would go about making such a look and feel in WPF / Silverlight.
First I showed him a metro button (a post on that later). Next I wanted to show him how the Available Tasks might be a styled TabControl / TabItems.

Based on Sacha's work ( I came up with this:

For selected Items I also added a scale X transform.
You can download all the code from here :

Saturday, March 26, 2011

Swap two numbers without using a temp variable

A friend of mine asked this question while we were in college. I didn't pay much attention to the question, didn't believe it was possible (because we were taught how to swap variables ... and taught to use a temp variable for it). I thought he joking and moved on.

But in my first programming job test this question was there: "How can you swap two numbers without using a temp variable. Hint: think of a mathematical operator"
And the hint gave it away :) I was quite proud of figuring it out myself. You basically just need to store the sum and subtract alternately. Here .. look at the code :

Some C#ish notes: 
Notice that it works even beyond int.MaxValue :) But for it to work you need to make sure that the assembly is not built with checked option and the code is not in a checked scope :

And Just out of curiosity:
Know that in python being a super cool language you can just do :
[x , y] = [ y , x ]

Now ain't that super cool!

Live and learn....and Enjoy! 

Tuesday, March 15, 2011

Exam 70-516 Passed

I passed this exam yesterday. Just got the certificate mail today.

For this exam I prepared using two books.

MCTS Self-Paced Training Kit (Exam 70-561): Microsoft .NET Framework 3.5-ADO.NET Application Development: Microsoft .Net Framework 3.5--ADO.NET Application Development (Self-Paced Training Kits)
This book does not have the best reviews on amazon. But I found it quite pleasing to read.

The other book I read was Programming Microsoft LINQ in Microsoft .NET Framework 4 which is a gem of a book really. I have already written much about this book in various blog posts for LINQ :

All in all the exam was worth it. I learnt a lot of new stuff. And fortunately have already started using standard ADO.NET (non EF / Linq2SQL) in a new highly dynamic application. 

Monday, March 14, 2011

Some cool patterns for MVVM property initialization

This post is about how to setup properties commonly used in MVVM.

The ObservableCollection
I like to create a backing field property. Initilize the backing field immediately. Return the backing field in get. And clear then copy the items into the backing field in set. The performance of add might not be perfect but it is the only option I have I believe:

private ObservableCollection _OpenDocuments = new ObservableCollection();
public ObservableCollection OpenDocuments
    get { return _OpenDocuments; }
        foreach (var item in value)

The RelayCommand
I got this pattern of the code from Karl : Based on how he initializes his RelayCommand. Have a backing field. And in get check the backing field for null. If null create it. Finally return it.

public RelayCommand _SaveStudent;
public RelayCommand SaveStudent
        if (_SaveStudent == null)
            _SaveStudent = new RelayCommand(() => { Save(); }, () => { return CanSaveExecute(); });
        return _SaveStudent;



Sunday, March 13, 2011

Hiding the wpf ribbon application menu

Setting The Application Menu to x:Null or simple not setting any value for the application menu does not work and you still see the ribbon menu button :

But it can be hidden by setting the Ribbon.ApplicationMenu to a dummy item and set its visibility to Collapsed.

You will (ofcourse) still see the button at design time but when you run the application it will be hidden :)

Saturday, March 12, 2011

Forcing the Aero Theme in your application

I have yet to find a theme that I am as satisfied with in WPF as the default aero theme that comes with the framework. But if you do not apply a theme to your application the look and feel of the WPF application will change according to the look and feel setup by the client.

But if you want your WPF application to always use the aero theme irrespective of the current client computer theme setting you can do that in simple steps.

Add a reference to PresentationFramework.Aero :
And set its property "CopyLocal" to true:

Finally add the following to your app.xaml:

                <ResourceDictionary Source="/PresentationFramework.Aero;component\themes/aero.normalcolor.xaml" />

And now your application will use the aero theme irrespective of client settings.

Friday, March 11, 2011

Free+OpenSource software for SQLite database management

Here's another software that I checked out from
Its called SqliteMan
You can download the latest windows version from here :

Its made in Qt4 (C++). Anyways on to the review as a user.
I downloaded the zip file for version 1.2.1 win32 : extracted and run. Easy peasy.
Now for the key features review.

Altertable is pretty basic. I missed that you cannot reorder rows. (although in the software defense it is a drop and recreate table script that would be required)

The create index setting is decent. No surprises there. 

I like the template provided for Create Trigger:

The Sql Editor is pretty basic. No intellisense. Just syntax highlighting.

I specifically liked the CreateView from current statement option.

The describe table option is vital to my way of working. Especially when you end up with legacy code:

However the resultant output is not formatted nicely. Its just a single line.

All in all its a pretty decent piece of software. And for the price you really can't complain.

Thursday, March 10, 2011

Ignorable design time namespace from Blend

Visual studio does not add it to files by default. And in new projects I create in Visual studio I find it annoying to create a random file just to get these namespaces and attribute out of it.

So here it is (tested on VS2010, WPF4). You can copy paste it into the root element of your xaml file :


if only xaml designer had a snippet option I would make one :)

Free+OpenSource software for SQLite database management

I have been looking through SQLite management tools free + opensource (what can I say ... sqlite has me spoilt! ) from here :

And I really like SQLite Studio

Check out there screenshots here :
They pretty much cover everything. I don't need to say much more.

Here are a few I took on windows:
Edit Table
Edit / Add / Commit data in the table
My favorite feature: The DDL for the table

The SQL Editor. And yes Ctrl+Space filled up the tale name for me. Intellisense :)

I needed something lightweight and this is awesome. Just a simple exe :)
Also check out the Query explain: 


Wednesday, March 9, 2011

Software Review : SQLite Designer, SQLite management software in C#

Just ran into a little SQLite database management software "SQLite Designer" written in c# :

A screenshot will do :)

I though updated might work. But didn't :(  Verified from code since it is just a DataTable that is getting updated:

NOTE: I intended to get the source code. But it is not uploaded (in svn or the zip file)! So I used reflector to see the code :)
PS: don't you just love how simple .NET is?

Also comes with a parser:

Is pretty. But I don't see much use of it ... after all I use PSPad :
And the lack of source was overly annoying. 

Monday, March 7, 2011

Verifying a Username/Password using Active Directory

Really simple to do in .NET / C#. Its one of the places where the going the full MS Stack helps.

Here is a simple function that will do the bulk of the work for you.

A using directiive :

using System.DirectoryServices;

An assembly reference (System.DirectoryServices ... obviously):

And this function:

/// Authenticates user name and password on the specified domain
/// Domain Name
/// User Name
/// User Password
/// True if user name and password are valid on domain
public bool AuthenticateUser(string domainName, string userName, string password)
  bool ret = false;
    DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName, userName, password);
    DirectorySearcher dsearch = new DirectorySearcher(de);
    SearchResult results = null;

    results = dsearch.FindOne();

    ret = true;
    ret = false;

  return ret;

A sample call:


Also you can get the current domain the user is logged into using a static property on Environment:




Book Review (Software Pricing) : Don't Just roll the dice

You can down a free pdf version of this book over here :

This book is from the co-founder and joint CEO of Red Gate Software Neil Davidson. The company is known most famously by its tools for SQL Server but recently many people now it by the company that bought reflector (which is the number 1 .net decompilation and IL analysis tool)

I got to know of this book from a tweet by ayende and I fully agree with his blog post :

Since the book is only 65 ish pages I will keep the review short :
This book aims to answer the question "How do I price my software?" 
And it does.

Go read the book !
You will hopefully at least learn what a demand curve is :)
There is lot of stuff about perceived value and how you can set people's perception based on reference points or if you are truly innovative you can enjoy the luxury of creating a reference point for a category. People's knowledge matters. The trick in  fives ($1995) and nines ($0.99$) . Newer versions are helpful.  Linking yourself to the product (i am a telecomm bachelors wink wink).

AND SOO SOO SOO much more.

Sunday, March 6, 2011

.NET Gem: String.PadRight

I never noticed this function before reading this book. An awesome function for string display in a tabular format:

The book reviews of this book on are quite negative but I have found the material in the book to be quite awesome (I have just read the first three chapters as of yet and they were stellar. There may be errors in exercises but I don't do them. I have seen enough .NET code to not need them really).

Saturday, March 5, 2011

Naming conventions : Call it DBStuff or DbStuff?

I have always wondered if it is better to name a class as DBStuff or DbStuff. 

I just noticed that ADO.NET uses DbCommand, DbConnection etc. so it is pretty clear that it should be DbStuff. Funny I never noticed it before. However if all you need to call it is DB .. then all uppercase is the convention (All Uppercase for abbreviations that are 1 or 2 characters long e.g. Math.PI otherwise Pascal case e.g. Guid

"Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal Casing instead."

Friday, March 4, 2011

Trick Question : What is the syntax of Left Inner Join?

Answer : There is no left inner join ... only left/right outer joins and an inner join.

I never like trick interview questions because they judge your presence of mind at the interview moment. You need to judge the interviewer. But nevertheless this question can make it into your interview.

Thursday, March 3, 2011

LINQ to Entity Gotcha : Transaction rollback

Another cool nugget from the book : Programming Microsoft LINQ in Microsoft .NET Framework 4

What happens if you call SaveChanges() and a transaction that continues beyond the SaveChanges call gets aborted?

  • The good: Internally the same transaction is used by the DbConnection. This means all data DB modifications are rolled back.
  • The bad: The EntityState objects managed by the ObjectStateManager  are all set to Modified and are not reverted. These in-memory operations are not protected by the transaction! This means that you will not be able to call SaveChanges again for this particular set of changes. 
So how do you get around this?

Two steps:

  • You need to call an overload of objectContext.SaveChanges providing the SaveOptions enumeration of either SaveOptions.DetectChangesBeforeSave or SaveOptions.None. You cannot use SaveOptions.AcceptAllChangesAfterSave.
  • If the transaction is successful call objectContext.AcceptAllChanges(); after the transaction. 


Wednesday, March 2, 2011

Some cool things about Process explorer

I have process explorer running on every single computer that I have used for greater than 5 minutes. You can see a great presentation on this little tool over here (from tech-ed 2010):

Here are somethings new to me:

Change difference highlight time for process start and exit
Whenever a new process starts it is shown as green:

and whenever a process exits it is shown as red:

However by default it is only shown for 1 second. This is too short when you want a little more headstart into what is going on in your system. You can change this setting from Options - Difference Highlight Duration:
5 Seconds seems appropriate:

Verifying Images
This is a quick way to check if any application has been modified by any virus etc since the time it was release by the publisher. You can enable it from Options - Verify Image Signatures:
And add the column for Verified Signer:

You can rest assured that the ones that state verified are safe applications (if you trust the publisher of course!):

Tuesday, March 1, 2011

What is the maximum number of handles you can create on windows?

If you ever wanted to know the answer, watch this presentation of Mark Russinovich.

TechEd 2010 : Pushing the Limits of Windows with Mark Russinovich

Also covered are virtual memory limits for each application and then the system commit memory limits.
And the best question answered is : How big should be your paging file? Turns out 1.5X RAM is not a neccessary formula. It depends entirely on your workload (i.e how much system commit memory you need).
BTW : If you let windows manage your pagefile, it gets set to 1.5 x RAM minimum and 2 x RAM maximum.

Next Physical memory limits are also covered.

This guy is a genius as most programmers will know him as the developer behind sysinternals. TechEd presentations are more oriented for System Engineers rather than Software engineers but somethings are really useful for programmers as well. This is one of those presentations. This presentation is chucked full with useful information.

He uses TestLimit which he wrote for his book "Windows Internals". You can download a sample chapter of the book as well as the software from here:
Just open Run (Winkey+R) and type in \\\WindowsInternals