I know the answer (it's 42)

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

January, 2006

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

    Neighbourhood super-hero LINQ comes to the rescue

    • 4 Comments

    I was just reading Mike Stall's blog Fun with yield, generics, foreach. He discusses using enumeration  with yield and generics. The example he uses is a heterogenous array object[] list = new object[] {1,2, "abc", 5f, "def" }; and he needs to print all the strings in it. The simple solution in C#1.x is

    object [] list = new Object[] { 1, 2, "abhinaba", 5f, "basu" };

    foreach (Object o in list)

    {

    string s = o as string;

    if (s == null) continue;

    Console.WriteLine(s);

    }

    Initially I was kind of opposed to the whole idea of LINQ. I think this is the mental adoption blocker which everyone talks about. As time is passing and I am being forced to use C#2.0 (we have not yet moved to 3.0) everyday I get the urge to use LINQ as it solves many problem so elegantly. If we use C#3.0 we can do this as follows

    object[] list = { 1, 2, "abhinaba", 5f, "basu" };

     

    foreach( var v in list.Where(x => x is string))

    {

    Console.WriteLine(v);

    }

    This code uses some of the new C#3.0 features. Where is a System.Query provided extension method which you can add to any collection. x => x is string is a lambda expression which is passed as the predicate to the extension method. Here type parameters of the predicate is inferred from the lambda expression.

    After writing this code I just felt happy. I think the greatest achievement for any language is that it makes programmers who use it happy, what more can you ask for?

    <Edit : Some additions>

    I asked what more you can ask for and Theme over on the original Mike's post suggested that the foreach can be further reduced. I took the hint and cooked up the following

    public delegate void Action<T>(T val);

    static class MyExtensions

    {

    public static void ForEach<T>(this IEnumerable<T> list,
    Action<T> act)

    {

    foreach (T t in list)

    act(t);

    }

    }

     

    object[] list = { 1, 2, "abhinaba", 5f, "basu" }; list.Where(x => x is string).ForEach(Console.WriteLine);

    So if I have the Extension method ForEach handy in some assembly/source or if I can find the equivalent in System.Query namespace then I have reduced the solution to 2 lines. Since the whole of it is generics based and Console.WriteLine have enough overloads the solution works fine with data types other than string (like int).

    I asked for more and got more. Bring on C#3.0, 2.0 is already stale and its time to replace it...

  • I know the answer (it's 42)

    typedef is good for your wrist but not for your social life

    • 17 Comments

    Sometimes, we find many of our favourite features missing in a language. The instant reaction is that we crib (yea, I do this a lot :-) ) and raise it as a short-coming of that language. Most language features are pretty simple to be implemented in a compiler and we miss the point that it could be that the language-designer deliberatly omitted that because it either does not fit in the language's general design or he considers it to be a bad programming practice.

    A classic example of this is typedef. C++ users are very familiar with it and have abused this to no end. While some uses of it could be ok, people typically go overbeoard using this. Sometime back I used the following

    typedef BOOL (WINAPI *lpfn) (HWND hWnd, COLORREF cr, 
                  BYTE bAlpha, DWORD dwFlags);
    lpfn g_pSetLayeredWindowAttributes = 
    (lpfn)GetProcAddress(hUser32, "SetLayeredWindowAttributes");

    I think this is a legitimate use where I used typedef to create a alias for a function pointer to a Win32 api. 

    The C++ world is different, there you play around with global functions, function pointers, cross-platform issues. In C++ applications its typical to see typedef or #define being used to create types like NUMBER, TCHAR to switch types based on compilation options and also for cross-platform support where you want NUMBER to be 16-bit unsigned int irrespective of the plaform. But these things make code very un-maintainable. I have spent countless hours traversing definition chains and it irritates a poor guy trying to debug a piece of code late in the evening to find out customer_list ultimately boils down to char * after 3-4 indirections. 

    I am not against typedefs, I have used it and have benefitted from other frameworks using it and its good for your wrist (less typing == less pain). But in C# it simply doesn't fit in and so C# doesn't have typedef. This is something to happy about and not a short-coming of the language. A lot of pain-points of C++ are not present in C# and hence you do not need typedefs that much.

    using != typedef

    Actually its wrong to say C# doesn't have typedef. It does have it in the form of using. But this is limited in terms of usage and functionality. You can do the following...

    using EmpList = System.Collections.Generic.List<MyNameSpace.Employee>;

    using NUMBER = System.Int32;


    namespace
    MyNameSpace

    {

    public class Employee

    {

    }


    public
    class Class1

    {

    public Class1()

    {

    EmpList empList = new EmpList();

    NUMBER num = 5;

    }

    }
    }

    So you can create alias for int and EmpList for a generic list of employees. The reason why this does not get as bad as typdefs is because of the following reasons

    1. You can have using clause only at the top of a namespace (using must precede all other namespace elements othern than extern alias declaration).
    2. using supports aliasing only classes and namespaces and not arbitrary types
    3. And most importantly aliases defined using using is visible only in that file(compilation unit). Actually the exact same thing is true for C++ as well. However in C++ you can put it in a .h file and include it in as many .cpp file you want. C# does not have the concept of including source files and so everything is just fine.

    Not having typedef is not bad

    actually its very good.

    Just because a language does not have a feature doesn't mean that it has to be bashed. In one thread I saw someone bashing C# becuase he couldn't do using NUMBER=int; globally. What I couldn't figure out is why do you want to do this? In C# int is anyway an alias for System.Int32 and for any system on which .NET is ported (Mono/Rotor project) int will be ported for you to support 32-bit signed integer and you should not be bothered with doing it yourself. If you think NUMBER gives more clarity, think twice. Wear a maintainers hat and think if you come to that code 2 years later will NUMBER look more clear or int. Even List<Employee> is much more readable than EmpList (see below).

    Some people suggest working around this limitation (???) using inheritance as follows.

    public class EmpList : 

    System.Collections.Generic.List<typedef.Employee>

    {

    }

    I think this simply doesn't scale. For example you'll need to create EmpList constructors that match those od List<T>.

     

  • 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)

    Aspect Oriented Programming using .NET

    • 22 Comments

    Some time back I wrote an article on AOP using .NET languages. It's a long post so bear with me. In case you are interested only about C# go down here

    What is AOP

    Aspect Oriented Programming or AOP is an interesting concept that can be applied to many of the programming problems we solve everyday. In our Visual Studio team system code we have a lot of web-services and remoting code that essentially does the following

    public void MyMethod(int parameter)

    {

    Trace.EnteredMethod("MyMethod", parameter);

    SecurityCheck();

    // Bunch of processing

    Trace.ExitMethod("MyMethod");

    }

    This is not just peculiar to our domain but is seen across different domains. In OO programming classes and methods are designed for performing specific operations and common/duplicate functionality are factored out into common classes. However, there are cross-cutting concerns that span accross all classes and methods, like logging and security checks. OOP only partially solves this problem by requiring users to define separate classes for logging and security checks and requiring each class/methods needing these services to call them. AOP targets and solves this problem elegantly.

    AOP divides code into base-code (code for your functionality) and a new construct called aspect. Aspect encapsulates these cross-cutting concerns using the following concepts

    • join-points: The points in the structure of base-code where the cross-cutting functionality needs to execute. This is typically when specific methods are entered or exited or properties are accessed.
    • point-cut: A logical description of join-points using some specific syntax
    • advice: additional code like logging and security check that each of these methods need to perform

    The most mature AOP language is probably AspectJ which adds AOP extensions to Java. However, for this blog, I'd stick to .NET languages like AspectDNG, Aspect# and C#.

    Language support for AOP

    AOP support has to be built in to the language and/or framework because it is based on method call interception. Whenever a methods is called the framework needs to provide a stub to call some other piece of code. Though .NET CLR has this capability, but it is intrusive as you need an object to extend from MarshalByRefObject  or ContextBoundObject to allow method-interception. This is a serious limitation because each class needs to be written so that it supports AOP. Many AOP languages or language-extensions get around this limitation by using various techniques. The techniques generally fall into two broad categories runtime or dynamic weaving, compile-time or static weaving.

    Aspect# is AOP language which uses static compile time weaving. It uses its own proxy (and not CLR's proxy) called DynamicProxy. DynamicProxy is generated compile time and works differently while proxying interfaces (generates dynamic class and delegates method calls to the target of invocation) and proxying classes (generates stub class that inherits from the target).

    Aspect# provides syntax to define point-cut and call method-interceptors or advice for them. It's done as follows 

    import YourCompany.CMS.ContentProviders in YourCompanyAssembly
    import YourCompany.CMS.Aop.Interceptors
    aspect SecurityAspect for RSSContentProvider
         include Mixins.SecurityResourceImpl in MyMixinsAssembly
    pointcut method(* MyMethod(*))
               advice(TracingInterceptor)
         end



    end
    public class TracingInterceptor : IMethodInterceptor { public object Invoke(IMethodInvocation invocation) { // Trace using information from IMethodInvocation
    // like Method, MethodInvocationTarget return invocation.Proceed(); } }

    The important bits are marked in bold. The first block is the point-cut in a Ruby like syntax which specifies all methods with the name MyMethod to be included in the join-points.  The second block is the interceptor (advice) TracingInterceptor. The TracingInterceptor is a class that has to implement the IMethodInterceptor. It can call invocation.Proceed to continue with the method invocation once it's done with the tracing. So whenever the MyMethod is called TracingInterceptor.Invoke gets called.

    Other languages like AspectDNG (.NET based AOP language-extension) accomplishes this using something called IL weaving. In this the target or base-code is coded in any language that can be compiled into MSIL like C#, VB.NET, J#. So the target code can look like

    using System;

     

    public class MyClass {

    public int ProcessString(String s, out string outStr) {

    // ...  

    }

    }

    There is no special code or any type of modification needed on the base-code as evident from above which is plain-vanilla C# code. The aspect code is written as follows which can also be C# code and needs some additional assembly reference and attribute decoration for AspectDNG to pick them up

    using DotNetGuru.AspectDNG.MetaAspects;

    using DotNetGuru.AspectDNG.Joinpoints;

    using System;

    public class AspectsSample{

    [AroundCall("* MyClass::ProcessString(*)")]

    public static object YourMethodCallInterceptor(JoinPoint jp) {

    Console.WriteLine("Code before calls to '.. MyClass.ProcessString(..)'");

    object result = jp.Proceed();

    Console.WriteLine("Code after calls to '.. MyClass.ProcessString(..)'");

    return result;

    }
    }

    Here point-cut is specified using attributes like AroundCall, AroundBody. Both the base-code and the aspect code are separately compiled into different assemblies using respective compilers like csc into Target.exe and aspect.dll. Then the aspectdng.exe tool can be used which uses reflection to reach to the attribute in the aspect code to weave call to them so that a new assembly called Target-weaved.exe is created. In target-weaved.exe AspectDNG directly puts in calls to the aspects around the target code by inserting/replacing IL code wherever required.

    There are some AOP languages like Encase which apply the aspects at run time. These languages use AOP frameworks which reads in configuration files for point-cuts and at runtime generate proxy classes that intercept calls, allows advice of the aspect to execute first and then invokes the actual target. The benefit is that there is not edit-compile cycle but it faces performance issues.

    AOP in C#

    Till now we were talking about non-mainstream languages to get AOP done. However, by doing a bit extra work we can get the same functionality in C# as well. The limitation with CLR is that it allows method interception only when the classes containing the methods inherit from MarshalByRefObject  or ContextBoundObject. When a class inheriting from ContextBoundObject is activated, the .NET interceptor comes into play. It creates a trasparent-proxy and a real-proxy. The transparent-proxy gets called for all invocation of the target. The transparent proxy serializes the call stack and passes that on to the real-proxy. The real-proxy calls the first message sink which is an object implementing the IMessageSink interface. Its the duty of this first message sink to call the next until the final sink goes and calls the actual target. In this sink chaining we can insert objects which can execute our aspect advice.

    Another limitation with C# is that there is no way in C# syntax to specify join-points. We will circumvent these two limitations by inheriting the target classes from ContextBoundObject. We'll use attributes on specific classes so that all methods and field-setters in them become included into the join-points.

    using System;

    // Include the aspect framework

    using Abhinaba.Aspect.Security;


    [
    Security()]

    public class MyClass : ContextBoundObject {

    public int ProcessString(String s, out string outStr) {

    Console.WriteLine("Inside ProcessString");

    outStr = s.ToUpper();

    return outStr.Length;

    }
    }

    Here Security is an attribute defined in our Abhinaba,Aspect.Security namespace which pulls in our support for AOP and includes the current class and all its methods in the join-points. The whole AOP framework looks as follows. All the important parts are marked in bold.

    using System;

    using System.Diagnostics;

    using System.Runtime.Remoting.Messaging;

    using System.Runtime.Remoting.Contexts;

    using System.Runtime.Remoting.Activation;

    namespace Abhinaba.Aspect.Security

    {

    internal class SecurityAspect : IMessageSink {

    internal SecurityAspect(IMessageSink next)

    {

    m_next = next;

    }

     

    private IMessageSink m_next;

    #region IMessageSink implementation

    public IMessageSink NextSink

    {

    get{return m_next;}
    }

    public IMessage SyncProcessMessage(IMessage msg)

    {

    Preprocess(msg);

    IMessage returnMethod =
    m_next.SyncProcessMessage(msg);

    return returnMethod;

    }

    public IMessageCtrl AsyncProcessMessage(IMessage msg,
    IMessageSink replySink)

    {

    throw new InvalidOperationException();

    }

    #endregion //IMessageSink implementation


    #region
    Helper methods

    private void Preprocess(IMessage msg)

    {

    // We only want to process method calls

    if (!(msg is IMethodMessage)) return;

    IMethodMessage call = msg as IMethodMessage;

    Type type = Type.GetType(call.TypeName);

    string callStr = type.Name + "." + call.MethodName;

    Console.WriteLine("Security validating : {0} for {1}",
    callStr,
    Environment.UserName);

    }

    #endregion Helpers

    }

    public class SecurityProperty : IContextProperty,
    IContributeObjectSink

    {

    #region IContributeObjectSink implementation

    public IMessageSink GetObjectSink(MarshalByRefObject o,
    IMessageSink next)

    {

    return new SecurityAspect(next);

    }

    #endregion // IContributeObjectSink implementation

    #region IContextProperty implementation

    // Implement Name, Freeze, IsNewContextOK

    #endregion //IContextProperty implementation

    }

    [AttributeUsage(AttributeTargets.Class)]

    public class SecurityAttribute : ContextAttribute

    {

    public SecurityAttribute() : base("Security") { }

    public override void GetPropertiesForNewContext(
    IConstructionCallMessage ccm)

    {

    ccm.ContextProperties.Add(new SecurityProperty());

    }

    }
    }

     

    SecurityAttribute derives from ContextAttribute and MyClass derives from ContextBoundObject, due to this even before the ctor of the class is called the framework instantiates SecurityAttribute and calls the GetPropertiesForNewContext passing it a reference to IConstructionCallMessage. SecurityAttribute creates an instance of SecurityProperty and adds it to the context. This addition makes the framework call the various IContextProperty methods that SecurityProperty implements and then calls the ctor of MyClass.

    After this the first time any MyClass method or variable is referenced it calls GetObjectSink method of SecurityProperty through its IContributeObjectSink interface. This method returns a newly created instance of SecurityAspect. Till this you can consider everything as initialization code and SecurityAspect implements our main functionality for AOP advice.

    When the instance of SecurityAspect is created its constructor is passed a reference to next message sink so that all the sinks can be chained and called one after the other. After this SyncProcessMessage is called which is our main method interceptor and where all processing is done. After doing all processing like security verification the code calls the target method. Then it can refer to the return value and do post-processing. With this we have AOP implementation albeit some intrusive code as the target codes needs to be modified for AOP support.

    Possibilities

    AOP is a very generic programming method and can be used in a variety of situation. Some of them are as follows

    Sample code

    The sample solution (VS2005) including all sources are available here. It contains sources for two different aspects, one for security and one for tracing both applied on the same class. I have applied conditional compilation attribute to the tracing aspect so that on release build tracing gets disabled.

  • 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)

    Vista Rocks!!!

    • 20 Comments

    Vista screen shotAnd so does IE 7 and Office 12.....

    I am ashamed to admit that even though I work in Microsoft I never tried out the cool new products. Being a bit low on bug-count I decided to try out Vista (a.k.a. longhorn). I tried ugrading one of the not-so-high-end boxes (3GHz, 1GB ram) to Vista from WinXP. The installation went through smoothly without any glitches and after some time I was the proud owner of a Vista desktop :).

    Within couple of hours of fidling around I was super-happy with what I saw. Not only the UI has become sooooo cool the functionality is simply awsome. I loved the new metallic (??) progress bar. I loved the integrated search. I genereally navigate using keyboards. I loved the fact that I could hit the Win key and directly type the name of the program I was looking for. I typed winword and it showed me MS Word as well as all emails and files containing those words.

    Vista is way ahead in security, with various security plugins in IE and Windows-defender turned on. The system was very stable and I decided to push my luck harder and went ahead with installing Office 12. This simply blew my mind off. The coolest features I hit upon is that your callender, upcoming appointments and pending emails are visible in the main email window of Outlook. The new formatting-preview  of Word, where you hover you mouse on the font size and word shows how the text'd look with the formatting applied was also nice.

    Vista also fixes the old allegation on Windows that you need to go to Start to shut-down. Now there is no text on the Start button. On the default theme its just a round button....

    Right now I am writing this blog in IE7 running on Vista. All in all I was very impressed and plan to shift to Vista as my primary OS over the next few weeks....

  • I know the answer (it's 42)

    .NET API's are not always honest

    • 3 Comments

    First a quiz, assuming that all required priviledges are there what is the output of the following code. All the important bits are marked in bold

    class Program

    {

    static void Main(string[] args)

    {

    string dirName = @"c:\a.";

    try

    {

    System.IO.Directory.CreateDirectory(dirName);

    Console.WriteLine("Created {0}", dirName);

    Console.WriteLine( System.IO.Directory.Exists(dirName) ?

    "Dir exist": "Dir doesn't exist");

    }

    catch (Exception ex)

    {

    Console.WriteLine("Failed to create directory {0}: {1}",
    dirName, ex.Message);

    }

    }

    The output is

    Created c:\a.
    Dir exist

    The problem is if I go to C:\ I see a folder names a and not a. The dot at the end is conveniently dropped. What more interesting is that even though a. does not exist the Directory.Exists API returns true. Windows does not support files and folders with a dot at the end. If you use command window to create a file with a dot at the end then you simply get the file without the dot and no error is reported. .NET Directory API's exactly simulate this, but the question is do I want the simulation? I'd like to see API's being honest and report issues if it fails to do something. API's are used at a lot of places and the burden of checking should be done inside the API and not on code calling the API.

    In VSTS we just got hit by a bug due to this. When you create a Build Type using the the Wizard, the user can enter names with a DOT at the end. We then create a folder with that name and check the whole thing into Team Foundation Source Control. The problem is what gets created is a and not a. So even though you wanted to create a Build Type named a.  you have one named a and all sorts of weird things happen after that. Though this is kind-of a corner situation but still I'd prefer a more honest API anyday..... 

  • I know the answer (it's 42)

    Time to be pushed out

    • 3 Comments

    On some weekends I bring my daughter to office. She's generally very pleased to be able to crawl all over and go where no baby has gone before. On two occasions she had firmly taken my chair and refused to get up. This really got me thinking, its not far away when the next generation comes and pushes us out. But I guess I have some time in hand and I'd use it to churn out more and better code. But first things first, Visual Studio Team System is now getting readied to be released some time in Q1 this year. Let me get back to fix the few bugs that are still left out. VSTS is surely going to be a great product and make life a lot easier for people developing Software....

     

  • I know the answer (it's 42)

    C# and const

    • 8 Comments

    When I first started developing programs using C# I had a lot of baggage that I carried over from C++. One of the programming good practices we used to follow in C++ is marking all instance methods (C++ folks insist on calling functions) that do not change the state of an instance as const. To ensure that methods did not accidentally change objects it was not supposed to change the parameters were passed as const as well. Both of these practices are highlighted in the following code

    class MyClass

    {

    int _value;

    public:

    int GetValue() const

    {

    // the following assignment would have failed to compile

    //_value = 5;

    return _value;

    }

    void SetValue(int pVal)

    {

    _value = pVal;

    }

    };

     

    void show(const MyClass& mc)

    {

    // The following line compiles because GetValue is

    // marked as const in MyClass

    cout << mc.GetValue() << endl;

    // the following call would have failed to compile

    //mc.SetValue(30);

    }

    In the above code if a maintainer came after a year or two and tried to make any changes in the GetValue method that changed the object it would fail to compile. Similarly if MyClass is in some class library then the const method suffix clearly indicates to the user that the method does not change the object in anyway.

    Marking methods with const had an additional benefit as well. In case a methods parameter is marked as const it is not allowed to change the state of the object passed to it. The compiler only allows calls to const methods in this case. However, there are several Gotchas to it, too many for most programmers liking. For example there is nothing to stop a programming from doing the following

    void show(const MyClass& mc)

    {

    MyClass& mcNotConst = const_cast<MyClass&>(mc);

    mcNotConst.SetValue(20);

    }

    However, I don't think that this is a big issue. Because in a C++ project, the lead's job description includes search for const_cast and fire the guy who sneaked it in. But some gotchas are real bad see http://cpptips.hyperformix.com/cpptips/const_logical

    C# unfortunately does not support const methods or const parameters. I always believed that its the duty of a language to be as self-descriptive as possible, const fits well into this even with const_casts lying around.

    There is a new feature in C# 2.0 that somewhat helps in a similar scenario. With C#2.0 get and set accessors of a property can be of different accessibility. So you can make the get accessor public and the set protected as follows

    class MyClass

    {

    int _val;

    public
    int Val

    {

    protected set { _val = value; }

    get { return _val; }

    }

    }

  • I know the answer (it's 42)

    Enumerting all values of an Enum

    • 3 Comments

    <to get all the values as an array see here

    Screen shot Sometimes you need to do something in code and you hit on a simple solution, and then you sit back and marvel on the design that lets you do that. Sometime back when writing my blog on the usage of console color I needed to write some code that got all the values for the Enum ConsoleColor and print text using those colors. I used the following code.

    static void Main(string[] args)

    {

    ConsoleColor originalCol = Console.ForegroundColor;

     

    foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))

    {

    Console.ForegroundColor = color;

    Console.WriteLine("{0, -12} {1}", color, color.ToString("D"));

    }

    Console.ForegroundColor = originalCol;

    }

    All of this could be done so easily is because of the unified inheritance structure of .NET. All enums inherit from System.Enum and so a lot of functionality comes to you for free. You can use Enum.GetValues to do the work of getting all the values and use the base Enum types ToString overrides to give you correct string/value representations of the enum. Try doing this in C++ and the difference is evident.

    The fact that I could do this so easily made me extremely happy. Programmers should be lazy and a language or framework that allows them to be lazy should be the platform of choice. As I had said in my profile I'm enjoying moving into C#/.NET from C++.

  • I know the answer (it's 42)

    C# generics syntax is elegant

    • 10 Comments

    C# generics syntax is much better than the nearest contender C++. Consider the following generic declaration in C++

    template <typename T> // can use <class T> as well

    class GenClass

    {

    };

    I always felt the need to use the typename keyword is without any purpose. Most developers kept using <class T>. The designers of C# showed that the usage of template is also not required. The short and sweet syntax in C# is

    class MyClass<T>

    {

    }

    Constraint syntax sucks

    This does not mean that everything is as small and sweet in C#. The usage of the struct keyword to indicate value type constraint is one such example. Say for a generic type I want to put a restriction that the type parameter can only be a value-type. I have to do it as follows

    class MyClass<T> where T: struct

    {

    }

    MyClass<int> mc = new MyClass<int>();

    This is very un-intuitive because even for integral types like Int I need to use struct as the constraint. 

    Similar issue is with specifying constraints on multiple type parameters. Consider the following

    class MyClass<T,U> where T: struct where U: class

    {

    }

    Only if I break the constraint to two lines can you read it

    class MyClass<T,U> where T: struct

    where U: class

    {

    }

    There should have been some delimiter in between consecutive where to make the whole thing more readable.

    The rules regarding the order of constraints initially taxes your memory but you get used to it soon. If I need a constraint that the type has to be a reference type that must have a public parameterless constructor I need to do the following

    class MyClass<T> where T: class, new()

    {

    }

    Here the order is important as class has to be the first contraint and new() has to be the last.

  • I know the answer (it's 42)

    Extending the team build web-view

    • 10 Comments

    <Update: Fixed so that you no longer need to copy the Microsoft.TeamFoundation.Build.Common.dll. Thanks to a Watson bug we got to this >

    We had a web-UI for Build Report but we do not have one for Build List. Sometime back we had customer queries on adding/removing columns as well as printing the list, both of which we do not support out of the box.

    Team System is very extensible with a lot of functionality exposed through web-methods and client-side object-models. I cooked up a web UI which you can use to see the list of builds, optionally filtered by the Build Type in you favourite borwser. The web-ui consists of an aspx page and an xsl file to format the generated xml. All the data that is available for a build is exposed in the XML generated by the aspx code and you can customize the xsl to show the nodes as you like. .

    Deploying

    1. Download the zip from here
    2. Unzip the sources into Team Foundation Server folder as in %Program Files%\Microsoft Team Foundation 2005\Web Services\Build\v1.0.
    3. Add people whom you want to be able to see the list in the Reader group for the team project.
    4. To access the list use the URL http://<TFSServer>:<Port>/Build/v1.0/BuildList.aspx?TeamProject=ProjectName. Replace the part marked in red with your TFS and project name
    5. To see the list of only a particular Build Type use something like http://<TFSServer>:<Port>/Build/v1.0/BuildList.aspx?TeamProject=ProjectName&BuildType=Bt

    Screen Shot

    Build list as seen in IE filtered on the Build Type Bt2

    Build list screen shot

    Customizing

    You can further customize the list like adding filters. You can accept some filter as in http://<TFSServer>:<Port>/Build/v1.0/BuildList.aspx?TeamProject=ProjectName&BuildType=Bt&Filter=LastWeek and then inside the foreach (BuildData buildData in listOfBuilds) skip all builds that have FinishTime more than a week older

    You can customize the list by changing the xsl file as well.

    Support

    This should work with both Beta 3 and the latest CTP bits. In case you failed to get this to work, drop me a message either in comments or in the contact page.

  • 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#: Fast string comparison optimization

    • 23 Comments

    Sometime back I had blogged about using reference comparison to speed up ordinal string comparisons. Essentially this means that if you know for sure that your string is interned and you want to do an ordinal string comparison you can use the following optimization

    if (command == "START")

    Console.WriteLine("Starting Build...");

    else if (command == "STOP")

    Console.WriteLine("Stopping Build...");

     

    // Optimization

    if (Object.ReferenceEquals(command,"START"))

    Console.WriteLine("Starting Build...");

    else if (Object.ReferenceEquals(command, "STOP"))

    Console.WriteLine("Stopping Build...");

    This works only if the string command is an interned string. If its not (e.g. its accepted from command lines or is constructed) you can intern it using something like string internedCmd = string.IsInterned(command) ?? string.Intern(command); and then use the interned version of the same string.

    However an email to the internal CSharp alias made me look again. The email stated that the static method String.Equals(a,b) is more efficient than instance method String.Equals(a). I looked in into the code and it appears that for static Equals we already do the reference comparison first, while for instance Equals we jump right to string comparison.

    // Static Equals called from overloaded operator ==
    public static bool Equals(string a, string b) { if ((object)a == (object)b) { return true; } if ((a != null) && (b != null)) { return string.EqualsHelper(a, b); } return false; }

    This might get fixed in future .NET version when both Equals will do the reference comparison first. However, the optimization I suggested does not hold because its already been done in the framework right now.

    So currently in the following snippet the second version is faster than the first

    string a = ...;
    string b = ...;




    a.Equals(b);
    string.Equals(a, b); // faster
  • I know the answer (it's 42)

    Mixins and C#

    • 8 Comments

    In one of my previous lives when I first heard about mixin and tried to look it up I hit into various conflicting definitions. The definition of Mixin I settled for is "MixIn programming is a style of software development where units of functionality are created in a class and then mixed in with other classes". In C++ two common ways of doing this is multiple-inheritance and parameterized Abstract Sub Class (yep not Abstract Base class). I'll not get into MI because the basic design of C# will never allow it. However C# may be expanded to include Mixin using generics.

    Mixin in C++

    The definition of mixin above is pretty general. Even though mixin is a class it is intended to be combined with other classes and not to be used standalone. Mixins can be defined using parameterized inheritance of Abstract Sub class as follows

    template <typename Base>

    class MyMixin : public Base

    {

    };

    template <typename Base>

    class AnotherMixin : public Base

    {

    };

     

    MyMixin<AnotherMixin<string> > mm;

    In the above code both MyMixin and AnotherMixin derive from the type parameter passed to it. They are Abstract Sub classes because their super classes are not pre-determined. It is possible to chain them to create a singly-inherited hierarchy so that the combined class gets the public functionality of all the mixin classes in the chain. Lets take a look at a more concrete example....

    #include <iostream>

    #include <string>

    #include <ctime>

    using namespace std;

     

    template <typename T>

    class AgeProvider : public T

    {

    time_t createdOn;

    public:

    AgeProvider() {

    time(&createdOn);

    }

    double age() {

    time_t currTime;

    time(&currTime);

    return difftime(currTime, createdOn);

    }

    string CreatedOn () { return ctime(&createdOn); }

    };

     

    template <typename T>

    class CountProvider : public T

    {

    static unsigned counter;

    public:

    CountProvider() {

    CountProvider::counter++;

    }

    unsigned GetCount() {

    return counter;

    }

    };

    template<class T> unsigned CountProvider<T>::counter = 0;


    typedef
    AgeProvider<CountProvider<string> > TrackedString;

     

    int main(int argc, char* argv[])

    {

    AgeProvider<CountProvider<string> > tstr;

    tstr.append("Abhinaba ");

    tstr.append("Basu");

    cout << "Content : " << tstr << endl;

    cout << "Created : " << tstr.CreatedOn();

    cout << "Age : " << tstr.age() << endl ;

    cout << "Count : " << tstr.GetCount() << endl;

    return 0;

    }

    Here the first mixin class in AgeProvider which gives info on the age in seconds of an instance of the class as well as when the instance was created. The other mixin is CountProvider which gives how many instances of a specific class was ever made. Both of these classes have no use on their own. However when they are mixed together with a stand-alone class like string they provide the funtionality of counting and age to that class. Interestingly the whole of the above works without any multiple-inheritance and not imposing any restriction on the Mixin classes on what they inherit from or the inheritance order.

    Mixins In C#

    Some suggest that extension methods in the upcoming C# 3.0 are a kind of Mixins, because you can put in functionalities in these methods and arbitrarily tag it onto any class you want. In the C# 2.0 specification section 20.1.3 it is clearly called out that the base class of a generic class has to be a constructed class type so this rules out using the above approach to be used in C#. I am not too sure on why we choose to explicitly disallow abstract subclass. Since C# does not support multiple-inheritance, IMO it should have supported Mixin style coding.

  • I know the answer (it's 42)

    Its not a good idea to use Console colors too much

    • 8 Comments

    With Whidbey (VS2005) managed Console based applications have got a boost with new additions to the System.Console namespace. You can now change the color, size, buffer-size, cursor-size, cursor-position, window-title directly from a managed application without PInvoke.

    However, just because it can be done easily, doesn't mean that it should be used. If you are developing a console based game or something similar like a chat client you have the liberty to do this. Otherwise think twice (or thrice) before you play around with any of these settings. The reason is simple most people (like me) will get super annoyed if for some reason the console window suddenly jumps and resizes when I run a program.

    If you think that doing some thing simpler like changing the text color (using Console.ForegroundColor) to draw attention is Ok, consider it carefully. It might just not work, could look horrible on some specific console setting or might convey the wrong meaning. I have listed below some common usage of changing these setting programmatically and why they might not work. Most programmers agree and understand that playing with console window size or buffer-size is not a good idea and do not use it so I have omitted them from here.

    Changing text color using Console.ForegroundColor

    Warning and Error Messages: Using different colors for output text, like yellow for warnings and red for error might be fine. You just need to ensure that you use the right set of colors as their meaning are deeply bound in the mind of the users. The following table typically works

    • Yellow: warning
    • Red: Error
    • Green: Pass, success messages
    • Cyan: Information

    Do NOT use colors when its not absolutely required: Its best to avoid using colors when not absolutely required. In most cases it'll lead to trouble and rarely be of any benefit. See the following example where the prompt comes in yellow. Since this is a console based application it would have blocked until I entered the required inputs so drawing attention with yellow does not add any value. Since yellow is associated with warning, a first-time user might thing that something is wrong and he's required to rectify this by entering some server name.

    Welcome to my tool
    Server  : MyServer
    Username: Abhinaba
    

    Do NOT use a dark color for text: People do change the background color of the console. I use Teal and DarkBlue often, so ensure that you do not choose one of the darker colors for the text as it might coincide with the background color of the console window and your text will be invisible. I once came accross a tool which used blue for text entered by the user. I had launched that application on a blue-background console. Since I was using the application for the first time, I had a hard time figuring out what was going on, as I couldn't see what I was typing.

    The safe colors are Gray, Green, Cyan, Red, Magenta, Yellow and White. However sometimes even these colors in combination with background colors cause eye-sore as in

    Some error message!!
    

    Do restore the original color: Even if you use any of the above colors remember to switch the color back to the original color. Use some thing like

    public void ShowError(string message)
    {
        ConsoleColor orgCol = Console.ForegroundColor; 
        Console.ForegroundColor= ConsoleColor.Red;
        Console.WriteLine(message);
        Console.ForegroundColor = orgCol; // restore color
    }

    This might look trivial, but can be a big source of annoyance. Like your application gets an exception, the exception-handler sets color to red, shows the error message and the application exits. Now whatever I type in that console window is in Red!!!

    Using Console.BackgroundColor

    Do NOT change the background color: Console.BackgroundColor = ... is bad.  The reason being that the color is changed only for subsequent text and it looks horrible as below

    Text before color change
    Text after I changed the background col to cyan

    Even though very few people intentionally do this, it does creep into application. Sometime back in some error message code I saw this.

    Console.BackgroundColor = ConsoleColor.Black;
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Error!!!");
    

    This went undetected in test, until someone opened it in a Teal window and this is what came up

    Some error message!!

    Playing with cursor

    CursorVisible: You might want to hide the cursor when showing some output using Console.CursorVisible = false. Just remember to revert it back to the same visibility state as it originally was.

    CursorPosition: Jumping the cursor around in the screen is not a main-stream scenario and most console application don't use it. However, I have seen some tools like build-systems use this to show subsquent outputs in the same line. Consider the following code

    int currPos = Console.CursorTop; // get the current pos 
    for (int i = 0; i < 30; i++) 
    {
        Console.WriteLine("Counting {0}", i); 
        Console.CursorTop = currPos; // Go back to the same line
        System.Threading.Thread.Sleep(200);
    }

    This shows the counter in the same line. This might be required in your application. However, in some cases its over-done and you can simply live without it...

    Most programmers are used to UI guidelines. Unfortunately most of these guidelines ingnore command line interface and are silent on them...

  • I know the answer (it's 42)

    C# 2.0: Protected member access and generics

    • 3 Comments

    Some time back I had posted about why protected member of a base class cannot be directly called from a derived class. The same thing holds for generic classes as well. However, protected member access rule has been updated in the C#2.0 spec to accomodate for Generics.

    Consider the following

    class BClass {

    protected int x;

    }

    class AClass : DClass {

    }

    class DClass : BClass {

    void Foo()

    {

    //BClass b = new BClass();

    //b.x = 5;

    DClass d = new DClass();

    d.x = 10;

    AClass a = new AClass();

    a.x = 13;

    }

    }

    The above code compiles fine because a class is allowed to access protected member of its base class (not directly though) and also of any other class (AClass) that derives from it. Obviously you cannot access the protected member of any other class.

    In case of generic classes the rule got slightly modified (2.0 spec Section 20.1.7) as follows

    Within a generic class G, access to an inherited protected instance member M using a primary-expression of
    the form E.M is permitted if the type of E is a class type constructed from G or a class type inherited from a
    class type constructed from G.

    What this means is that atleast for protected member access, types constructed from the same generic class are considered the same. Contrast this with the fact that if a generic class has a static member, a seperate copy (not shared) of it used for each constructed type. The following code compiles fine

    class B<T> {

    protected T x;

    }

    class E<T> : D<T>{

    }

    class D<T> : B<T> {

    void F()

    {

    D<int> di = new D<int>();

    D<string> ds = new D<string>();

    di.x = 123;

    ds.x = "test";

     

    E<string> e = new E<string>();

    e.x = "test2";

    }

    }

     

    D<int> d = new D<int>();

    So in the above code even though D<string> and D<int> are different closed constructed types they can access each other protected members. Same thing holds for E<string>.

  • I know the answer (it's 42)

    Stroustrup talks on V-Next of C++. Do they apply to C#?

    • 4 Comments

    For a long time I am out of touch with the C++ world. Amit pointed me to the paper A Brief Look at C++0x which talks about C++0x scheduled to be released in 2009. I loved some of the new features. Some of the changes proposed in C++ brings it closer to C#. Here is a run down with some comparisons with how the new C++ features match up with C#

    • You can now use something like template<class T> using Vec = vector<T,My_alloc<T>>;
      So aliasing is now supported using the keyword using :). I always had some doubt regarding the benefits of having typedef in C# and now we see C++ extending on it as well. I think I'll post later on why C# does not support typedefs and weird things people do to get around it....
    • In the same snippet as above there is a subtle change. I had blogged about it before. You no longer need to have an extra space in between the two >> in nested template definitions as was required before. As I said C++ is getting closer to C#
    • The next one is cool. You can now do Vec<double> v = { 2.3, 1.2, 6.7, 4.5  };
      So you have collection initializers in C++ as well. C# has this too in its next version (3.0). I blogged about this some time back. Combined with object initializers C# is going to be much more powerfull in this.
    • Introduction of Concepts. Concept is the type of a type. Using this you can specify what properties a type should have. It is something similar to the generics where clause in C#. The difference is that concepts in C++ is much more powerful than C# since it is not class hierarchy based. However, both use the where clause. Currently Boost libraries have an implementation for this. Read more about it here.
    • And you have the dreaded implicit type. In C# you call it var and in C++ auto. In a expression like
      for (auto p = v.begin(); p!=v.end(); ++p)
          cout << *p << endl;
      The type of p is inferred from the return type of v.begin().

    Interestingly as Stroustroupe himself says all the new features are targeted for generics development. This is very close to the C#2.0 release which had a huge number of changes targetted for generics.

Page 1 of 1 (18 items)