I know the answer (it's 42)

A blog on coding, .NET, .NET Compact Framework and life in general....

Posts
  • I know the answer (it's 42)

    C#: String comparison guidelines and common usage

    • 2 Comments

    The recommendation for string comparison has been updated for Whidbey (Visual Studio 2005) and there is an excellent MSDN article on this. One of the highlights is the introduction of the clear cut enumeration that can be passed into most string comparison methods to indicate the kind of comparison you are trying to make.

    [Serializable]

    [ComVisible(true)]

    public enum StringComparison

    {

    CurrentCulture = 0,

    CurrentCultureIgnoreCase = 1,

    InvariantCulture = 2,

    InvariantCultureIgnoreCase = 3,

    Ordinal = 4,

    OrdinalIgnoreCase = 5,

    }

    The recommendation also states that for culture-agnostic comparisons use the Ordinal and OrdinalIgnoreCase comparisons. These are fast and also safe. They rely on byte matching and are excellent options for matching strings for internal (non-UI) processing.

    string.Compare(str1, str2, StringComparison.Ordinal);

    With the introduction of the guidelines, developers have become defensive and have started looking for all code that compare string and re-coding them to meet the guidelines. Let's take a look at the most common culture-agnostic string matching used in code and see if they are safe.

    string.Equals(string1, string2)

    Default interpretation for equals is Ordinal so using this is fine. In case of using any other type of comparison use in the lines of
    string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

    string1 == string2

    In accordance to the class library design guidelines the == operator for string is overloaded and the implementation is same as for string.Equals. So this is equivalent of calling string.Equals(string1, string2, StringComparison.Ordinal) which is also fine.

    switch(string1)

    For small sized switch blocks of the form

    string myStr = "Abhinaba";

    // ...

    switch (myStr)

    {

    case "Abhinaba":

    Console.WriteLine("switch match"); break;

    default:

    Console.WriteLine("switch did not match"); break;

    }

    the code is compiled into 

    if ((myStr!= null) && (myStr == "Abhinaba"))

    {

    Console.WriteLine("switch match");

    }

    else

    {

    Console.WriteLine("switch did not match");

    }

    So this is also fine and the comparison will be a string.Equals( strA, strB, StringComparison.Ordinal) comparison.

    However, if the switch block is larger then things get complicated. A dictionary is created and lookup happens through Dictionary.TryGetValue with the string as the key. Lookup happens using code similar to

    int num1 = this.comparer.GetHashCode(key) & 0x7fffffff;

    for (int num2 = this.buckets[num1 % this.buckets.Length]; num2 >= 0; num2 = this.entries[num2].next)

    {

    if ((this.entries[num2].hashCode == num1) && this.comparer.Equals(this.entries[num2].key, key))

    {

    return num2;

    }

    }

    A quick look and a bit of poking around with reflector indicates that the result will ultimately be the same as string.Equals( strA, strB, StringComparison.Ordinal).

    InvariantCulture

    As the guideline suggests replace all InvariantCulture usage with either Ordinal or OrdinalIgnoreCase

    Be on the Safe Side

    The above discussion was mainly to figure out what to make out of common string comparison statements in existing code. Going forward I think its best to be defensive and clear in code and explicitly call the comparison methods and pass the correct StringComparison enumeration constant.

  • I know the answer (it's 42)

    C# 2.0: life was a bit more difficult without Static classes

    • 2 Comments

    Usefulness of a new feature is best understood if you try to implement something that the feature targets without using that feature. I started programming in C# when v2.0 was already available internally, so I got used to many of the new features in v2.0 without realizing the people outside have to work hard to get the same thing done.... One of these features is static classes. We use this in lot of places in our Team System code to group resources like constant strings, methods that operate on them and also utility methods that do not need any instance to operate. So a typical implementation is something like

    public static class BuildStatus

    {

    public static string Initializing { get { return BTRes.Initializing; } }

    public static string Sync { get { return BTRes.sync; } }

    public static string SyncCompleted { get { return BTRes.syncCompleted; } }

    /* ... */

    internal static bool IsOneOfCompletedStatus(BuildStatusIconID status)

    { /* ... */ }

    }

    Marking these classes as static ensure all of the following

    • Ensure that only static members can be placed in them
    • Unnecessary instance of the class will not be created
    • They are sealed and cannot be inherited from
    • They will not contain instance constructors

    Pre C#2.0 classes couldn't be marked as static and the workaround was to use the following pattern

    public sealed class MyStaticClass

    {

    private MyStaticClass(){}

    public static void MyStaticMethod(){ /* ... */}

    public static string Author = "Abhinaba";

    }

    So the class had to be marked sealed to stop inheriting and you needed to have a private constructor to stop creation of instances. Even then things did not work out perfectly as anyone could just go ahead and add instance members. With static modifier being supported for classes, the compiler can ensure that no instance members are added by mistake and it also helps in code-readability.

  • I know the answer (it's 42)

    TFS prank: Scare your developer with a bug created by the CEO

    • 2 Comments

    Raymond Chen in one of his posts jokingly wished that if he could use an alter-ego to update bugs in the bug-repository it'd be great. Actually there is a neat feature in Team Foundation Server's Work-Item tracking (WIT) client using which you can do just that. See the screen shot below. Looks like Mr.Ceo made some changes to the bug.

    The feature is that the history tab where you enter comments support rich text. So I copied a bit of the history text, pasted it and then changed the text. So this exactly looks and feels (the + buttons are expandable as well) like another history item. Next time the dev checks the bug, he'd not be very happy about it.

    I'll let you into another secret. I did make a change like this in an actual bug. A reward awaits for the dev/test in our tem who finds it......

     

     

  • I know the answer (it's 42)

    Everyone working in Microsoft are millionaires

    • 2 Comments

    24 hours and 5 movies later I finally landed in Seattle. Journey was uneventful other than the fact that the security in Amsterdam had some doubt about my passport :) As usual my Microsoft blue badge did the trick. They seemed to be more convinced by the blue badge than my passport, I guess the computer in front of them running Windows helped me a bit :)

    I was in the immigration check queue and the officer there asked me how much cash I was carrying. I gave him the 3 digit number (see I'm being discreet here) and he gave me a shocked look and said "I thought everyone working for Microsoft are millionaires, and you are carrying just that much cash!!!".

    I didn't get into a detailed discussion about the merits of credit cards or the current price of MS stocks, just gave a little smile and proceeded to get into US....

  • I know the answer (it's 42)

    Calling desctructors in email

    • 2 Comments

    I have the habit of ending emails I send with ~Abhinaba. So my emails would go like

    Hi <Someone or SomeGroup>
    <body of email>
    ~Abhinaba

    Each time one of my friend would recieve such an email he'd reply back with "Email error: Calling destructor explicitly is not allowed. After closing the email you'd anyway go out of scope and the desctructor would be called"

    Avoid having such friends and if you do kick them on their backside for such replies :)

  • I know the answer (it's 42)

    Front license plates are not required in NC and many other states in the US

    • 1 Comments

    While this can be very common and insignificant information for most people in US and specifically those from the 19 states that doesn't officially need a front license plate, it caught us by surprise. 

    We (me another colleague Neeraja) went to Microsoft Raleigh (in NC) for some work. Early morning we got down at the airport and reached Avis car rental. We were given the car number and so we headed towards the parking lot. The first car didn't have a number plate and so we went to the next and the next and the next. Puzzled we went to the attendant and told him none of the cars have number plates. He explained and we went to the back of the car and finally found the one we were looking for!!

    Its another thing that Neeraja felt that the car, a Chevy HHR was the ugliest looking car she had ever got into. I kind off liked it though. However, we can vouch for one of the claims they're making on the web-site the hidden rear cargo compartment. We didn't see it, so it must've been well hidden.

  • I know the answer (it's 42)

    Most users do not read documentation

    • 1 Comments

    This was something our User-Experience folks keep telling us. Frameworks and UI needs to be designed such that they fall into the pattern that'll be assumed by the user.

    Recently I got bitten by this. I was writing some verification code which needed to get the pixel color from a location on desktop and match it against a known color. I used the following code

    int hwnd = Native.GetDesktopWindow();
    int desktopDC = Native.GetWindowDC(hwnd);
    uint pixel = Native.GetPixel(desktopDC, x, y);
    Native.ReleaseDC(hwnd, desktopDC);
    Color realCol = Color.FromArgb((int)pixel);

    Then I was comparing the RGB components of realCol with my expectedColor. Funnily the test was failing each time. Then I dug a bit into the documentation and to my utter disbelief found that the following code was yielding me ABGR and not ARGB.

    GetPixel returns COLORREF who's documentation states that the color is stored in 0x00bbggrr. This resulted in this.

  • I know the answer (it's 42)

    Back from vacation

    • 1 Comments

    For folks missing my posts (are there any such people :) ) I am back from vacation. I was getting scorched in the hot Mumbai sun and then I was chilling out in Daman or in the Buddhist caves in the western Ghat.

    I was welcomed home with a long list of bugs and emails, emails and more emails. As someone who joined MS recently said "Man!!! it rains emails here"

    Me getting baked in Juhu Beach

    Chilling out in Cidade De Daman. Obviously I'm not in the frame as I took the picture and was juggling 2 beer cans and my camera at that time ;^)

  • I know the answer (it's 42)

    C#2.0: Generic methods, delegates and type inference...

    • 1 Comments

    I did not like var in C# 3.0 because I felt it reduces code readability. For the same reason I do not like using Type-Inference in C# 2.0 generics.

    class MyClass

    {

    public void MyMethod<T>(T value) {

    Console.WriteLine("{0} {1}", typeof(T).FullName,
    value.ToString());

    }

    }

    class Program

    {

    static void Main(string[] args)

    {

    MyClass mc = new MyClass();

    mc.MyMethod(5); // Type inference

    mc.MyMethod<int>(12); // Explicit type parameter

    }

    }

    Even though the first one using type inference requires less typing (and I'm sure will go a long way in CTS erradication) I prefer the more verbose explicit type parameter.

    However when applied to generic delegates, type inference becomes a bit different. Consider the following

    class MyClass

    {

    public delegate void Foo<T>(T item);

    private void Bar(int i)

    {

    Foo<int> foo = MyMethod; // MyMethod<int> is inferred

    //Foo foo = MyMethod<int>;

    }

    public void MyMethod<T>(T value)

    {

    }

    }

    I was talking to a friend some-time back and when compared to generic methods, he had assumed that  type inference for generic delegate would mean that the type parameter of the delegate will be inferred. However as we see from the example above that the type of the delegate needs to be explictly given and from this the type of the generic method is inferred. I am kind of OK with this because at least the types are specified in the statement...

  • I know the answer (it's 42)

    C#2.0: Nullable types, lifted operators and some compare weirdness

    • 1 Comments
    Recently I was stumped on some weird comparisons and I promised myself I'd do some investigations. I figured out with help of some people like Erric Lippert they are due to the inclusion of nullable types in the language. When a new feature is added the ripple effects reach every nook and corner of the language, nullable types are no exception to this. Consider the following code and try to guess whether they'll compile

    int i = 5;

    if ( i == null )

    Console.WriteLine ("null");

    if ( 5 == null )

    Console.WriteLine ("null");

    The answer is "NO" on C#1.1 but "YES, with warnings" on C#2.0. The warning give away the reason why they compile "The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' ". The part in bold clearly indicates that the i and 5 are getting converted to the nullable type int?.

    Lifted conversion operator

    According to the C#2.0 spec if there exists an conversion from a type S to T then a lifted conversion operator exists from S? to T?. For this conversion T? will be unwrapped to T, then T will be converted to S and then S will be wrapped into a S?

    struct S

    {

    public static implicit operator S(T t){

    Console.WriteLine("Conversion T=>S");

    return new S();

    }

    }

    struct T

    {

    }

    class Program

    {

    static void Main(string[] args)

    {

    T t = new T();

    S s = t;

    T? tq = new T();

    S? sq = tq;

    }

    }

    In the above code even if T? to S? conversion does not exist directly it will go through. The output will have two "Conversion S=>T" indicating that even for the second conversion the same conversion operator was called. There is an exception rule to it though. Consider the following when applied to the same classes

    T? tq = null;
    S? sq = tq;

    For this the compilation will go through as ususual but the convertion function will not be called and sq will be null. This is called null propagating in which the null source is directly converted into null target without going through the underlying conversion function. However, the conversion function needs to exist so that the compiler can verify that the conversion is valid (even though it does not call it). In our conversion function we create a new S irrespective of the value of T. So if our function was called, sq would have been non-null which is not the case...

    Lifted Operators

    Lifted operators allow predefined and user-defined operators (overloaded-operators) that work for non-nullable types to be used for their nullable forms as well. Consider the code below

    struct S

    {

    public int val;

    public S(int val)
    {

    this.val = val;

    }

     

    public static S operator +(S s1, S s2)

    {

    Console.WriteLine("+ operator called");

    return new S(s1.val + s2.val);

    }

    }

    // user-defined operators

    S? sq1 = new S(5);

    S? sq2 = new S(6);

    S? resq = sq1 + sq2; // resq will be 11

    resq = sq1 + null; // resq will be null

     

    // pre-defined operators

    int i = 5;

    int? j = 6;

    int? k = j + i; // 11

    int? q = i + null; // null

    In the above code even though the + operator is overloaded for S it also works for S?. Even here null propagation takes place and for resq = sq1 + null; the overloaded operator function is not called as one of the sources is null.

    For the expression S? resq = sq1 + sq2; the code that is generated is something like

    S? resq = (sq1.HasValue && sq2.HasValue) ? (sq1.Value + sq2.Value) : (S?)null;

    Equality operator

    This is the one I hit in my previous blog. The == and != operators have been lifted so that it allows one operand to be a value of a nullable type and the other to be the null literal. So both of the following expressions are valid

    int i = 5;

    if (i == null)

    Console.WriteLine("null");

    if (5 == null)

    Console.WriteLine("null");

    However if you want to get the following to work you need overload the == and != (and Equals) of the type S

    S s = new S();

    // compile error is == and != is not overloaded

    if (s == null) Console.WriteLine("null");

  • I know the answer (it's 42)

    Scheme of things

    • 1 Comments

    Unfortunately I did not attend MIT, and Scheme was not taught to us as one of the first languages :) . Our college used Prolog for similar purpose and I learned scheme much later. When I first started out what intrigued me most was that its one of the oldest launguages around and was still holding ground. It was developed in 1975 a year before I was born and in the field of computing things seldom stick for so long.

    After taking a brief look into the syntax I figured out this is not one of those languages where you try out "Hello world" first. I brought up the DrScheme IDE and tried out (/ 22 7) which is supposed to print out 22 divided by 7. I was surprised that to get back 3 1/7 and not something like 3.1428.

    The results of the next attempt was even for interesting. I tried out (% 22 7). This was a typo as there is no % operator in Scheme. The Scheme interpreter actually displayed the imageof a bug to indicate there was a bug in the code I typed. Whenever I get a VSTS bug assigned to me on some improper/ambiguous/funny error messages I always feel like showing that person this message :)

    DrScheme Screen shot
  • I know the answer (it's 42)

    Customers rule

    • 1 Comments

    I develop commercial software which is critical for our customers' success. In this effort we always take decision in favor of the customer. The customer rules!!!  Many times the decisions are not of great liking to the developers and we get into heated arguments with the PMs and leads arguing that we should do this feature or we should use that technology. Sometimes we become over-passionate about fixing some bugs which gets reproed in arcane situations. The PM's generally know more as these are the folks who do all the research on customer requirements, usage scenarios and they are right most of the times.

    But this does not mean that the developers are wrong. I was greatly inspired by the following piece from SICP

    "I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more."

    Alan J. Perlis (April 1, 1922-February 7, 1990)

    So there exists no monarchy is software development, its democracy and customer's rule as much as fun does. So lets get going and have all the fun we can afford......

  • I know the answer (it's 42)

    We just got jolted

    • 1 Comments

    I'm sure the world already knows, but still there's nothing wrong in saying it over and over again. The results of the 2006 Jolt award is out and we've won in the Development Environment category. Check out Rob Caron's post on this.

    If I ever got the chance to go on stage to recieve an award I'd do it exactly in Oscar style and thank Douglas Adams the person who taught me the answer to life, Universe and everything.

  • I know the answer (it's 42)

    Team Foundation Server is released

    • 1 Comments

    Its hard to express in a blog the feeling of seeing the Earth shattering product I was working on for about 2 years getting released. Its official now Team Foundation Server has shipped.  However the bang was kind of diluted as the news went out a bit earlier with the posts here and here. Unfortunately we are ahead in Time Zone and its already Saturday morning here. So our celebrations have to wait till Monday morning.

    This is the 4th product I'll be shipping in my career and the 1st from Microsoft. Everytime its an unique feeling and I keep going back to the site to see the anouncement and get amazed as I see the sales figures and get humbled by the fact that such a large user base is going to use the product.

  • I know the answer (it's 42)

    command line tool syntax

    • 1 Comments
    Command line interface (CUI) designs for many of the tools found with VS or in Windows were to include a bunch of individual commands or exe with options or flags.

    To get a directory listing: dir <options> as in dir c:\temp /w
    To create a directory: md c:\temp\foo
    To delete a directory: rd /s c:\temp\foo

    So even though all the tasks pertain to directory or path handling , you need to know three command to do the task. This design is slowly changing to the format of command <action> [</options:attributes>]

    For example if we change the above commands to this format with the common command called dir, we will be getting
    To get a directory listing: DIR list c:\temp /w
    To create a directory: DIR  make c:\temp\foo
    To delete a directory: DIR rem c:\temp\foo /s

    So effectively user learning is reduced. One can argue that he still needs to remember the names of the actions. But in the previous case he needs to remember rd, md, dir. Now he knows everything to do with path handling is to be done with DIR. So he can run DIR /? to get the list of actions and then do a DIR list /? to know the options for listing. The other advantage is namespace pollution in terms of the names of the executables also reduces.

    This new format has also been adopted in the VS as in the source control tool. So to get the listing of all workspaces on MyServer you  run the command
    h.exe workspaces /s:MyServer
    To create a new workspace you run the command
    h.exe workspace /new MySpace /s:abhinab-test
    I guess going forward we will see more and more of the standard OS commands also taking up this format. A very common example is the NET command

  • I know the answer (it's 42)

    All new MSN blog

    • 1 Comments

    With all those blog servers floating around I was waiting for MS to do something about it, and voila there are here with http://spaces.msn.com . Its free provides all that other blog servers do and more. MS has made it a habit to wait and watch a technology to grow and mature, then take it up and make it reach new heights :)

    Just thought I'll copy/paste the feature list I got through an internal mail

    MSN Spaces Enables Rich Self-Expression

    MSN Spaces enables consumers to easily share things with the people they care about in a format that can be easily customized. People can start a Space with just a few clicks, and then personalize it to reflect their moods, likes and dislikes:

    ·         Rich layout. Fifteen custom backgrounds and five layout template choices allow consumers to customize their MSN Spaces quickly.

    ·         Web logs. The MSN Spaces blogging tool allows people to publish and maintain online personal journals and enables them to link to photos and other Web sites.

    ·         Photo albums. Consumers can upload up to 10 MB of photos (250 images after compression) to their Spaces sites and display them to others in slide shows.

    ·         E-mail uploads. Consumers can upload photos or blog postings to their Spaces from virtually any e-mail service or e-mail-enabled mobile device.

    ·         Music favorites and lists. Consumers can create and manage lists of information that is important to them, such as their favorite music, books or travel destinations. Consumers can easily share playlists through their Space with Microsoft® Windows Media® technologies. With just two clicks, people can sample or purchase a song on someone’s playlist through MSN Music.*

     

    MSN Spaces Helps Users Connect With Others

    MSN Spaces is designed to help people express themselves online while better connecting them with their friends, family and other contacts:

    • Contact Cards. When a person clicks on a Contact Card in a MSN Messenger or Hotmail® Contact list, the card pops up and gives a sneak peek at that contact’s Space – from its look and feel to the person’s most recent postings. The Contact Card includes links to the Space and those entries for easy access.
    • Gleaming. When a Spaces site is updated or content is added, the MSN Messenger Contact icon of the Space’s owner will light up, making it easy for friends and family to know when there have been changes. This facilitates more visits to a Space, faster responses to new postings and closer bonds between Space owners and their contacts.
    • RSS. MSN Spaces also supports RSS 2.0, so consumers can publish their Space to others by way of RSS viewers and aggregators, including My MSN, scheduled to come soon. This is another way to ensure that the people who matter to a user can stay up to date on his or her Space.

     

    MSN Spaces Offers Protection and Control

    MSN Spaces is designed to give consumers control over how they share their Space information and who can access it:

    • Permissions. Consumers have three permission control settings on their MSN Spaces site, enabling them to decide just how widely they want to share their content:

             Public: Viewable by anyone

             Contacts Only: Viewable only by their MSN Messenger contacts

             Private: Viewable only by contacts whose e-mail addresses are manually entered by the MSN Spaces author or selected from an MSN Contact list

    • Controls. MSN Spaces gives the consumer control over how others interact with his or her Space. MSN Spaces includes settings that give each person power over who views his or her Space and how people can interact, read and comment on the Space. This includes the ability to set up the Space so people can read but not comment.
    • Statistics. Consumers will be able to track visitor statistics on their Spaces site, so they will know how many people are visiting as well as other detailed information
  • I know the answer (it's 42)

    Shooting star

    • 1 Comments

    Yesterday night when we (me, Ankur and Hemant) were going out to dinner from office (Microsoft India Campus), we saw a meteor shooting past us in the sky. It was huge and almost looked like some firework except that it was coming downwards. I had never seen a larger shooting star and nither had the others. I was big enough and close enough for atleast the ashes to fall on earth. Unfortunately, there were no report of it in the news papers, I guess we should have reported it in the first place.

    The worst part is that we figured out that we've been playing Halo a bit too much 'cause Ankur said that he thought it looked like a shot from the Rocket launcher.

  • I know the answer (it's 42)

    Build Type creation and Drop Location

    • 1 Comments

    One of the most common issues everyone is running into with Team Build is configuring the Drop Location.

    All builds that happen through Team Build are dropped (bits are copied) to this location. Drop location is entered in the Location page of the Build Type wizard. This is essentially a shared folder on the network and needs to be available in UNC format as in \\server\share. However most users enter a path in the wizard and then any of the following three things happen

    1.      They forget to share the folder out
    Result: First build fails

    2.      The folder is shared out but adequate permissions are not given on it
    Result: First build fails

    3.      The folder gets unshared at some point of time
    Result: Suddenly builds start failing after that

    A common question is raised that both the first and second reasons of failure are a pre-requisite to starting a build, why doesn’t the Build Type wizard verify that the share exists. We could have done this but there are a couple of reasons we do not.

    Firstly it could be a common scenario that the administrator is first setting up couple of Build Types and will then go and share those folders. So failing would simply hinder this process. However, this is not a very good excuse because we could have at least gone ahead verified the share and then given warnings stating that the share does not exist and the admin should share them with the correct permissions.

    The main reason for not doing this verification is that scenario 2 is not easily verifiable. To undertand this let’s consider the permission required on the shared folder

    1.      The service account under which the Team Build Service is running on the  Build Machine needs write permission on this folder

    2.      Other users need to have read permission on this folder so that they get to see build logs and the build itself

    On the client where the Build Type is getting created through the wizard there is no information regarding the service account on the Build Machine so we cannot verify 1. This is because the admin while installing the BM could have chosen any valid account to run the service and can give explicitly and exclusive write permission to this account on the share. Moreover, user can change the Build Machine while firing the build and the service account on the new Build Machine might be a different account and that might not have permissions.

    On OS’s like WinXP in addition to the sharing permission you can go to the security tab on the folders properties and apply a lot of permissions which are not accessible over the network but would make the build to fail. Take for example in share tab you give Full control to everyone and in the security for that folder you explicitly deny create folder permission. So even though our verification succeeds build will fail.

    Verifying 2 does not add any value if we cannot verify 1.

    Its not that we cannot verify drop location, what I tried to highlight above is that it is non-trivial. Many users think that the Wizard should just try to see if the share exists and then create and delete a file on the share to ensure it is writable. However for the reasons mentioned above this approach would just not work.

     

  • I know the answer (it's 42)

    Team Foundation Server tool dump workspace details

    • 1 Comments
    Bangalore airport

    I juggle around with a lot of workspaces. The reason is .NET Compact Framework is consumed in a whole bunch of things like Windows Mobile, Xbox, Zune, Nokia and most of them are on different source branches. On top of this active feature work happens in feature branches and there are other service branches to frequently peek into.

    So the net effect is I need to sometime go to different folders and see what it's source control workspace mapping is or I need to dump details of workspaces on other computers and see if I can use that workspace as a template to create a new workspace.

    The thing I hate here is to run cd to that folder and do a tf workspace to bring up the GUI and then dismiss the UI. I don't like GUI when things can be done equally well on the console. So I quickly hacked up a tool that dumps workspace details onto the console, something as below

    d:\>workspace.exe NETCF\F01
    Name:      ABHINAB2_S60
    Server:    TfsServer01
    Owner:     Abhinaba
    Computer:  ABHINAB2
    
    Comment:
    
    Working folders:
    
    Active   $/NetCF/F01/tools     d:\NETCF\F01\tools
    Active   $/NetCF/F01/source    d:\NETCF\F01\source
    
    
    

    -

    This tool can be used either to see the mapping of a folder or given a workspace name and owner dump it details. It uses the exact same format as show in the tf workspace UI.

    Source

    The source and a build binary is linked below. It is a single source file (Program.cs) and you should be able to pull it into any version of Visual Studio and even build it from the command line using CSC

    1. Source
    2. Binary

    Using the tool

    Build it or use the pre-built binary and edit the .config file to point it to your TFS server and you are all set to go.
  • I know the answer (it's 42)

    Designer for my path finding boards

    • 1 Comments

    I'm writing a small application (or rather a screen saver) that animates and demonstrates A* search algorithm. The idea is simple. On screen you see a start and end point and some random obstacles in between them. Then you see animation on how A* algorithm is used to navigate around the board to find a path (close to the shortest possible) between the two.

    All of this is fairly standard. However, I got hit by a simple issue. I wanted to have the ability to design this board visually and also let my potential million users do the same. Obviously I don't have time to code up a designer and hence choose the all time manager's favorite technique. Re-use :)

    So the final solution I took was to use Microsoft Office Excel as the WYSIWYG editor. I created a xlsx file with the following conditional formatting which colors cells based on the value of the cells.

    Excel Conditional Formatting screen shot for blog

    So in this case

    1. w = Wall marking the end of the table
    2. b = blocks/bricks/obstacle
    3. s = start
    4. e = end

    Using this I can easily design the board. The designer in action looks as follows

    Excel Designer For A* blog screenshot

    Since the excel sheet has conditional formatting the user just types in s, e, b, w in the cells and they all light up visually. At the end he/she just saves the file using File => Save As and uses CSV format. This saves the file shown above as

    w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w
    w,,,,,,,,,,,,,,,,,,,,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,b,,,,,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,s,,,,,,,,b,b,b,b,b,b,,,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,,b,b,b,b,,b,b,b,b,,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,b,b,b,,,,,,b,b,b,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,b,b,,,,,,,,b,b,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,b,b,,,,,,,,b,b,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,b,b,,,,,,,b,b,,,,,b,,,,,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,b,b,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,b,b,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,b,b,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,b,b,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,b,,,,b,,,,,,,,,,,e,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,b,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,,,,,b,,,,,,,,,,,,,,w
    w,,,,,,,,,,,,,,,,,,,,,,,,,,,b,,,,,,,,,,,,,,w
    w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w,w

    As you see the format is simply a row per line and every column separated by a comma. My simulator reads this file and renders using whatever renderer is configured (console or WPF).

    More about the A* simulator to come soon...

  • I know the answer (it's 42)

    A* Pathfinding algorithm animation screen saver

    • 1 Comments

    I'm trying to learn WPF and IMO it is not a simple task. Previously whenever I upgraded my UI technology knowledge it had been easy as it build on a lot of pre-existing concepts. However, WPF is more of a disruptive change.

    I decided to write some simple fun application in the effort to learn WPF. Since I cannot write a BabySmash application as Scott Hanselman has already done a awesome job out of it, I decided to code up a simulation of A* path finding algorithm and push it out as a screen saver. The final product looks as follows.

    AStar

    What it does is that it shows a source, a destination with blockages (wall, mountain?) in between and then uses A* algorithm to find a path in between them. This is the same kind of algorithm that is used in say games like Age of the Empires as workers move around collecting wood and other resources. The algorithm is documented here.

    Features

    1. It supports plugging in your own scenes with help of the awesome screen/board designer I blogged about
    2. Comes with a WPF and a console client to show the animation
    3. Algorithm can be played with easily to change or tweak it.
    4. Shows full animation including start, end, obstacle, closed cells, current path being probed and the final path
    5. Multi-screen support. Each screen shows a different board being solved.

    Limitations:

    Obviously this was more of a quick dirty hobby project and there remains a ton to work on. E.g.

    1. Screen saver preview doesn't work.
    2. Setting dialog is a sham.
    3. The boards do not flip for vertically aligned screens
    4. The XAML data binding is primitive and needs some work
    5. The path can choose diagonally across cell even if it seems to cross over diagonal wall of obstacle.
    6. Mouse move alone doesn't shut down the screen saver. You need to hit a
    7. Many more :)

    Download:

    Download the final binaries from here. Unzip to a folder, right click on the *.scr and choose Install

    Download sources (including VS 2008 sln) from here.

    Enjoy.

  • I know the answer (it's 42)

    Tail call optimization

    • 1 Comments
    wall

    I had posted about tail call and how .NET handles it before. However there was some email exchanges and confusion on internal DLs around it and so I thought I'd try to elaborate more on how .NET goes about handling tail calls

    Let’s try to break this down a bit.

    a) A piece of C# code contains tail recursion .

    static void CountDown(int num)
    {
    Console.WriteLine("{0} ", num);
    if (num > 0)
    CountDown(--num);
    }

    b) The C# compiler does not optimize this and generates a normal recursive call in IL

     IL_000c:  ...
    IL_000d:  ...
    IL_000e:  sub
    IL_000f:  dup
    IL_0010:  starg.s num
    IL_0012:  call void TailRecursion.Program::CountDown(int32)

    c) The Jitter on seeing this call doesn’t optimize it in any way and just inserts a normal call instruction for the platform it targets (call for x86)

    However, if any compiler is smart enough to add the tail. recursive IL statement then things change.

    a) Scheme code

    (define (CountDown n)
        (if (= n 0)
             n
          (CountDown (- n 1))))

    b) Hypothetical IronScheme compiler will generate (note for scheme it has to do the optimization)

     IL_000c:  ...
    IL_000d:  ...
    IL_000e:  sub
      tail.
    IL_0023:  call void TailRecursion.Program::CountDown(int32)
    IL_0029:  ret

    c) Based on which JIT you are using and various other scenarios the JIT now may honour the tail. IL instruction and optimize this with a jmp when generating machine instruction

    Please note the may in the very last point and refer to here for some instances where the optimization still might not take place…

  • I know the answer (it's 42)

    String equality

    • 1 Comments
    Flowers At the Botanical park

    akutz has one of the most detailed post on string interning and equality comparison performance metrics I have ever seen. Head over to the post here

    I loved his conclusion which is the crux of the whole story.

    "In conclusion, the String class’s static Equals method is the most efficient way to compare two string literals and the String class’s instance Equals method is the most efficient way to compare two runtime strings. The kicker is that there must be 10^5 (100,000) string comparisons taking place before one method starts becoming more efficient than the next. Until then, use whichever method floats your boat."

  • I know the answer (it's 42)

    Model, View, Controller

    • 1 Comments
    Chocs

    These days the whole world is abuzz with the Model, View, Controller (MVC) architecture. This is not something new and is known by computer scientists for close to 30 years. I guess the new found popularity is due to the fact that this has heavy application is web development and lot of main-stream web development platform are putting in support for this. Ruby-on-rails and ASP.NET MVC are classic examples.

    Coding horror has a nice post on this topic. I liked the following statement it made

    "Skinnability cuts to the very heart of the MVC pattern. If your app isn't "skinnable", that means you've probably gotten your model's chocolate in your view's peanut butter, quite by accident."

    I actually use a very similar concept. The moment I see an application's architecture (be it an interview candidate or a friend showing off something) I ask the question "Can you write a console version of this easily?". If the answer is no or it needs a re-design it means that the separation of model, view and controller is not correct. You are going to have a nightmare if you write and maintain that software.

  • I know the answer (it's 42)

    Time for a change

    • 1 Comments

    I've been working for some time in Visual Studio Team System (first on the TFS server and then on the testing infrastructure). I was looking for a change and then I happened to talk with the GPM of the .NET COMPACT FRAMEWORK team. The following explains in brief what followed...

    NetCF

    ... and so I landed a job in the .NETCF Garbage Collector and other parts of the execution engine. I'm sure I'll be super busy as the team is heads down into getting Silver Light onto mobile devices and going cross-plat (I guess most folks have heard about SL on Symbian/Nokia).

    What this means is that I can (or rather I have to) muck more with .NET (both desktop and CF) without any guilt and can claim that blogging about them is actually a part of my job. So what this means for this blog is that there'll be more hardcore stuff about .NET and an additional Tag called NETCF when I post specifically about it.

    In case you are in India and want to work in a Kick-ass team delivering one of the most key technologies for the industry then drop me a line at abhinaba.basu @ you know where. Bragging rights will come for free when you point to all those cool WinMobile/S60/XBox/Zune devices and claim how you coded .NET for it....

    Wish me luck...

  • Page 11 of 15 (374 items) «910111213»