image Alright, a lot of arguments are already going on in the twitter sphere about Microsoft positioning HTML 5 on top of Silver light. A lot of opinions are floating around in the blogosphere too.  My 2 cents here.

If you are not aware about the story, then I suggest you to read Mary Jo’s Initial post that says Microsoft: Our strategy with Silverlight has shifted based on her conversation with Bob Muglia - that kicked off the entire debate, and also read this post from Mashable that says “Microsoft Shifts from Silverlight to HTML”

I’m not a Silverlight ‘only’ developer, though I'm a Microsoft MVP in Client Application Development.  But I loved Silverlight for its potential - I used to discuss with my friends how big Silverlight is, and how it may become a platform for developing “write once, run anywhere” apps for web, desktop, mobile & handheld devices, IPTVs etc – especially with cloud in the background.

So, let us take a step back and have a look at what exactly is the strategy shift from Microsoft. All of us know that, for some time, Microsoft is projecting Silverlight as the “Cross platform, Cross device technology”

From Scott Gu’s Blog, From his Silverlight 2.0 Post that he posted some time back.

Silverlight opens up a ton of opportunities to build significantly richer client experiences that run cross platform and cross browser.

So, now Bob Muglia quoted as saying

“Silverlight is our development platform for Windows Phone,” he said. Silverlight also has some “sweet spots” in media and line-of-business applications, he said.

Ah, so what do you infer from that? If you are a Silverlight dependent guy, who makes your living by selling Silverlight trainings and content, you might say  “Don’t worry a bit, Silverlight is still there, Silverlight was never about Websites, you can still use it to build apps, you can still use it to develop for Phone”. That may be a consolation to some of the Silverlight developers. You can console them even more by saying - “Wow guys, cheer up, Silverlight is not yet dead as you think, there is just change in strategy. It was never for web”. But hold on, there are other grave concerns here.

A Dilemma for CTOs – The Business Angle, A Matter of Trust

The fact is, today, a number of enterprises already started investing in Silverlight for their next generation web applications. So Bob, what those guys are going to do now? Scrap the existing Silverlight projects, because Microsoft says Silverlight is not that cross browser/cross platform any more, and it is no longer the preferred platform for developing web applications?

I think Microsoft should have been more organic in their positioning strategy, because now most CTOs who invested in Silverlight for their next generation ‘cross platform/cross browser’ applications should be scratching their heads, and should be searching web to get some explanation for justifying their investments now hanging in mid air. Your clients are going to come and ask you - “Why you are building this on Silverlight, instead of HTML5? We need stuff in HTML5” – How you are going to convince them? I’ve already seen couple of tweets like “CTO is already reneging/disallowing #Silverlight for any client facing solution”. And even if you are not a CTO, you can understand what I meant. I want to point out in bold, It is a matter of trust. Now, any CTO or technology guy might think twice - before betting on any Microsoft technology in future.

A Concern for .NET Developers

One big charm of Silverlight was the ability to deliver user experience over a browser via the Silverlight Plugin, with out worrying much about HTML/Javascript/CSS. A ‘normal’ .NET developer would prefer to code more in C# and XAML, than embracing Javascript and CSS – mainly because of the tooling support available for C# and XAML in his preferred IDE. So, all the Silverlight developers out there might be also scratching their head – because their CTOs are scratching their head, and they don’t  know whether the Silverlight project they work right now is going to continue or not. Ah, I’m not joking – Just saw a Silverlight MVP tweeting “Where can I find a beginners guide to JQuery?”

A Pointer Towards Microsoft’s Internal Politics?

So, long point made short – Bob Mugila rubbed a couple of guys who invested in Silverlight the wrong way – Microsoft will lose the trust from at least a handful of F500 CTOs, and will receive the wrath of a good number of Silverlight developers who might want to learn HTML, JQuery and CSS in depth now!!

Oh Bob, why you did this? Especially when you don’t have enough tooling around HTML5 and JQuery, and you want your developers with you? Not because Silverlight is less adopted. Silverlight was well adopted as a development platform – most Microsoft developers were excited about Silverlight, most CTOs were planning to increase their investments in Silverlight. The end user adoption by internet users was 60%, compared to 96% of Flash.

Then? Is it because Microsoft felt HTML5 is the only way they can get into the Apple devices by projecting HTML5 more, by kicking Silverlight a bit down? Oh, wait, but No. HTML5 is not driven by Microsoft, it is not yet ready or adopted totally, their existing developers don’t have any know-how there, and Microsoft development environments don’t have any solid tooling available to build HTML5 applications.

Huh, Curios. But at least for me, the reason seems pretty simple – If Microsoft supports Silverlight too much, IE9 will lose it’s prominence. If Microsoft shops start building their applications in Silverlight, no body will care of upgrading to IE9, because you are not browser dependent. The IE guys may not need that to happen. Also, if Silverlight is promoted more, Silverlight based operating systems (like Windows Phone 7 OS) will be in demand for hand held devices more than Windows OS itself. So, whether some one in Microsoft is letting down their Silverlight followers and even betting on customer trust for protecting the job/importance of the guys in IE/Windows OS team? Or, if they have a better reason, there no better time to stand up and speak out.

So, what about Silverlight’s future?

Microsoft should stand corrected. Don’t let Silverlight go down under the carpet, don’t limit it just ‘for phone’ or only for other ‘sweet spots’. Commit towards investing more in Silverlight, to implement more features and tooling around them - so that it’ll stay on top of HTML5, as a value added platform. Say that publicly. Continue the efforts for making it cross browser and cross platform. Continue supporting Moonlight initiatives for Linux. Promote Silverlight based OS platforms (Windows Phone 7 OS) more – so that it can get more adoption for thin devices and IP TVs. Provide better support for Silverlight in Mac for OOB scenarios. Most importantly, don’t de-motivate your awesome Silverlight team.

Ok, those are few thoughts I have as of now :) Happy Coding!!

Update: Nov 02, 2010: Bob just came up with few good clarifications on the entire drama, Read this post from Bob Muglia

 

Other Must Reads:

Read more >>

image Recently, in Microsoft PDC 2010, Anders announced the new asynchronous features that’ll be introduced in the next version of C# (5.0?). This post is a quick and simple introduction towards using the async and await keywords. If you want to play with the async/await, you may need to download and install the Async CTP from the MSDN Site..

In short, “async” modifier marks method or lambda as asynchronous. “await” operator yields control until awaited task completes.

Writing some actual Code

Might be helpful if you read Tasks 1-2-3 Why What How before this, if you are not familiar with Tasks.

Let us try some simple ‘working’ code first, then we’ll discuss the concepts involved. Consider the following code, where we start a hotel and call our Cook/Chefs to start cooking various dishes. Each cook will take a random time to cook his dish. See the implementation below.

        

        static Random rnd = new Random();

        static void Main(string[] args)
        {
            //Do some other heavy duty background task in this thread
            StartHotel();
            Console.WriteLine("StartHotel called..");
            Console.ReadLine();

        }

        static void StartHotel()
        {
            Console.WriteLine("Starting Hotel..");

            for (int i = 0; i < 10; i++)
            {
                string name = "Chef" + i;
                CookDish(name, "Dish"+i);
                Console.WriteLine("Asked {0} to start cooking at {1}", name, DateTime.Now.ToString());
            }
        }

        static async void CookDish(string chefName, string dish) 
        {
            //Induce a random delay 
            int delay = rnd.Next(1000, 4000);
            //Cook is cooking - Task
            await TaskEx.Delay(delay);
            //Write the result - StuffAfterAwait
            Console.WriteLine( "Chef {0} Finished at {1}",chefName,DateTime.Now.ToString());
        }

See the usage of ‘async’ and ‘await’ keywords.

  • We used ‘async’ to mark our CookDish as an asynchronous method (The method involves async flow, and can return before it is completed).
  • We used ‘await’ keyword to inform the compiler to re-wire the method in such a way that (a) the remaining part of the method (after using ‘await’) should be executed only after the task is fished  (b) Return to the caller immediately.

To understand the above two points, let us have a look at the output of the above program. When you run this, have a look at the output that you’ll get.

image

See that each time you call CookDish in the for-loop, the cook will be asked to start his job, and the control is returned to the caller, i.e, the StartHotel method, so that we can ask the next cook to start cooking, with out waiting for the first cook to finish. And each cook will finish cooking based on the delay required for cooking, and the remaining part of CookDish will be executed once the cook finishes cooking. Note: When you actually run this, the console messages after ‘StartHotel called..’ line will appear one by one, because Console.WriteLine(..) part of CookDish will be executed after the delay for each cook. 

Also, note that in the Main(..) method, the calling context went past StartHotel call before first cook finished his cooking (hence the message “StartHotel called..” before Chef Finished messages). We’ve a Console.ReadLine in our method so that we won’t end Main automatically before all cooks are done with cooking.

 

A Minimal look at the concepts

This part is more or less about few basic concepts involved. Let us have a closer look at the usage of async/await, which is pretty simple. Have a look at this informal code.

void Caller() 
{ 
  SomeMethod(); 
  StuffAfterSomeMethod(); 
} 

//Mark a method as async 
async void SomeMethod() 
{ 
   StuffBeforeAwait(); 

   //Ask compiler to re-wire StuffAfterAwait as a continuation, 
   //and return execution point to the Caller immediately 
   var result=await SomeTask(); //Remember cooking part 

   StuffAfterAwait(result); 
}

There are two interesting aspects here.

  • The async keyword is just for informing the compiler that your method involves asynchronous flow, so that it can be re-wired in such a way that the statements after await SomeTask are executed as a continuation of SomeTask, with out blocking anything.
  • The re-wiring ensures the context can be returned to the Caller() immediately  – So that StuffAfterSomeMethod() in Caller (See above code) can be called with out waiting for SomeTask in SomeMethod

I want to re-iterate that 'await' is not there for blocking anything as you might think. Technically, it is there for marking a delayed execution of what ever that comes after await. So, what ever that comes after ‘await’ in that method will be executed only after the Task is finished. By using await, you are saying the compiler –"hey dude, re-wire this method so that StuffAfterAwait will be executed as a continuation of SomeTask()" - Now, during compile time, the C# compiler will re-wire your above code to something like this. 

//Pseudo code

void SomeMethod()
{
  StuffBeforeAwait;
 

  //Note: Pseudo code, just to indicate the logic

  When SomeTask is completed
    {
      //We'll enter this only when SomeTask is completed
      //Continue with StuffAfterAwait
      
      //Some way to return the result to current sync context    
      //NOT by directly returning
      result=SomeTask.Result;
 
      StuffAfterAwait(result);     
    }

  //Return the context to the caller with out
  //waiting for SomeTask to finish.

} 

The above code is just informal/pseudo code that represents how the SomeMethod and SomeTask is re-wired.

The actual implementation involves, the compiler generating code for invoking a GetAwaiter() method on the await’s target. GetAwater inturn returns a TaskAwaiter object,  and then the BeginAwait and EndAwait methods of the TaskAwaiter is used to do the Continuation re-wiring - that is similar to what we discussed above.

If you remember, Task class was part of  the .NET 4.0 TPL, under the System.Thread.Tasks namespace. See my earlier post Tasks 1-2-3 Why What How. The Async CTP provides a GetAwaiter() extension method for the Task class.

A Task in .NET 4.0 is a simple unit of an asynchronous operation. From .NET 4.0 onwards, it is recommended that you should use Tasks instead of creating your own Thread pool work items. Also, it is recommended that you should avoid creating threads, if you don’t need direct control on a thread’s life time.

Anyway, we’ll discuss more about GetAwaiter, BeginAwait and EndAwait in a later post. 

I’m talking about Continuation ‘re-wiring’ a couple of times above. What I really meant is, ‘re-wiring’ a sequence of methods to a Continuation Passing Style. If you want to understand more details about CPS and how it is leveraged to implement async/await under the hoods - the best way is to read all these posts from Eric.

Instead of "returning" values as in the more familiar direct style, a function written in continuation-passing style (CPS) takes an explicit "continuation" argument.

So, hope you’ve a better idea of async/await now. Happy Coding!!

Read more >>

In this round up post, I’ll list down some of my “Back To Basics” C# Articles.

1 – Creating Fluent Interfaces in C#

This post demonstrates various possibilities of Fluent programming in C#. Have a look at how to train a bunch of dogs using Fluent interfaces

2 – Revisiting Delegates, Anon Methods & Lambdas

This post briefs Delegates, Anonymous Methods and Lambda expressions, and how these features got evolved with various versions of C#. Also, this post has few interesting uses of Lambda expressions as well

3 – A closer look at Anonymous Types in C#

If you want to examine Anonymous types closely, have a look at this post. This post briefs the object initializer syntax, and projections via Anonymous types.

4 – C# ‘dynamic’ Keyword – Under the hood

Want to know more about the Dynamic features of C#, and how the ‘dynamic’ keyword is getting compiled? See this post, where we have a look at the disassembled code to examine how ‘dynamic’ keyword actually works.

5 – C# Compiler Type inference for Generic Methods

In this post, we’ll examine type inference features of C# compiler for generic methods, and how to leverage that to write cool extension methods with type inference.

Happy Coding, Enjoy!!

Read more >>

Poor Man's Singleton Methods via Dynamic Wrappers in C#

image "The static world you see there is not real, you are programmed to think so. There is a true world out there, which is very very dynamic" - Do I sound like Morpheus in Matrix?


Justin recently wrote an emotional post about Ruby, and as a primary C# guy, I found it quite interesting. Though I’ve never paid some serious attention to Ruby earlier, I was exploring the dynamic features in C# for some time (See my posts on dynamic and also have a look at this ElasticObject implementation). So, I started digging into Ruby a bit after reading Justin’s post, I found a lot of interesting concepts, for example, the Singleton methods.

Singleton Methods

So, what are Singleton methods?

The behavior of an instance is determined by its class, but there may be times we know that a particular instance should have special behavior. In most languages, we must go to the trouble of defining another class, which would then only be instantiated once. In ruby we can give any object its own methods.

And here is a Ruby example.

ruby> class SingletonTest
    |   def size
    |     25
    |   end
    | end
   nil
ruby> test1 = SingletonTest.new
   #<SingletonTest:0xbc468>
ruby> test2 = SingletonTest.new
   #<SingletonTest:0xbae20>
ruby> def test2.size
    |    10
    | end
   nil
ruby> test1.size
   25
ruby> test2.size
   10

See that you are 're-opening' the size method of test2 object, to return some other value other than the value specified by the default size method, at runtime. Isn’t that interesting? For sure, especially if you hasn't visited Ruby earlier.

Poor man's Singleton Methods In C#

Now, I started thinking about implementing something similar in C#, leveraging the dynamic features, with out depending on the traditional AOP style, and came up with a dynamic wrapper that’ll allow you to do wrap objects, some what like a proxy. You can assign a new delegate instance against an existing method name, and the wrapper is capable of re-routing invocations to the assigned method when an invocation happens. Ah, I think some code is better than the explanation.

For example, consider this code.

class Program
    {
        static void Main(string[] args)
        {

            //Existing objects
            Duck someObject = new Duck();
            dynamic duck = someObject.Extend();

            //Call Walk
            duck.Walk();

            //Now modify this Walk() on the fly
            duck.Walk = new Action(() => System.Console.WriteLine("Duck Walking left"));

            //Call Walk again
            duck.Walk();

        }
    }
    public class Duck
    {
        public void Walk()
        {
            System.Console.WriteLine("Duck walking right");
        }
    }
You can see that we are modifying the Walk behaviour, and imagine the output you'll get.

Duck Walking right
Duck Walking left

As you might imagine, the Extend extension method simply creates a dynamic wrapper on top of our duck object, and returns the wrapper for further operations. The wrapper can also wrap static methods, which means you can do something like this as well.

//Static classes
            dynamic con = typeof(System.Console).Extend();
            con.WriteLine=new Action<string>
                             (s=>System.Console.WriteLine("hello " + s));
            con.WriteLine(" world");
            
           //Your output will be 'hello world' (with out the quotes)

The only problem here is, once you extend the object via the dynamic wrapper, you need the whole infrastructure to be dynamic to leverage this, while in AOP your proxies are still typed. So assuming your program universe has two worlds, say static and dynamic, the wrapped object is of no use in the static world – all this will work only in the dynamic world (say your functions/properties accepting dynamic objects and returning dynamic objects etc).

Also, comparing to Ruby, we are not even near - we are not touching the actual object or modifying any behavior of the same, we are just wrapping it :(

Now, if you don't need to wrap existing classes/objects in the .NET framework, you may use the ExpandoObject to attach your own behavior

Another interesting thought


The wrapper can be used to wrap the C# objects, and pass the same to dynamic worlds so that the behavior of your C# objects can be modified there - like, when you pass an object from C# to IronRuby. I havn't tried it yet and I have no idea how it works in the IronRuby world right now, but it should be possible. :)

The Code - Exploring further

So, here are the extension methods and the wrapper, that'll achieve what I showed above.

//Warning: Just wrote this pretty quickly, only for demo purposes :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Reflection;

namespace DynamicLibrary
{

 public static class DynamicExtensions
    {
        //Our generic IsGreaterThan extension method
        public static dynamic Extend<T>(this T obj)
        {
            return new ExtensionWrapper(obj);
        }

        public static dynamic New<T>(this T t)  where T:new()
        {
            return new ExtensionWrapper(new T());
        }

    }

    public class ExtensionWrapper : DynamicObject
    {

        /// <summary>
        /// The object we are going to wrap
        /// </summary>
        object _wrapped;

        /// <summary>
        /// A collection of methods
        /// </summary>
        Dictionary<string, Delegate> _methods = new Dictionary<string, Delegate>();

        /// <summary>
        /// Specify the flags for accessing members
        /// </summary>
        static BindingFlags flags = BindingFlags.Instance
            | BindingFlags.Static | BindingFlags.Public;

        /// <summary>
        /// Create a simple private wrapper
        /// </summary>
        public ExtensionWrapper(object o)
        {
            _wrapped = o;
        }


        public ExtensionWrapper(Type t)
        {
            _wrapped = t;
        }


        Type WrappedType
        {
            get
            {
                return (_wrapped is Type) 
                    ? _wrapped as Type 
                    : _wrapped.GetType();
            }
        }

        /// <summary>
        /// Try invoking a method
        /// </summary>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var types = from a in args
                        select GetActualType(a);
            string mname = GetInternalName(binder.Name, args);

            if (_methods.ContainsKey(mname))
            {
                result = _methods[mname].DynamicInvoke(args);
                return true;
            }

            var method = WrappedType.GetMethod
                (binder.Name, flags, null, types.ToArray(), null);

            if (method == null)
                return base.TryInvokeMember(binder, args, out result);
            else
            {
                result = method.Invoke(_wrapped, args);
                return true;
            }
        }

        public Type GetActualType(object t)
        {
            return (t is ParameterInfo)
                        ? (t as ParameterInfo).ParameterType : t.GetType();
        }

        /// <summary>
        /// Get the internal name for a method for housekeeping
        /// </summary>
        private string GetInternalName(string name, object[] args)
        {

               var typeNames = from a in args
                            select GetActualType(a).Name;

            string mname = name + "$" +
                                        (typeNames.Count() > 0
                                            ? typeNames.Aggregate((a, b) => a + b)
                                            : string.Empty);
            return mname;
        }

        /// <summary>
        /// Tries to get a property or field with the given name
        /// </summary>
        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            //Try getting a property of that name
            var prop = WrappedType.GetProperty(binder.Name, flags);

            if (prop == null)
            {
                //Try getting a field of that name
                var fld = WrappedType.GetField(binder.Name, flags);
                if (fld != null)
                {
                    result = fld.GetValue(_wrapped);
                    return true;
                }
                else
                    return base.TryGetMember(binder, out result);
            }
            else
            {
                result = prop.GetValue(_wrapped, null);
                return true;
            }
        }

        /// <summary>
        /// Tries to set a property or field with the given name
        /// </summary>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            var prop = WrappedType.GetProperty(binder.Name, flags);
            if (prop == null)
            {
                var fld = WrappedType.GetField(binder.Name, flags);
                if (fld != null)
                {
                    fld.SetValue(_wrapped, value);
                    return true;
                }
                else if (value is Delegate)
                {
                    var param = (value as Delegate).Method.GetParameters();
                    var types = from a in param
                                select GetActualType(a);
                    var method = WrappedType.GetMethod
                                        (binder.Name, flags, null, types.ToArray(), null);

                    if (method != null)
                    {
                        string mname = GetInternalName(binder.Name, param);                         
                        _methods[mname] = value as Delegate;
                        return true;

                    }
                    else
                    {
                        return base.TrySetMember(binder, value);
                    }

                }
                else
                    return base.TrySetMember(binder, value);
            }
            else
            {
                prop.SetValue(_wrapped, value, null);
                return true;
            }
        }

    }
}

This might be insane and of no use, but never mind. Happy coding!! Have a look at my other posts on C# dynamic features
Read more >>

Straight to a question for you.

Consider the following code, where you accept a caller key and a token request from a caller, to issue a security key for further requests? Note that we also have a minimal exclusion check, where we prevent certain callers from getting the admin permission. Now, the question. What is wrong with the code below?

public enum SecurityToken
    {
        Admin,
        Registered,
        Anon
    }

    public class SecurityGateway
    {
        public string GetSecurityKey(string callerKey,SecurityToken token)
        {

            //Prevent caller2 from getting the admin token
            if (callerKey.Equals("secretcallerkey2") 
                && token == SecurityToken.Admin)
                return "Error: You can't request an admin token";

            //Issue the token
            switch (token)
            {
                case SecurityToken.Anon:
                    return "PermissionKeyForAnonymous";
                case SecurityToken.Registered:
                    return "PermissionKeyForRegistered";
                default:
                    return "PermissionKeyForAdmin";
            }
        }
    }

If you already found the issue, you may stop reading here. Otherwise, let us examine this in a bit detail.

Assume that a caller, let us sayCaller1, is requesting a security key for leveraging admin permissions.

SecurityGateway gateway = new SecurityGateway();

            //Caller 1
            var key = gateway.GetSecurityKey("secretcallerkey1", SecurityToken.Admin);
            //key's value is PermissionKeyForAdmin for secretcallerkey1


As you may imagine, the value of key will be PermissionKeyForAdmin, as expected.

Now, the issue. As you may be aware, C# enums are implemented as integers by default, and you can cast integers to an enum type. So, if the Caller2 has some evil plans, it may do something like this.

SecurityGateway gateway = new SecurityGateway();

            //Caller 2
            var key = gateway.GetSecurityKey("secretcallerkey2", (SecurityToken)10);

            //OOps, key's value is still PermissionKeyForAdmin for secretcallerkey2, 
            //bypassing the exclusion check we've above
            


Note that I'm casting an integer to an enum, and the following exclusion check will be bypassed by Caller2, because the token's value is 10, instead of the value for SecurityToken.Admin.

//OOps, Caller2 can bypass this exclusion check

           //Prevent caller2 from getting the admin token
            if (callerKey.Equals("secretcallerkey2") 
                && token == SecurityToken.Admin)
                return "Error: You can't request an admin token";


Alright, so the point is, be a bit more careful when working with Enums in general, and also when you implement check conditions with enums.

Update: As Oleg pointed out below, an explicit check using Enum.IsDefined(..) to validate if the passed value exists in the specified enumeration is the best solution.


Happy coding, you may also love reading few more back to basic posts in this blog
Read more >>

This is a back to basics post.

As you may already know, C# compiler don’t support type inference for generic classes, but it supports type inference for generic methods. To illustrate the point, let us consider a very simple example.

class Program
    {
        //Our generic IsGreaterThan method
        public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
        {
            return (x.CompareTo(y) > 0);
        }

        static void Main(string[] args)
        {
            //You don't need to explicitly specify IsGreaterThan<int>
            var result = IsGreaterThan(20,10);
            Console.WriteLine(result); 
        }

    }

As you can see, we are not specifying the type explicitly, while calling our IsGreaterThan method - it is inferred automatically by the compiler. That is simple, isn’t it? Now, things become a a bit more interesting when you combine Generic method type inference with extension methods. Have a look at this code, we just made our IsGreaterThan<T> method an extension method.

  public static class UtilExtensions
    {
        //Our generic IsGreaterThan extension method
        public static bool IsGreaterThan<T>(this T x, T y) where T : IComparable<T>
        {
            return (x.CompareTo(y) > 0);
        }      
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            //You still don't need to explicitly specify IsGreaterThan<int>
            var result = 20.IsGreaterThan(10);
            Console.WriteLine(result);

        }

    }

As you can see, we are still good - the compiler can still infer the types. And of course, you can leverage our IsGreaterThan against any IComparable implementation. Also, explore more back to basics posts.

Read more >>

image Mono is getting more mature. I should say, Mono guys are even outshining their Microsoft counterparts in some areas. For example, Mono’s C# compiler already supports Compiler as a Service. In this post, we’ll have a quick look at some interesting Mono libraries that you can use in your .NET projects, to take advantage of some of their functionalities, that is not present in the .NET stack.

1 - Mono.CSharp – For Compiler as a Service and C# as a scripting language

Anders in his C# Futures Talk mentioned about C# Compiler as a Service and demonstrated an REPL (Read Evaluation Print Loop) implementation. And few months back, I got pretty surprised when I found that Mono announced Compiler as a Service support. This will enable you to evaluate C# code on the fly, and more importantly, to use C# as a scripting language in your applications. Here is a step by step guide to this feature.

2 - Mono.TextTemplating – For T4 (Text Templating) Functionality in your .NET applications

In a lot of scenarios, a custom text template processor comes in handy. I remember putting together a simple, custom Text template processor some time back for generating Emails. With in Visual Studio, there is a Text Templating transformation engine built in, better known T4. It is used for a lot of scenarios, mainly for generating code from Models, and is used in various VS Packages for code generation purposes. You can also write your own Template files (*.tt) with in Visual Studio, and Clarius has a cool T4 Editor available for Visual Studio.

All is good. But what if you want to implement some templating functionality in your own applications? We can’t use the Microsoft.VisualStudio.TextTemplating libraries, because I don't believe that T4 can be legally redistributed without Visual Studio. But you can rely on Mono equivalent T4 implementation,Mono.TextTemplating

And, if you want to see an example, you should check out a Custom View Engine I developed for ASP.NET MVC using Mono.TextTemplating and the related example code. More than an ASP.NET MVC View Engine example, it is also an example of how to host the T4 Engine in your own applications.

3 - Mono.Cecil – For Modifying .NET Assemblies, And a better alternative to .NET Reflection

If you use .NET Reflection heavily, you should have a look at Mono.Cecil.  You can also use Mono.Cecil to modify a compiled assembly, or to weave some code in to your assemblies (AOP) directly. To try out Cecil, get the latest version 0.9 from Github and compile Mono.Cecil library in VS2010.

Now, create a console application in Visual Studio, and try this example after adding a reference to Mono.Cecil.dll. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;

namespace CecilAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Open a given assembly. Let us assume the
            //first command line param is the path to the assembly to load and inspect
            AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(args[0]);

            //All Modules in this assembly
            foreach (var modDef in assemblyDefinition.Modules)
            {
                Console.WriteLine(" +--Module {0}", modDef.Name);
                //All types in this module
                foreach (var typeDef in modDef.Types)
                {
                    Console.WriteLine("   +--Type {0}", typeDef.Name);
                    //All methods in this type
                    foreach (var methodDef in typeDef.Methods)
                    {
                        Console.WriteLine("      --Method {0}", methodDef.Name);
                    }
                    //All properties in this type
                    foreach (var propDef in typeDef.Properties)
                    {
                        Console.WriteLine("      --Property {0}", propDef.Name);
                    }
                }
            }
        }
    }
}

Compile the above example, and try it against a .NET dll to see the output, by providing the target assembly’s path

The above example shows how to iterate through all modules, types, methods and properties in an assembly using Mono.Cecil. What is more interesting is, you can even modify the information and even save it back. Paul has a good post on using Cecil to obfuscate your .NET assemblies. Also, have a look at his NCloak obfusctor, it is open source, that is built leveraging Cecil’s power.

Also, check out my C# AccessPrivateWrapper where I explore how to use reflection to access private classes, variables etc.

Read more >>

image This post assumes you are familiar with basic MVVM concepts and RelayCommand/DelegateCommand

In a lot of scenarios, you need to perform operations in an asynchronous way in your View Model. And most of the time, BackgroundWorker class comes handy. So, here is a quick implementation of an Asynchronous version of DelegateCommand, that wraps the BackgroundWorker under the hoods.

    /// <summary>
    /// An async version for delegate command
    /// </summary>
    public class AsyncDelegateCommand : ICommand 
    {

        BackgroundWorker _worker=new BackgroundWorker();
        Func<bool> _canExecute;

        /// <summary>
        /// The constructor
        /// </summary>
        /// <param name="action">The action to be executed</param>
        /// <param name="canExecute">Will be used to determine if the action can be executed</param>
        /// <param name="completed">Will be invoked when the action is completed</param>
        /// <param name="error">Will be invoked if the action throws an error</param>
        public AsyncDelegateCommand(Action action, 
                                    Func<bool> canExecute=null,
                                    Action<object> completed =null,
                                    Action<Exception> error=null
                                    )
        {

            _worker.DoWork += (s, e) =>
                {
                    CommandManager.InvalidateRequerySuggested();
                    action();
                };

            _worker.RunWorkerCompleted += (s, e) =>
                {

                    if (completed != null && e.Error == null)
                        completed(e.Result);

                    if (error != null && e.Error != null)
                        error(e.Error);

                    CommandManager.InvalidateRequerySuggested();
                };

            _canExecute = canExecute;
        }


        /// <summary>
        /// To cancel an ongoing execution
        /// </summary>
        public void Cancel()
        {
            if (_worker.IsBusy)
                _worker.CancelAsync(); 
        }

        /// <summary>
        /// Note that this will return false if the worker is already busy
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            return (_canExecute == null) ? 
                    !(_worker.IsBusy) : !(_worker.IsBusy) 
                        && _canExecute();    
        }

        /// <summary>
        /// Let us use command manager for thread safety
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Here we'll invoke the background worker
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            _worker.RunWorkerAsync(); 
        }
    }
So, now from your view model, you can use use our AsyncDelegateCommand like this.
    public class YourViewModel : INotifyPropertyChanged
    {
        public YourViewModel()
        {
            DoSomethingCommand = new AsyncDelegateCommand(
                    action:() => DoSomething(),                   
                    error:(ex)=>Debug.WriteLine(ex.Message));
        }

        public ICommand DoSomethingCommand { get; set; }

        void DoSomething()
        { 
        }
		
    }

This will execute DoSomething in an asynchronous manner. And when you bind the DoSomethingCommand to the Command property of your UI elements, you'll see that the UI element's enable/disable state is changing automatically based on our BackgroundWorker's state (i.e, when worker is busy, you'll see your buttons disabled).

Just thought about sharing the implementation after finding this pretty handy :). Not sure if some one out there already has a similar idea/implementation that wraps the Background worker inside a command implementation, if you know about any, please leave a message. A quick note – I’m using optional parameters here (C# 4.0 specific). So tailor down as required if you need to use this in 3.5.

Happy Coding!!

Read more >>

search For some time, I was thinking about developing a web search plug-in for Visual Studio, so that I can search the web (mainly sites like StackOverflow, CodeProject, MSDN etc) in a non intrusive way, with out leaving the IDE.

Here we go, meet Vingy 1.0 – A simple, but effective add in for Visual Studio 2010 so that you can search the web in a non intrusive way, and can filter results based on sources.

Getting used to Vingy

You can bring up Vingy either by clicking View->Other Windows –> Vingy Search Window from the Visual Studio IDE, or just by high lighting some text in the document and then clicking Tools –> Search Selected Text (Ctrl + 1).

Searching with Vingy is pretty straight forward. You can initiate a Search in two ways.

  • By typing the text in the Vingy search box and pressing ‘Enter’ or by clicking the ‘Go’ button
  • By highlighting some text in the editor when you type in Visual Studio, and then pressing Ctrl + 1

image So, after installing Vingy, high light some text in your editor and press Ctrl + 1 to start searching.

You can use the Next and Previous buttons to browse through the results, and can click the Title of a result or the tiny ‘Open’ button to open the result in a full browser Window. Also, there is a progress ‘busy’ indicator to indicate if Vingy is busy.

 

The Source Selector

You may also restrict your search based on particular sources. For example, you may need to view the results only from StackOverflow or MSDN, and not from the entire Web. You can select the source via the Source selector combo box.

image

 

Installing Vingy

Vingy is free and you can install the same from this direct link (hosted at Visual Studio Extensions Gallery)  or via the Extensions Manager in Visual Studio 2010 (Search Vingy in the Online Gallery). Enjoy, happy coding!!

Let me know your feedback. This version is minimal, but I’ll add more meat based on your feedback. Also, planning to make it open source after a bit of code cleanup.

Read more >>

top