Feeds:
Posts
Comments

Archive for the ‘General’ Category

VS 2010 Beta 1 includes some C# 4.0 features and though I have been reading about some of the new stuff on various blogs and forums, I only got to play with it very recently. Put simply, the dynamic keyword allows you to declare and use types that are not type-checked during compilation. They are resolved at runtime using the DLR.

Here’s a simple class that has a dynamic field, a method that has a dynamic argument, and a dynamic property:

class Dynamic
{
    private dynamic data;

    public void SetData(dynamic data)
    {
        this.data = data;
    }

    public dynamic MetaData { get; set; }

    public void Display()
    {
        Console.WriteLine("{0} {1}, {2} {3}",
            data, data.GetType(), MetaData, MetaData.GetType());
    }
}

Using the class is quite straightforward:

private void Foo()
{
    var d = new Dynamic();
    d.MetaData = 100; <-- Int32
    d.SetData(99); <-- Int32
    d.Display();
    d.MetaData = 100f; <-- Single
    d.SetData("hello"); <-- String
    d.Display();
}

Notice how I keep using different types at runtime for calling the same methods and properties. If you look at the IL via Reflector, you’ll see that dynamic types are internally treated as System.Object. Intellisense within VS 2010 will also give you System.Object members since that’s what they are guaranteed to have.

There are three dynamic calls in the Display method. A nested static class is generated inside the Dynamic class, and it will have one static CallSite<> field per dynamic call. In this case, there are three such fields. Whenever the dynamic calls are made, it’s these DLR call sites that come into play. An extremely simplified explanation of what happens is that the DLR internally uses reflection to figure out what type the dynamic object is at runtime. There is also caching done so that type-matching (or mapping) is not repeated unnecessarily. Of course the implementation is quite complex and you could probably spend weeks going through the code in Reflector. Note that if you make dynamic calls in a different method, there will be another static class generated – so it seems to be one inner class per method.

Consider the following simple method:

public void Test()
{
    var type = data.GetType();
}

A class will be generated similar to the following (I’ve made this easy to read – so this is not an accurate representation of the generated code):

[CompilerGenerated]
private static class SiteContainerForTest
{
    public static CallSite<FUNC<CALLSITE, object, object>> callSiteGetType;
}

And the method Test gets compiled into:

public void Test()
{
    if (SiteContainerForTest.callSiteGetType == null)
    {
        SiteContainerForTest.callSiteGetType = CallSite<Func<CallSite, object, object>>.Create(
            new CSharpInvokeMemberBinder(
                CSharpCallFlags.None,
                "GetType", <-- the name of the dynamic member
                typeof(Dynamic),
                null,
                new CSharpArgumentInfo[] { new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }
            )
        );
    }

    object type = SiteContainerForTest.callSiteGetType.Target(
      SiteContainerForTest.callSiteGetType,
      this.data <-- the dynamic object
    );
}

The call site’s Target will be of type Func<CallSite, object, object>, and the return type is object (because at compile time that’s what the local variable type was defined as, since we don’t know what type it would be at that time). It’s at this point that dynamic binding is done. Fortunately for us, it’s all done behind the scenes and we are protected from having to write all this code ourselves. Assuming data is an Int32 at this time, Int32‘s GetType is called (and since it doesn’t have one, Object‘s GetType is invoked).

You can also use dynamic types locally (a site container class is generated for the containing method) :

dynamic d = 1;
string s = d.ToString();
Console.WriteLine(s);

d = "dynamic data";
Console.WriteLine(d.Length);

d = 33;

try
{
    int len = d.Length; <-- Invalid dynamic call on an Int32 object
}
catch (RuntimeBinderException ex)
{
    Console.WriteLine(ex.Message);
}

When I try to use the non-existent Length property on an Int32 value, the runtime will throw a RuntimeBinderException. And it even gives a very useful error message : ‘int’ does not contain a definition for ‘Length’.

Overall, one of the most celebrated uses of dynamic types is supposed to be for Office interop. You no longer have to do endless casts and mid-level variables for debugging. It’s just as easy as using classic VBScript. At this point, unless you want to interop with Word or Excel, I can’t think of too many scenarios where this will come in handy. Maybe someone who’s more functionally oriented than I am can think of some common scenarios.

Read Full Post »

Here’s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.

Here’s a simple hack to do this :

private static void FlushKeyboard()
{
    while (Console.In.Peek() != -1)
        Console.In.Read();
}

Now you can use it as follows :

char x = (char)Console.Read();
FlushKeyboard();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.

Read Full Post »

Last week I attended the 2009 MVP Summit held at Redmond/Seattle and I’ve got to say that I had two rather peculiar experiences whilst there. The first incident was on the way to Seattle – it snowed in Atlanta of all things to happen and this resulted in dozens of cancelled and delayed flights. My flight was scheduled for a 2:30 PM departure and after a 3 1/2 hour delay where they pushed back the boarding time every 30 minutes, we finally boarded at 6 PM. Once we got in the aircraft we waited on the tarmac for another 3 1/2 hours more before take-off as we had to wait in line behind dozens of other flights for de-icing. I am still not sure why they couldn’t have us wait outside (at the gate) and let us board after the de-icing. The air was pretty stuffy inside because the air-conditioners seemed to be at half power. And after take-off they ran out of food when it was my turn to order – so yeah, that didn’t help either. It was one of the nastiest experiences I’ve had in an airport/flight in my entire life – one that I hope will not be repeated in future.

The second incident occurred on Tuesday night (or rather Wednesday morning). I was at the Grand Hyatt (17th floor) and had gone to bed close to 1 AM as I had gone for a late dinner/chat with an old friend. Around 4:30 AM or so this really loud siren came on and an even louder announcement was repeated instructing all occupants to move to the nearest staircase and to descend to the first floor immediately. It was also announced that the elevators were shut down. I wasn’t sure if it was a fire-emergency or some temporary air-pollution – in any case, I put on my shoes, picked up my laptop and climbed down the 17 set of stairs (16 maybe if they didn’t have a 13th floor, didn’t feel like counting then). I found a few dozen equally incredulous folks downstairs wondering what the heck had just happened. We watched the fire-trucks come and the firemen go up – and all this time we were all out on the streets. A few minutes later, they said everything was alright and said we could go back up to our rooms. There was a further wait of 20 minutes or so as we waited for an engineer to come down and reset the elevator system – and I didn’t want to climb up the 17 floors, not with my laptop. The worst part of the incident was when we found out that some dim-witted inconsiderate jerk had been smoking in a non-smoking floor which was what set off the fire-alarm. So they had to evacuate that floor as well as the floors directly above and beneath it.

The nice thing about the trip was that the summit was pretty good, we had some interesting technical sessions, the food was great, and it was good to catch up with some fellow MVPs and Microsoft buddies – some of whom I’ve only met at Microsoft summits and never outside Redmond.

Read Full Post »

In my previous blog entry, I had recommended storing enums using their string representations when writing them to a database. There’s a caveat there though – the enum names should be guaranteed to remain stable, because if you change the name of an enum member, it breaks the database. For my specific scenario I ended up using enum values with explicit short values, so if the names ever change in future the short values remain the same and thus the database remains consistent.

There are other approaches to solving this too. Reader Arnaud Weil suggests having a table for each enum and the enum id from this table is used to refer to the enums elsewhere in the database. The guys at my current project have a specialized class that emulates enums and also allows the ability to associate meta-information to each enum value (like an image or a description). A third approach would be to use custom attributes and a type descriptor that’d extract the meta-information from an enum type. The old adage is true – there are many ways to skin a cat.

Read Full Post »

Okay I’ve been called many things in my life, but this was a first for sure. My wife ordered pizza and I went to pick it up on my way home from work. She gave my name as Nish, and she spelled out the first letter as “N for Neptune”. I’ve heard her use “S for Saturn” too. Though they are both planets from her perspective I usually tell her that for a lot of folks, one of those is a car and the other’s an odd word they’ve never heard before. Anyway the guy on the phone wrote it down as Neptune. So when I went to pick it up I was addressed as Neptune, and though I was surprised I just thought I had misheard him. Then I saw my name on the receipt and there it was – “Neptune”. I didn’t bother correcting him of course, instead I put on my best “Lord of the sea” look and walked out with a godly swagger.

Read Full Post »

I am a bit fixated on how people spell my name – for those of you who don’t know, it’s “Nishant” – 7 unrepeated letters that even a 4-year old should find it trivial to remember. Unfortunately enough, many Indian names that end in “nt” are sometimes pronounced and spelled as “nth”, so there’s a common misspelling of my name where there’s an “h” suffixed to the “ant”. Westerners never spell my name wrong, they always get it right. It’s the Indian folks who sometimes think they know what’s best and misspell my name with the trailing “h”. And sometimes it happens on my own blog. People address me using the misspelling when leaving a comment or sending me an email, and when you consider that a majority of these communications are requests for help, you’d think they’d have the basic courtesy to at least get my name correct. Oh well, at least nobody’s misspelled “Nish” so far.

Read Full Post »

A singular solicitor at Target

Smitha and I were shopping at Target this past weekend, and as is the norm these days I was pushing little Rohan around in his stroller while Smitha went through the aisles picking, unpicking and then re-picking various items that seized her interest. I was mostly bored and lost in my thoughts when I was brusquely interrupted by an unwarrantedly loud “Are you from India?” from a formally dressed middle-aged Indian gentleman. I nodded my head in affirmation as curiously enough I did happen to be from India, though for the life of me I cannot figure out what gave that away!

The next few minutes he proceeded to converse with me about how lots of Indians were in the US these days on H1 Visas, how a lot of them went on to get Green Cards, how he recently moved to Atlanta from Arkansas, how he’d be delighted to introduce his wife to me (apparently she was elsewhere in the store at that time) and a few other topics that I don’t remember right now. All I remember thinking was how to get out of this conversation, especially since I had a sneaking suspicion that this guy was trying to sell some Amway like pyramid scheme on me. Fortunately Smitha called for me at that moment and I used this opportunity to say goodbye to him, but before I could do so he handed me his business card and asked me for mine. I did not have one with me and when I said that to him, he quickly produced a piece of paper and a pen out of nowhere – honestly, I didn’t see where he took it out from, he was like a conjurer – conjuring pen and paper out of thin air. With heavy misgivings I wrote my first name and phone number on his magically produced piece of paper and gave it to him and we parted.

Needless to say, Smitha gave me a quick firing-down for giving my number to a stranger, but fortunately enough she was soon distracted by a shelf containing the oddest looking ladies’ purses I have seen in a while. Normally this would have worried me since I definitely didn’t want her carrying around one of those revoltingly unattractive purses, but at that point I was just relieved to get out of her firing line. Just then I noticed a middle aged Indian woman conversing with a young, pretty and trendily dressed Indian girl (looked like she was in her early 20s). Now I don’t want to come across as someone who eavesdrops when 2 strange women are conversing in front of me, but I couldn’t help catch a few odd words here and there. It didn’t take me too long to realize that this woman was basically dishing out the same stuff to this girl that the strange guy had earlier dished out to me, and in a minute or so I saw the hapless girl hand over her phone numbers to this lady (I distinctly remember her explicitly specifying her land, work and cell numbers). I was certain that this middle aged lady was the earlier gentleman’s spouse and at that point it became increasingly evident that they were soliciting phone numbers from Indian looking folks.

My suspicions were confirmed a little later when we left Target with Smitha’s shopping picks for the day. The middle aged couple were walking together towards the parking lot, and most markedly they did not have a single item with them (forget a bag). They had basically spent close to an hour inside Target seeking out potential Indian victims (who they hoped would be new enough to the country) and collecting their information. I fully expect to receive a phone call this week inviting me to a gathering of some sort where this gathering would most definitely be a sales talk for some crappy pyramid scheme. Obviously I would get out of it with a clever excuse but I really do feel sorry for the pretty young girl who did seem naïve enough to fall into this trap. Oh well, I suppose she will eventually learn that strange Indian looking people approaching you in the middle of a store and asking you if you are from India are to be treated with the deepest mistrust and skepticism possible. Oh, and we are going to Target this evening – Smitha wants to return a hand bag that she took half an hour to select, apparently she did not like it when she looked at it this morning and so wants a new one. Sigh!

Read Full Post »

I’ve had some very interesting experiences when calling customer support, but last week a call to Comcast resulted in a whole new experience for me. After being on hold for about 5 minutes, listening to some of the most awful music you could possibly round up, a girl picks up. She greets me and then tells me apologetically (I hope) that her PC has got very slow and so she’s going to reboot it and will I please wait? For a profound few seconds, I stood there in incredulous shock. Though to be fair to her, she did come back after 3-4 minutes (pretty slow machine if it takes that long to boot) and she did help me out, and I somehow managed to resist making some weird joke asking her if she’d mind if I rebooted my PC as mine was getting a little slow too.

Read Full Post »

Really getting design patterns

The CEO of my first company (who was an old time assembler/C programmer even before I was born) liked to periodically quote, “you either get pointers or you don’t”. I believe I’ve seen variants of that on the web – but I just did some Googling and could not find out who made the original quote (if there’s indeed someone who this is attributed to). Anyway I am not really talking about pointers here – I am talking about design patterns. The first time I read the GOF’s Design Patterns, I remember thinking that some of those patterns did look familiar and that I’ve used them without knowing what they were formally called. But I also remember thinking that some of the structural and behavioral patterns described in the book didn’t seem particularly useful – in fact I thought that it was just a big pile of complicated sounding text. But since the rest of the smart programming world accepted these patterns I remember worriedly pondering over whether I was one of those unfortunates who simply didn’t “get” design patterns.

Anyway I have re-read the book a few times now, some parts of it several times, some parts of it maybe a couple of times, and with each iteration I ended up with a “hey that makes sense now” feeling. I spent the last few days of this Christmas/New Year holiday re-reading the entire book and this was probably my best experience so far. I instinctively recognized familiar patterns that I had seen in use in MFC and the .NET class library, and I also began to understand certain patterns better (even those that I was previously sure I understood). I don’t think I’ve fully got it even now, but I have concluded that the key to getting design patterns is probably to apply them in many different scenarios and perhaps occasionally coming back to the book and giving it a quick read (1-2 hours should be good enough to scan the entire book and refresh your memory). And though design patterns is a subject that has been covered once too often in various blogs and articles I may occasionally blog about my attempts at applying known patterns to specific problems. That I guess would be my new year resolution (or at least one of a dozen others).

Read Full Post »

I started an installation of Visual studio Orcas beta 1 last night just before I went to sleep and also set the alarm for 3 AM so I could wake up and hit [Next] when it prompts me to install the documentation. Well guess what? I woke up and found that Vista had rebooted and there was a nice balloon tip on the lower right of my screen telling me some updates got installed and so it rebooted. Holy crap! There was a freaking installation going on, damnit! Has this crap happened to anyone else too?

The good thing is I restarted the installation and decided to stay up for 30 minutes to make sure it was all good. That turned out to be a good move because the setup paused and asked me to kill the machine debug manager (no idea why that was running) which I did. I went to sleep and woke up a while ago to find the installation complete. Apparently documentation got auto-installed and thus I didn’t have to click [Next] for that. But I still cannot believe that the OS was stupid enough to do a reboot while an installation was running – how screwed up an idea is that anyway! :grrr:

Read Full Post »

Older Posts »

Follow

Get every new post delivered to your Inbox.