Quick Ruby Reference for .Net Developer

22. January 2012

I use C# at my day job and Ruby for other work. After years of thinking and programing in C#, lots of things comes naturally while programming in C#. In the evenings, when I switch to Ruby, many times I find myself thinking about how to do simple thing like checking type in Ruby. I have put together a list of a handy reference for Ruby common constructs, if you are also switching between languages, you might find it useful. I have covered 12 common things here, more in future posts.

1) Static Methods

class DoorFactory def self.make_door width,height "Door (size #{width} by #{height})" end end puts DoorFactory.make_door(3,8)

2) Hash - Common Operations

door_prices = { "small" => 34.00, "medium" => 46.00, "large" => 55.00} puts door_prices.select{|k| k == "medium"} # {"medium"=>46.0} puts door_prices.select{|k,v| v > 35} # {"medium"=>46.0, "large"=>55.0} puts door_prices.has_key?("super-large") # false puts door_prices.has_value?(46.00) # true

3) Array – Common Operations

door_sizes = ["small","medium","large"] puts door_sizes.find_index("super-large").nil? # true door_sizes.each_index{|i| puts door_sizes[i]} # small medium large puts door_sizes.include?("super-large") # false puts door_sizes.empty? # false

4) Iteration

door_prices.each{|k,v| puts "#{k} = #{v}"} door_sizes.each{|s| puts s}

5) Type Check

price = 56.00 puts price.class # Float puts price.is_a? Integer # false puts price.instance_of? Float # true

6) Method Exists?

puts DoorFactory.respond_to? 'make_door' # true because it's static method agile_door_factory = DoorFactory.new puts agile_door_factory.respond_to? 'make_door' # false because it's not an instance method

7) Try, Catch, Finally

begin 3/0 rescue puts 'There was an exception for sure...' ensure puts 'Exception or no-exception, I am gonna be there...' end

8) Properties

class Door attr_reader :state attr_writer :lock_code attr_accessor :door_number def initialize @state = 'Closed' end end door = Door.new #puts door.state = 'Open' # Error as its read-only door.lock_code = '4563' # Ok #puts door.lock_code # Not Ok, as its a write-only

9) Inline instantiation with attribute hash

# Its not in-built, some custom approaches :http://stackoverflow.com/questions/2680523/dry-ruby-initialization-with-hash-argument

10) Access Control

class DoorLock private def reset_timer end protected def emergency_unlock end public def unlock access_code end def lock end end lock = DoorLock.new puts lock.respond_to? 'unlock' # true puts lock.respond_to? 'reset_timer' # false puts lock.respond_to? 'emergency_unlock' # TRUE ,unlike C# where protected are visible only internally or to inherited clases

11) Lambda, Proc and Block

class AsyncProcessor def do_async_job arg1, call_back raise 'Sorry,it doesnt look like lambda' unless call_back.is_a? Proc # Do the job call_back.call('Status: Done') end end processor = AsyncProcessor.new processor.do_async_job("long task",lambda{|result| puts result})

12) Date Formatting

now = Time.now puts "#{now.year}-#{now.month}-#{now.day}" puts now.strftime("%a %b %d %H:%M:%S")

Ruby

Measuring AppDomain Resource Utilization

6. September 2010

Around a year and half before, I wrote an application which used .Net AppDomains to host background processes and WCF service hosts. One of the motivation was to be able to recycle any AppDomain individually as and when needed. It was on .Net Framework 3.5 and one of the major limitation we faced was inability to measure resource utilized by individual AppDomain. Processor and memory utilization can be monitored for the windows process, but there was no way to know the amount of resources each AppDomain is consuming. If resource consumption at each AppDomain level can be measured, we can have automatic or manual recycle mechanism based on the AppDomain’s health or other criterions like amount of time it is running, number of requests it processed, memory usage, etc. In .Net Framework 4.0 Microsoft added a feature which allows to measure memory and processor time consumption at AppDomain level. I put together a console application, which hosted multiple AppDomains and measured resource consumption for each of them. After looking at running number on console, I thought this need to have better visual representation and I wrote a little WPF application to visualize this data. Following is the resulting application

AppDomainPerfMon

Following is the console application which hosts the AppDomains.

AppDomainPerfMonHoster

Console applicationcation prompts for the number of AppDomains you would like to host. We need to do some processing in the AppDomain, so that we can see some processor and memory utilization. To simulate some work in the AppDomain, a thread is spawned in AppDomain which wakes up after some random amount of time and concatenates random length of string, encrypts and decrypts it. String concatenation results in to large memory use but not much of the CPU usage, so I added encryption and decryption of the string, which flexes the CPU little bit. In the screenshot above you can see a circular gauge indicating processor utilization and two bars indicating total amount of memory allocated since the AppDomain was created and second bar indicating the amount of memory survived after the CLR garbage collection. In the screenshot you can see the survived memory is 0 most of the time because our processing is happening in a method which doesn't hold any object references outside the context of the method.

Monitoring the AppDomain resource utilization is enabled through a static property exposed through AppDomain class.

   1: AppDomain.MonitoringIsEnabled = true;   

Once the monitoring is enables, you can collect the AppDomains resource utilization through following AppDomain instance properties.

   1: healthData.TotalProcessorTime = this.AppDomain.MonitoringTotalProcessorTime;
   2: healthData.TotalAllocatedMemorySize = this.AppDomain.MonitoringTotalAllocatedMemorySize;
   3: healthData.SurvivedMemorySize = this.AppDomain.MonitoringSurvivedMemorySize;

Following is the brief explanation about available properties

1) MonitoringTotalAllocatedMemorySize: All memory(in bytes) allocation that have been made for this AppDomain since it has been created. This will help to know how memory intensive is your processing.

2) MonitoringSurvivedMemorySize: Memory(in bytes) survived after the GC cycle and currently being used by your AppDomain.

3) MonitoringTotalProcessorTime: This is the total time each thread in the process spent executing in that application domain. You need to consider the number of cores on the machine while calculating the processor utilization based on this time. 

4) MonitoringSurvivedProcessMemorySize: Memory(in bytes) survived after the GC cycle and currently being used by all AppDomains in the process. I am not using this property in the sample application as I am measuring it at AppDomain level.

Please note that these properties requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. So, please run this application or visual studio as an administrator.

As you can see, measuring the resources at AppDomain level is very straight forward. However, I ended up spending some time in creating the infrastructure which can gather the data and publishes to the external applications. I created a health broadcaster WCF service with duplex channel, any interested application can subscribe for the health data by calling ‘SubscribeToHealthBroadcast’ operation. The calling application needs to host the callback contract ‘IHealthBroadcastListener’. The application broadcasts health data to each subscriber at configured interval. I created two simple WPF control to visualize the health data Gauge and Equalizer control. Please note that I wrote these controls only for this application, so they might not be fully mature or reusable.

You can download the complete source code from following link. Please let me know if you have any questions or suggestions.



.Net, .net 4.0, M-V-VM, WPF , ,

Creating WCF Service Extensibility through MEF (Managed Extensibility Framework)

6. September 2010

Recently I was working on an application integration design wherein I wanted to expose service operations as extensibility points. By opening up the service operations for extensibility I wanted to create a simple message bus which can be tapped in to for application integration needs without making any changes to the existing implementation. The extensibility point will expose the operations of service to other components which will get chance to act upon service requests.

I considered few design approaches to accomplish this, however I found most of the approaches to be intrusive to existing implementation. I was looking for something which will be loosely coupled to the existing service implementation and really be like plug-and-play, without much code changes.

First obvious thought was to look at IoC(Inversion of Control) and DI(Dependency Injection) along with WCF extensibility points. After looking all the available WCF extensibility points it was easy to zero down on Parameter Inspector (IParameterInspector) as it gives access to the operation name and parameters. If we know the operation being called along with parameters and all the extensions implemented for that specific service, it would be just matter of loading the extensions and calling the operation.

When you look at IoC/DI space there are few seemingly overlapping options from Microsoft itself, like Unity application block from P&P, Managed add-in framework (MAF) in System.AddIn namespace and the latest entrant Managed Extensibility Framework(MEF). At high level, all of these are composition engines, however MEF looked like specialized IoC container with added bells and whistles around DI. MEF is optimized around ‘discovery of unknown parts’ rather than just ‘registration of known parts’, this is what made MEF an interesting option for the problem I was trying to solve.  Another consideration was that MEF is bundled with .Net Framework 4.0, so no more libraries to update and move around. There is a nice post about Ten Reasons to use the Managed Extensibility Framework.

After little bit playing around with MEF, following looked like the emerging pattern for the problem I was trying to solve.


 WCFandMEF


I defined an attribute(named ‘ServiceOperationExtensibility’) which implements IOperationBehavior interface and adds IParameterInspector DispatchBehavior. This attribute can be applied to an operation which needs to be exposed as extensibility point as shown below.

   1: [OperationContract]
   2: [ServiceOperationExtensibility]
   3: string OperationA(int param1, string param2);

A class implementing IParameterInspector (named ‘ExtensibilityInspector’) will accept the service contract type as constructor parameter.

   1: ExtensibilityInspector extensibilityInspector = new ExtensibilityInspector(operationDescription.DeclaringContract.ContractType);
   2: dispatchOperation.ParameterInspectors.Add(extensibilityInspector);

The ExtensibilityInspector simply gets instance of ExtensibilityManager and passes the service contract type, operation name and arguments in ‘BeforeCall’ method of IParameterInspector interface.

   1: public object BeforeCall(string operationName, object[] inputs)
   2: {
   3:     ExtensibilityManager.Instance.InvokeExtension(this.ServiceContractType, operationName, inputs);
   4:     return null;
   5: }

The ExtensibilityManager is responsible for discovering and loading the extension components and calling the operation. The extension components needs to implement contract of service being extended. The component need to decorate the class with MEF ‘Export’ attribute, this attribute would allow it to be discovered by MEF catalog.

   1: [Export(typeof(ProductService.IProductService))]
   2: public class ProductServiceExtension1:ProductService.IProductService
   3: {
   4:     //Implementation removed for brevity
   5: }

The ExtensibilityManager creates MEF catalog from assemblies present in designated directory. So the extension components need to be simply dropped in to designated directory(I have named this directory ‘Extensions’).

   1: private void Compose()
   2: {
   3:     var Catalog = new AggregateCatalog();
   4:     Catalog.Catalogs.Add(new DirectoryCatalog(@".\Extensions"));
   5:     this.Container = new CompositionContainer(Catalog);
   6:     this.Container.ComposeParts(this);            
   7: }

InvokeExtension method of ExtensibilityManager created instance of MEF ImportDefinition based on the passed service contract type. It calls TryGetExports method on the previously created container to get all the extensions of specific type.

   1: public void InvokeExtension(Type contractType, string operationName,object[] arguments)
   2: {
   3:     ImportDefinition importDefinition = new ImportDefinition(i => i.ContractName.Equals(contractType.FullName), contractType.FullName, ImportCardinality.ZeroOrMore, false, false);
   4:     AtomicComposition atomicComposition = new AtomicComposition();
   5:     IEnumerable<Export> extensions = null;
   6:  
   7:     bool exportDiscovery = this.Container.TryGetExports(importDefinition, atomicComposition, out extensions);
   8:     
   9:     if (extensions != null && extensions.Count<Export>() > 0)
  10:     {
  11:         foreach (Export extensionExport in extensions)
  12:         {
  13:             //ToDo: spawn a thread and do work there instead of doing it on the calling thread
  14:             contractType.InvokeMember(operationName, System.Reflection.BindingFlags.InvokeMethod, null, extensionExport.Value, arguments);
  15:         }
  16:     }
  17: }

After getting the extensions, we can invoke the operation on each of the extension components. Please note that in this sample I have directly called InvokeMember operation on the type instance, in production code you will spawn a thread instead of doing it on the calling thread.

Overall this turned out to be a good solution, though there is a space for improvement to make it more fault tolerant and scalable. Depending upon your scenario you need to build good security around the extensibility points and components, which I have completely omitted here.

The sample code can be downloaded from following link. The sample service(named ‘IProductService’) is hosted in IIS, you can use WCFTestClient to invoke the operations. I have added one extension component in the solution which simply writes an entry to windows event log on invocation of the operation.



WCF, MEF , ,

Object to Object Mapping

18. February 2010

Have you ever found yourself wasting time mapping your entity objects to DTOs (Data Transfer Objects)? You will frequently encounter this scenario if you are building your application with some degree of service orientation. It is also common occurrence if you are using UI patterns live MVC, MVP or MVVM, where you would like to pass simpler, binding-friendly version of domain entities. I came across this nice utility called AutoMapper on codeplex. AutoMapper is like Swiss Armey Knife for object to object mapping, it provides features to perform simple naming convention based mapping to complex, configuration driven mapping. It also provides methods to easily translate your collection across around a dozen various collection types. Following sample shows the simple object to object mapping.

   1: public class Order
   2: {
   3:     private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();
   4:  
   5:     public Customer Customer { get; set; }
   6:  
   7:     public OrderLineItem[] GetOrderLineItems()
   8:     {
   9:         return _orderLineItems.ToArray();
  10:     }
  11:  
  12:     public void AddOrderLineItem(Product product, int quantity)
  13:     {
  14:         _orderLineItems.Add(new OrderLineItem(product, quantity));
  15:     }
  16:  
  17:     public decimal GetTotal()
  18:     {
  19:         return _orderLineItems.Sum(li => li.GetTotal());
  20:     }
  21: }
  22:  
  23: public class Product
  24: {
  25:     public decimal Price { get; set; }
  26:     public string Name { get; set; }
  27: }
  28:  
  29: public class OrderLineItem
  30: {
  31:     public OrderLineItem(Product product, int quantity)
  32:     {
  33:         Product = product;
  34:         Quantity = quantity;
  35:     }
  36:  
  37:     public Product Product { get; private set; }
  38:     public int Quantity { get; private set; }
  39:  
  40:     public decimal GetTotal()
  41:     {
  42:         return Quantity * Product.Price;
  43:     }
  44: }
  45:  
  46: public class Customer
  47: {
  48:     public string Name { get; set; }
  49: }
  50:  
  51: public class OrderDto
  52: {
  53:     public string CustomerName { get; set; }
  54:     public decimal Total { get; set; }
  55: }
  56:  
  57: [TestFixture]
  58: public class Flattening
  59: {
  60:     [SetUp]
  61:     public void SetUp()
  62:     {
  63:         Mapper.Reset();
  64:     }
  65:  
  66:     [Test]
  67:     public void Example()
  68:     {
  69:         // Complex model
  70:         var customer = new Customer
  71:             {
  72:                 Name = "George Costanza"
  73:             };
  74:         var order = new Order
  75:             {
  76:                 Customer = customer
  77:             };
  78:         var bosco = new Product
  79:             {
  80:                 Name = "Bosco",
  81:                 Price = 4.99m
  82:             };
  83:         order.AddOrderLineItem(bosco, 15);
  84:  
  85:         // Configure AutoMapper
  86:         Mapper.CreateMap<Order, OrderDto>();
  87:  
  88:         // Perform mapping
  89:         OrderDto dto = Mapper.Map<Order, OrderDto>(order);
  90:  
  91:         dto.CustomerName.ShouldEqual("George Costanza");
  92:         dto.Total.ShouldEqual(74.85m);
  93:     }
  94: }


.Net, Tools ,

ASP.Net MVC Page Life Cycle

13. February 2010

ASP.Net MVC is carefully crafted piece of software. ASP.Net MVC offers good amount of flexibility and number of extensibility points in addition to other advantages. I was looking for ASP.Net MVC page life cycle in pictorial format, however I couldn't find any on the internet. I decided to prepare one my self and following is the result. I have captured ASP.Net MVC page life cycle in 13 steps. I have tried to depict maximum amount of details to precisely reveal inner working of ASP.Net MVC. Please post comments if you have any questions, ASP.Net MVC is an interesting topic to discuss.

Asp.Net MVC Page Life Cycle



ASP.Net MVC, ASP.Net

Design by Contract (DbC) and .Net 4.0 Code Contracts

31. January 2010

After spending years developing software which collaborates with many other sub-systems, I have subconsciously developed affection for Design by Contract (DbC). When various system/ sub-systems are designed to communicating over SOAP or similar protocol through well defined data contacts, a degree of discipline is generally enforced by the development framework.  However, when we are designing a set of sub-systems which is Intend to communicate through in-process calls, it is very easy to violate clean-contract principle. It’s not that things are not going to work if contracts are not clearly defined, but it makes it very easy to maintain and troubleshoot in long run. Following is the formal definition of the Design by Contract (DbC) from Wikipedia entry.


Design by Contract (DbC) or Programming by Contract is an approach to designing computer software. It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, post conditions and invariants.

So when I was going through the list of new features in .Net 4.0, Code Contract immediately caught my attention. In pre-4.0 versions of .Net, assertion is the feature we can use to express our design intent about the rules object needs to follow. However, it was more like developer’s internal sanity check. There is no way to expose these assertions to consumer of your library or performing any static or runtime analysis to see if any of the code is violating it. .Net 4.0 Code Contract will help to fill this vacuum.

We can think of .Net Code Contracts as ‘Assertions on steroids’. However, the set of tools built around it makes Code Contract very compelling. Code Contract resides in System.Diagnostics.Contracts namespace.  Currently, Code Contract is a separate download, you can download it from Microsoft DevLabs. It comes with dlls, documentation and samples in addition to Code Contract property pane for Visual Studio.  I am using Visual Studio 2010, Beta 2 but Code Contract works well with Visual Studio 2008 too. If you are running on .Net Framework 3.0/3.5, you need to add reference to Microsoft.Contracts.dll. If you are powered by .Net Framework 4.0 you need not worry as Code Contracts are bundled with mscodelib.dll (still you need to install the Code Contracts from DevLabs to get the property pane in Visual Studio). Following screenshot shows the Code Contract property pane you can use to configure various Code Contract related features.

CodeContractPropertiesPane

Following are three major flavors of the Code Contracts.

Method Contracts
It helps to express method level contracts which callers need to adhere to, in return methods can also promise to hold on to the result. Contract.Requires is used to impose condition on the method arguments (pre-condition). Whereas Contract.Ensure is used to define methods exit condition (post-condition).  You can use any code expression with Contract.Requires and Contract.Ensure which can yield Boolean.

Following is the simple example showing method contracts. I have used contract to ensure the order amount is greater than 0 and connection is open on method call ProcessOrders. I also imposed a condition on this method that the return value must be greater than or equal to 0.

   1: public int ProcessOrders(int minimumOrderAmount)
   2: {           
   3:     Contract.Requires(minimumOrderAmount > 0, "Minimum order amount must be greater than 0.");
   4:     Contract.Requires(DataProvider.IsConnectionOpen);
   5:     //Order processing logic will go here
   6:     Contract.Ensures(Contract.Result<int>() >= 0);
   7:     return 1; //dummy result
   8: }


Object Invariant
Object invariants can be used to express the conditions under which the object is in a "good" state. Object invariant conditions are applied to each instance of the class. During runtime checking, invariants are checked at the end of each public method. Object invariants need to be defined in instance method decorated with ContractInvariantMethod attribute. The invariant methods need to return void and could not contain code other than calls to Contract.

Following code snippet shows example of object invariant contract. As per this contract, the object of type DataProcessor can never have the dataProvider as null and dataProvider’s connection status as closed.

   1: [ContractInvariantMethod]
   2: void ObjectInvariant()
   3: {
   4:    Contract.Invariant(this.m_dataProvider != null );
   5:    Contract.Invariant(this.m_dataProvider.IsConnectionOpen);
   6: }

 
Interface Contract
Interface contract can be defined at the interface level and all the classes implementing that interface will have to abide by that contract. As .Net doesn’t allow to have any implementation code in interface definition, we need to define a separate class implementing that interface to define the code contracts. This class needs to be decorated with ContractClassFor attribute. Code Contract expects the interface to be implemented explicitly to avoid any ambiguity.

Following code snippet shows the interface contract for our sample interface IDataProvider. Please notice how the default is used to return some value to fulfill interface requirement.

   1: public interface IDataProvider
   2: {
   3:     bool IsConnectionOpen{get;}       
   4:     List<Tuple<int, string, string, string>> GetOrders(DateTime orderDate);
   5:     void AddOrders(List<Tuple<int, string, string, string>> orders);
   6: }
   7:  
   8: [ContractClassFor(typeof(IDataProvider))]
   9: sealed class IDataProviderContract : IDataProvider
  10: {
  11:     bool IDataProvider.IsConnectionOpen
  12:     {
  13:         get { return false; } //dummy return
  14:     }
  15:  
  16:     List<Tuple<int, string, string, string>> IDataProvider.GetOrders(DateTime orderDate)
  17:     {
  18:         Contract.Requires(orderDate < DateTime.Now);
  19:         Contract.Ensures(Contract.Result<List<Tuple<int, string, string, string>>>() != null && Contract.Result<List<Tuple<int, string, string, string>>>().Count > 0);
  20:         return default(List<Tuple<int, string, string, string>>); //dummy return
  21:     }
  22:  
  23:     void IDataProvider.AddOrders(List<Tuple<int, string, string, string>> orders)
  24:     {
  25:         Contract.Requires(orders != null && orders.Count > 0);
  26:     }
  27: }


Following screenshot shows static analysis failures and warnings in Visual Studio.

CodeContractErrorsAndWarnings 

Following screenshot shows the runtime code contract violation exception.

AssertFailure 

Now as we have developed a bulletproof object API using Code Contracts, we need to put together extensive unit test cases to ensure nothing goes untested. We can use Microsoft DevLab’s Pex (Program EXploration) to generate ‘parameterized’ unit tests. You can download Pex from here. Following is the definition of parameterized unit test.


A parameterized unit test is simply a method that takes parameters, calls the code under test, and states assertions. Given a parameterized unit test written in a .NET language, Pex automatically produces a small unit test suite with high code and assertion coverage. To do so, Pex performs a systematic white box program analysis.

Pex will require a blog post of its own to cover all the aspects. Following is just a brief outline of how it can be used with Code Contracts.

Following screenshot shows Pex Explorer with various parameterized unit tests identified for our test project.

PexExplorer

Following screenshot shows the Pex test execution result. You can see that Pex executed 3 tests on our XMLDataProvider constructor which accepts string as a parameter. First unit test passes null parameter to our constructor, second passes the empty string and third passes some random string.

PeXExplorerResult
You can even save these unit tests as a project in the unit testing framework of your choise. Following screenshot shows various unit testing frameworks currently supported by Pex.

PexTestFrameworkSelector 
You can generate your code documentation using Sandcastle, however you need to patch the Sandcastle to create section for contracts. Code Contract download provides set of XSL which you need to copy to Sandcastle directory.

I hope you enjoyed this post. You can leave comments for your feedback.



.net 4.0

Inside Extension Methods: Compiler to IL

24. January 2010

Extension Methods is a nice feature introduced in .Net Framework 3.5, it opens up lots of possibilities including LINQ. Even after reading short description of this feature anyone can guess that Extension method is simply syntactic sugar. It doesn't in any way modify the type that is being extended nor it can access private members, nor is the extension method returned when reflecting the extended type. I decided to dig little dipper to see how compiler is achieving this feature. First I will scratch the surface and look at the IL then we will dig in to the compiler. I don’t have access to Microsoft CS compiler source, so I will use Mono CS compiler (mcs) to investigate Extension method implementation.

Following is the very simple extension method, notice the use of ‘this’ as a first argument to indicate this is as extension method to compiler.

   1: public static int WordCount(this String str)
   2: {
   3:     return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
   4: }

And here is how this extension method is being used.

   1: string statement = "Hey this is a test";
   2: Console.WriteLine("Word Count = " + statement.WordCount().ToString());

Following is the partial IL of extension method.

   1: .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
   2: .method public hidebysig static int32 WordCount(string str) cil managed
   3: {
   4:    .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
   5:    .maxstack 4
   6:    .locals init (
   7:        [0] int32 statement)
   8:    L_0000: nop 

Following is the IL of the code which uses extension method

   1: L_000d: call int32 ExtMethods.MyExtensions::WordCount(string)

You can notice in the extension method IL that compiler has removed ‘this’ argument and decorated the method with System.Runtime.CompilerServices.ExtensionAttribute attribute. In the IL of the code which used extension method, you can see that method is invoked as a regular static method.

Now let’s dig in to the compiler (mcs – Mono CSharp compiler). You can see following Emit method, which will be called for each method in the type. The flag Modifiers.METHOD_EXTENSION is set if the methods first argument is of type ‘this’.  The compiler will emit the System.Runtime.CompilerServices.ExtensionAttribute attribute when this flag is set.

   1: public override void Emit ()
   2: {
   3:     base.Emit ();
   4:  
   5:     if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
   6:         PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
   7: }

Now let’s look at the extension method resolution mechanism. Following code shows the part of ComputeNamespaces method. It calls RegisterExtensionMethodClass method, which in turn registers type exposing extension method in the Namespace object by calling RegisterExternalExtensionMethodClass. This method add the type exposing extension method to arraylist named external_exmethod_classes.

   1: foreach (Type t in assembly.GetTypes ()) {
   2: if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
   3:  contains_extension_methods && t.IsDefined (extensionType, false))
   4:  RegisterExtensionMethodClass (t);

The DoResolve method of Mono.CSharp.Invocation contains following logic to resolve the method invocation call. As a last step of method resolution it tries to find extension method for the targeted type.

   1: mg = ec.LookupExtensionMethod (me.Type, me.Name, loc);
   2: if (mg == null) {
   3:     ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
   4:         expr_resolved.GetSignatureForError ());
   5:     return null;
   6: }
   7:  
   8: ((ExtensionMethodGroupExpr)mg).ExtensionExpression = me.InstanceExpression;

I hope you found this quick detour to Mono compiler interesting.



.Net, Mono ,

Touching the Moonlight

23. January 2010

From long time I was curious about Moonlight (in case you need help to recollect - Moonlight is open source implementation of Silverlight, primarily for Linux and other Unix/X11 based OS). Moonlight 2 was released December 17, 2009, which is largely compatible with Silverlight 2.0. Moonlight 2.0 also contains few of the Silverlight 3.0 features. So, if you try to run Silverlight 3.0 compiled application with Moonlight 2.0 runtime, it gives ‘potential incompatibility’ warning, but goes ahead and executes it.

I decided to try Moonlight myself. I choose SUSE Linux as it looked promising to create a custom distro. SUSE Studio offers lots of development tools including Mono, MonoDevelop, Apache, PHP, etc. which you can include in the distro. Setting up a development environment on Linux for a fulltime Windows guy/gal might be a laborious task. I decided to use Sun’s VirtualBox to run SUSE Linux on my Windows 7 machine. In past, I used VirtualBox to host Windows 7 on my Windows Server 2008 machine and it worked really well.

I created a Silverlight application, threw in few basic controls and hosted it on IIS 7. Now, I can access my Silverlight 3.0 application from SUSE Linux through Mozilla Firefox browser. You can see Silverlight & Moonlight running in Windows and Linux side by side in following screenshot. In future posts I will explore Moonlight implementation details. If you find this interesting, please subscribe to my blog feed .

TouchingMoonlight



Silverlight, Moonlight, Linux , ,

Experiments with F# + WPF + M-V-VM

22. January 2010

In last few days I was thinking about what this new decade is going to bring to software development. I feel we will experience more rapid pace of technological changes and how we do things in this decade. Just look around and you can see things like cloud computing, functional programming, domain specific language and few more on the horizon.

I decided to experiment with functional programming using F#, it is bundled with Visual Studio 2010 (beta 2 as of now).  I did not come across many UI applications done using F# and WPF, so I decided to do one. Following screenshot shows outcome of this exercise.

BingSearch_5 
It simply uses Bing API’s OpenSearch compliant RSS interface for querying the web and image search result for the user specified term. The web and image search results are displayed on different tabs. The Bing API’s RSS interface doesn’t require any registration or application id.
There are so many new programming constructs available in F# that it takes a little time to get up-to-speed with what's available and how it can be used. This sample might not demonstrate the most elegant way of doing functional programming, I hope to cover that in future posts.

I have employed M-V-VM pattern for presentation and logic separation. Views are done using WPF/ XAML , the view model is written in F# while the Bing API provides the data. I have clubbed the Bing API interaction logic with the view model. I have used WPF Toolkit’s DelegateCommand to handle commands from the views. Instead of referencing the complete WPF MVVM Toolkit, I have simply added couple of required classes from it in a separate project which is referenced by F# view model project. Following are the classes present in the view model, name of the classes are descriptive enough to indicate the role it plays.

Bing_Classes 
I use System.Net.WebRequest to get the RSS XML from the Bing API asynchronously. Following code snippet shows the F# code to do this

   1: async{ let request = WebRequest.Create uri
   2:        use! response = request.AsyncGetResponse()    
   3:        use stream = response.GetResponseStream()
   4:        use reader = new StreamReader(stream)
   5:        let lines = [ while not reader.EndOfStream do yield reader.ReadLine() ]
   6:        return lines } 

 
Concurrency is going to be the next major revolution in how we write the software.  Though Moore’s Law is not over yet, we will have to prepare ourselves to take advantage of multi-core processors. Designers of new languages like F# do consider this upcoming trend and provides constructs to parallelize the computation and I/O operations. Following code snippet shows how the code shown above is executed parallelly using Async.Parallel construct against a for loop.

   1: member se.Search(searchTerm:string)= 
   2:         async{  let searchAPIUrls = new List<string>()
   3:                 searchAPIUrls.Add("http://api.search.live.com/rss.aspx?source=web&query=" + searchTerm)
   4:                 searchAPIUrls.Add("http://api.search.live.com/rss.aspx?source=image&query=" + searchTerm)
   5:                 let webResponses = 
   6:                     Async.Parallel [for site in searchAPIUrls -> GetWebResponse site ]
   7:                     |> Async.RunSynchronously
   8:  
   9:                 let rssParser = RSSParser()
  10:                 let results = new Dictionary<WebSearchType,ObservableCollection<RSSItem>>()
  11:                 let tempResults = new List<string>()
  12:                 for str in webResponses do
  13:                     tempResults.Add(str.Item(0))
  14:  
  15:                 let mutable items = ObservableCollection<RSSItem>()
  16:                 
  17:                 items <- rssParser.Parse tempResults.[0]     
  18:                 results.Add(WebSearchType.Web,items)
  19:  
  20:                 items <- rssParser.Parse tempResults.[1]     
  21:                 results.Add(WebSearchType.Image,items)
  22:                 
  23:                 return results}

The code for this sample application can be downloaded from here

I would be happy to hear your comments on this.

Technorati Tags: ,,



F#, M-V-VM, WPF , ,