DarioSantarelli.Blog(this);

Archive for the ‘Programming’ Category

ASP.NET SignalR and Ext.NET MessageBus

Posted by dariosantarelli on October 20, 2013


Most of the modern web applications provides real-time functionalities (“real-time web“) through a set of technologies and practices that enable users to receive information as soon as it is published by its authors, rather than requiring that they or their software check a source periodically for updates.  Moreover, in very scalable and complex architectures, server-side code execution is often asynchronous. Just for example, let’s think to a task-based UI which submits a command like “book a plane ticket” to a web service. The server-side command processing could be performed after some hours: for example, the command could be just enqueued to a command-bus to be processed later. In scenarios like that, the client can’t count on an updated read model just after sending the command. As a consequence, in order to receive a feedback as soon as possible, all the involved clients should poll the server until the command execution reaches a significant state (e.g. in progress, completed, canceled etc.) and the read model is updated, ready for queries.

Before WebSockets, the classic implementations of this kind of real-time features were not so easy and they used to adopt strategies like forever frame (see “Comet“) or periodic/long polling. Today, all the modern browsers and web servers fully support WebSockets and they can extabilish bi-directional and persistent communications, so that a client can receive content through a “push” action performed by the server. In the ASP.NET world, SignalR is a growing new library that uses WebSockets under the covers when it’s available, and gracefully fallbacks to other techniques and technologies when it isn’t, while the application code stays the same. SignalR also provides a very simple, high-level API for doing server-to-client RPC (call JavaScript functions in clients’ browsers from server-side code) in an ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

Developers that are currently using the Ext.NET component framework can take advantage on SignalR by combining it with the Ext.NET MessageBus component. The MessageBus provides a simple and robust client-side infrastructure to propagate notifications to listening UI components. The reference scenario I’m talking about in this post is represented in the figure below:


1. The client browser extabilishes a persistent connection to a server-side SignalR application hub. After that the client mantains a reference to an auto-generated hub proxy.
2. The Ext.NET UI components submits commands to the server.
3. At any time of the server-side command execution, the server can use the SignalR hub to push notification messages back to all the involved clients via RPC.
4. Any client receiving a SignalR message through the hub proxy redirects the message to the Ext.NET Message Bus
5. On the basis of the specific type of message, the Ext.NET UI components are updated through a message handler function. In fact, each Ext.NET component has a MessageBusListeners property (client side handlers of MessageBus client side events) and a MessageBusDirectEvents property (server side handlers of MessageBus client side events).

Let’s have a look to a minimalistic example implemented in an ASP.NET MVC web application. Here’s the view :

@using Ext.Net;
@using Ext.Net.MVC;
@{
    Layout = null;
    var X = Html.X();
}
<!DOCTYPE html>
<html>
    <head>        
        <title>SignalR and Ext.NET MessageBus example</title>
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jquery.signalR")
        <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
    </head>
<body>
@(X.ResourceManager())
@(X.Viewport().Padding(20).Items()

.Add(X.Button().Icon(Icon.Add).Text("New customer")
      .DirectClickAction("AddCustomer", "Customers")) 

.Add(X.Button().Icon(Icon.Delete).Text("Delete customer")
      .DirectClickAction("DeleteCustomer", "Customers"))

.Add(X.GridPanel().Title("Customers").MarginSpec("10 0 0 0").Icon(Icon.User)
      .Store(X.Store()
              .AutoLoad(true)
              .Proxy(X.AjaxProxy().Url("/customers/all").Reader(X.JsonReader()))
              .Model(X.Model()
                      .Fields(fields =>
                      {
                        fields.Add(X.ModelField().Name("Id"));
                        fields.Add(X.ModelField().Name("Name"));
                        fields.Add(X.ModelField().Name("Surname"));
                        fields.Add(X.ModelField().Name("Email"));
                      })))
              .ColumnModel(columnModel =>
              {
                columnModel.Columns.Add(X.Column().Text("Name").DataIndex("Name").Flex(1));
                columnModel.Columns.Add(X.Column().Text("Surname").DataIndex("Surname").Flex(1));
                columnModel.Columns.Add(X.Column().Text("Email").DataIndex("Email").Flex(1));
              })
              .MessageBusListeners(new MessageBusListener 
              {   
                 Name = "Customers.*",
                 Handler = "this.getStore().reload();",
                 Buffer = 500
              }))

.Add(X.GridPanel().Title("Events log").MarginSpec("10 0 0 0").Icon(Icon.Report)
      .Store(X.Store()
      .Model(X.Model()
              .Fields(fields =>
                          {
                              fields.Add(X.ModelField().Name("EventId"));
                              fields.Add(X.ModelField().Name("DateTime"));
                              fields.Add(X.ModelField().Name("Name"));
                              fields.Add(X.ModelField().Name("Data"));
                          })))
                    .ColumnModel(columnModel =>
                    {
                        columnModel.Columns.Add(X.Column().Text("EventId").DataIndex("EventId").Flex(1));
                        columnModel.Columns.Add(X.Column().Text("DateTime").DataIndex("DateTime").Flex(1));
                        columnModel.Columns.Add(X.Column().Text("Event name").DataIndex("Name").Flex(1));
                        columnModel.Columns.Add(X.Column().Text("Event data").DataIndex("Data").Flex(1));
                    })
                    .MessageBusListeners(new MessageBusListener
                    {
                        Name = "Customers.*",
                        Handler = "this.getStore().add({ EventId: data.Id, DateTime: getFormattedDateTime(), 
                                   Name: name, Data: \"CustomerId: \" + data.CustomerId });"
})))
<script type="text/javascript">      
var loadHub = function () {
    var hubProxy = $.connection.applicationHub;
    hubProxy.client.publish = function (name, message) {
        Ext.net.Bus.publish(name, message);
    };
    $.connection.hub.start().done(function () {
        Ext.net.Notification.show({
            title: "Info",
            iconCls: "#Accept",
            html: "SignalR connection is active!"
        });
    });
};

$(document).ready(function () {
    loadHub();
});

</script>    
</body>
</html>

As you can see, the view is composed by the following Ext.NET components:

– A couple of buttons which send commands to the server (e.g. Add/Remove a customer)
– A grid panel which holds the current customer data
– A grid panel which holds trace data about messages received through the SignalR connection.

The integration between the client-side SignalR hub proxy and the Ext.NET components MessageBus is done through the loadHub javascript function: it wraps the SignalR hub named “applicationHub” so that all the received messages are redirected to the Ext.NET MessageBus and again to the listening UI components. Please note that the SignalR “publish” function and the Ext.NET MessageBus “publish” function accept the same parameters: the message name and the message data. For this reason, the integration between the two worlds is practically natural.

In the example above, the Store of the former GridPanel is reloaded each time its MessageBusListener intercepts any message whose name starts with the prefix “Customers.” . Please pay attention to the Buffer property: it’s very useful when the component is under message storming and we want the UI to be refreshed just after a specified delay during which no messages have been received.

What about server-side code? Well, the server-side code is not so relevant in this post. The most important thing to be considered here is that at some point of the server-side command execution, the code retrieves the SignalR hub, selects which clients will receive the RPC (for simplicity, in this example a message is sent to all connected clients) and finally pushes a message containing the data the client needs for updating UI. Here an example:

GlobalHost.ConnectionManager.GetHubContext<ApplicationHub>()
          .Clients.All.publish("Customers.Added", new CustomerAdded { ...<data for clients>... });

Useful links

Advertisements

Posted in .NET Framework, AJAX, ASP.NET, ASP.NET MVC, C#, Microsoft Technology, Programming, Web Development | Tagged: , , , , , , , | 1 Comment »

Two new projects released!

Posted by dariosantarelli on March 22, 2013


I’ve just published two new projects I’ve worked on in the last months:

LogLive

LogLive is free software for Windows written in .NET (WPF 4) that enables you to perform real-time monitoring on different types of log sources through components called “listeners”.

TextTableFormatter.NET

TextTableFormatter is a .NET porting of Java TextTableFormatter.
This library renders tables made of characters. The user add cells and can add format characteristics like predefined/custom table styles, text alignment, abbreviation, column width, border types, colspan, etc.

In the next months I will publish other projects, so please stay tuned! 🙂

Posted in .NET Framework, About Me..., Microsoft Technology, Programming, WPF | Leave a Comment »

C# dynamic dispatch and class inheritance

Posted by dariosantarelli on December 8, 2012


I believe dynamic dispatch is a very cool feature of C# 4.0. It was designed to simplify interop between statically typed C# and dynamically typed languages or COM components by deferring method resolution at runtime, dynamically applying the same overload selection logic that the C# compiler would normally use at compile time. This feature is known as single/multiple dispatch. A common usage of this technique can be found in many implementations of the visitor pattern. Maybe you have already read something like this:

public class MessageHandler
{
    public void HandleMessage(Message message)
    {
        ProcessMessage((dynamic)message);
    }
    protected void ProcessMessage(MessageA messageA)
    {
        Console.WriteLine("MessageA processed");
    }

    protected void ProcessMessage(MessageB messageB)
    {
        Console.WriteLine("MessageB processed");
    }
}

This code works great when you don’t know the exact type beforehand and you don’t want to use a big switch statement. If you use dynamic dispatch within the same class everything should work as expected. So, if you execute the following lines of code..

var messageHandler = new MessageHandler();
messageHandler.HandleMessage(new MessageA());
messageHandler.HandleMessage(new MessageB());

…the console output would be the following:

MessageA processed
MessageB processed

OK, but what happens if you introduce a class derived from MessageHandler in order to separate message handling?

The problem

Let’s suppose to have an DefaultMessageHandler that holds the fallback message handling method and a DerivedMessageHandler which holds methods for some specific messages.

public abstract class Message { }
public class MessageA : Message { }
public class MessageB : Message { }
public class MessageC : Message { }

public class DefaultMessageHandler
{
    public void HandleMessage(Message message)
    {
        ProcessMessage((dynamic)message);
    }

    protected void ProcessMessage(Message message)
    {
        Console.WriteLine("Message processed");
    }

    protected void ProcessMessage(MessageA messageA)
    {
        Console.WriteLine("MessageA processed");
    }
}

public class DerivedMessageHandler : DefaultMessageHandler
{
    protected void ProcessMessage(MessageB messageB)
    {
        Console.WriteLine("MessageB processed");
    }

    protected void ProcessMessage(MessageC messageC)
    {
        Console.WriteLine("MessageC processed");
    }
}

When we try to execute the following lines of code…

var messageHandler = new DerivedMessageHandler();
messageHandler.HandleMessage(new MessageA());
messageHandler.HandleMessage(new MessageB());
messageHandler.HandleMessage(new MessageC());

…the console output is…

MessageA processed
Message processed
Message processed

The problem here is that every call to the ProcessMessage method via dynamic dispatch is linked to the only implementation of the method that is found in the DefaultMessageHandler class, and the ones in the derived classes will never be executed. At first glance, this behaviour could be not so easy to expect.

A simple solution

In order for our code to work as expected we could just override the HandleMessage method in the DerivedMessageHandler class, leaving it exactly the same as the one defined in the base class. As alternative, we could completely move the HandleMessage method to derived classes.

public class DefaultMessageHandler
{
    public virtual void HandleMessage(Message message)
    {
        ProcessMessage((dynamic)message);
    }

    protected void ProcessMessage(Message message)
    {
        Console.WriteLine("Message processed");
    }

    protected void ProcessMessage(MessageA messageA)
    {
        Console.WriteLine("MessageA processed");
    }
}

public class DerivedMessageHandler : DefaultMessageHandler
{
    public override void HandleMessage(Message message)
    {
        ProcessMessage((dynamic)message);
    }

    protected void ProcessMessage(MessageB messageB)
    {
        Console.WriteLine("MessageB processed");
    }

    protected void ProcessMessage(MessageC messageC)
    {
        Console.WriteLine("MessageC processed");
    }
}

Now, if we try to handle specific messages…

var messageHandler = new DerivedMessageHandler();
messageHandler.HandleMessage(new MessageA());
messageHandler.HandleMessage(new MessageB());
messageHandler.HandleMessage(new MessageC());
messageHandler.HandleMessage(new MessageD());

…everything works as expected and the console output is

MessageA processed
MessageB processed
MessageC processed
Message processed // fallback for MessageD

Please note that the fallback overload of the ProcessMessage method has been invoked for MessageD because a specific overload has not been dinamically found by the runtime binder.

Posted in .NET Framework, C#, Microsoft Technology, Programming | Tagged: , , , | 2 Comments »

Unity Interception Extension

Posted by dariosantarelli on September 30, 2012


Starting from Enterprise Library 5.0, Unity supports interception mechanisms which captures the call to an object at invocation time and provides the full implementation of the object through lightweight code generation (ILEmit). It’s something very similar to the aspect-oriented programming (AOP) approach.

However, Unity is NOT an AOP framework implementation for the following reasons:

  • It uses interception to enable only preprocessing behaviors and post-processing behaviors.
  • It does not insert code into methods, although it can create derived classes containing policy pipelines.
  • It does not provide interception for class constructors.

Instance Interception VS Type Interception

With instance interception, when the application resolves the object through the container,

  1. The Unity interception container obtains a new or an existing instance of the object and creates a proxy.
  2. Then it creates the handler pipeline and connects it to the target object before returning a reference to the proxy.
  3. The client then calls methods and sets properties on the proxy as though it were the target object.

Interface interception

With type interception , the container uses a derived class instead of a proxy (it  resembles AOP techniques). Type interception avoids the possible performance penalties of using a proxy object by dynamically deriving a new class from the original class, and inserting calls to the behaviors that make up the pipeline. When the application resolves the required type through the Unity container,

  1. the Unity interception container extension creates the new derived type and passes it, rather than the resolved type, back to the caller.
  2. Because the type passed to the caller derives from the original class, it can be used in the same way as the original class.
  3. The caller simply calls the object, and the derived class will pass the call through the behaviors in the pipeline just as is done when using instance interception.

Type Interception

However, there are some limitations with this approach. It can only be used to intercept public and protected virtual methods, and cannot be used with existing object instances. In general, type interception is most suited to scenarios where you create objects especially to support interception and allow for the flexibility and decoupling provided by policy injection, or when you have mappings in your container for base classes that expose virtual methods.

Interceptors and Behaviors

Unity uses an Interceptor class to specify how interception happens, and an InterceptionBehavior class to describe what to do when an object is intercepted. There are three built-in interceptors in Unity:

  • VirtualMethodInterceptor: a type based interceptor that works by generating a new class on the fly that derives from the target class. It uses dynamic code generation to create a derived class that gets instantiated instead of the original, intercepted class and to hook up the call handlers. Interception only happens on virtual methods. You must set up interception at object creation time and cannot intercept an existing object.
  • InterfaceInterceptor:  an instance interceptor that works by generating a proxy class on the fly for a single interface. It can proxy only one interface on the object. It uses dynamic code generation to create the proxy class. Proxy supports casting to all the interfaces or types of the target object. It only intercepts methods on a single interface. It cannot cast a proxy back to target object’s class or to other interfaces on the target object.
  • TransparentProxyInterceptor: an instance interceptor that uses remoting proxies to do the interception. When the type to intercept is a MarshalByRefObject or when only methods from the type’s implemented interfaces need to be intercepted. The object must either implement an interface or inherit from System.MarshalByRefObject. If the marshal by reference object is not a base class, you can only proxy interface methods. TheTransparentProxy process is much slower than a regular method call.

Interception is based on one or a pipeline of behaviors that describe what to do when an object is intercepted. You can create your own custom behaviors by implementing the IInterceptionBehavior interface. The interception behaviors are added to a pipeline and are called for each invocation of that pipeline, as shown below.

Here an example of interception behavior which intercepts a call to a method and logs some useful info if the call throws an exception internally:

public class ExceptionLoggerInterceptionBehavior : IInterceptionBehavior
{
  private readonly ILogger _logger;
 

  public ExceptionLogInterceptionBehavior(ILogger logger)
  {
    _logger = logger;
  }
 
  public IEnumerable<Type> GetRequiredInterfaces() return Type.EmptyTypes; }

  public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)    
  {
      IMethodReturn result = getNext()(input, getNext);

      if (result.Exception != null)
      {
        _logger.Log(string.Format(“Exception occurred in {0}.\nParameters: {1}\nException: {2},
                               input.MethodBase,
                               string.Join(“,”, input.Inputs.Cast<object>()),
                               result.Exception));
      }
      return result;
  }
 
  public bool WillExecute
  {
    get { return true; }
  }
}

In detail, you must provide an implementation of the two IInterceptionBehavior interface methods, Invoke() and GetRequiredInterfaces(), and set the WillExecute property.

  • The WillExecute property indicate if the behavior perform any operation when invoked. This is used to optimize interception. If the behaviors won’t actually do anything (for example, PIAB where no policies match) then the interception mechanism can be skipped completely.
  • The GetRequiredInterfaces method returns the interfaces required by the behavior for the intercepted objects. The Invoke method execute the behavior processing.
  • The Invoke method has two parameters: input and getNext. The input parameter rapresents the current call to the original method, the getNext parameter is a delegate to execute to get the next delegate in the behavior chain.

Now let’s see an example of usage.  The following code executes a statement that makes my IService implementation raise an ArgumentNullException. This exception will be logged thanks to the ExceptionLoggerInterceptionBehavior registered for my IService interface.

new UnityContainer()
    .AddNewExtension<Interception>()
    .RegisterType<ILogger, ConsoleLogger>()
    .RegisterType<IService, Service>(new Interceptor<InterfaceInterceptor>(),
                                     new InterceptionBehavior<ExceptionLoggingInterceptionBehavior>())
.Resolve<IService>()
.Process(null); // It throws ArgumentNullException!!!

If we open the Console output window we’ll find something like this…

Exception occurred in MyNamespace.Response Process(MyNamespace.Request).
Parameters:
Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: request
at MyNamespace.Service.Process(Request request) in …
at DynamicModule.ns.Wrapped_IService_1cccb54f8a8b4109a353b589ea96c30e.<Process_DelegateImplementation>__0(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)

A first chance exception of type ‘System.ArgumentNullException’ occurred in Unity_ILEmit_InterfaceProxies

Posted in .NET Framework, C#, Microsoft Technology, Programming | Tagged: , , | 1 Comment »

Unity container and the Decorator Pattern

Posted by dariosantarelli on September 12, 2012


In these days I’m using Unity as IoC and DI container in a project. One of the “must-have” features of a modern container is the ability to be configured at runtime, preferably with a  fluent mapping registration interface. Moreover, one of the expected features is the support for decorator or chain object pattern configurations with intuitive code. A simple scenario could be something like this:

public interface IService {}

public class Service : IService {}

public class ServiceDecorator : IService
{
  protected IService DecoratedService { get; private set; }

  public ServiceDecorator(IService service)
  {
    DecoratedService = service;
  }
}

The intent is straightforward and quite common: registering the relationship between the Service and the ServiceDecorator class, so when someone asks for an IService, he gets a Service instance wrapped in a ServiceDecorator instance. Let’s have a look at the most used solutions.

 

Solution 1: Using an InjectionConstructor

Well, configuring the Unity container to support a decorator in the old-fashioned way requires some not so much readable code. In fact, making this work seems a kind of magic.

[TestMethod]
public void UnityContainer_Should_Resolve_The_ServiceDecorator_With_InjectionConstructor()
{
  var container = newUnityContainer();
  container.RegisterType<IService, Service>(“Service”);
  container.RegisterType<IService,ServiceDecorator>(
                new InjectionConstructor(new ResolvedParameter(typeof(IService), “Service”)));
 
  var service = container.Resolve<IService>();
  Assert.IsInstanceOfType(service, typeof(ServiceDecorator));

}

I think the code above is not optimal, because it uses magic strings.  It also has a dangerous disadvantage: changes to the ServiceDecorator constructors will generate runtime instead of compile time errors.

 

Solution 2: Using an InjectionFactory

This is a substantial improvement of the previous solution. It allows to specify a factory function which can use the injected container to explicitly resolve eventual dependencies to decorated/decorator constructors.

[TestMethod]
public void UnityContainer_Should_Resolve_The_ServiceDecorator_With_InjectionFactory()
{
 var container = new UnityContainer();
 Func<IUnityContainer, object> factoryFunc = c => new ServiceDecorator(new Service(
       // Here you can use the container to resolve further dependencies…
 ));

 container.RegisterType<IService>(new InjectionFactory(factoryFunc));

 var service = container.Resolve<IService>();
 Assert.IsInstanceOfType(service, typeof(ServiceDecorator));
}

The downside is that code still needs updating every time a new constructor parameter is added to Service or ServiceDecorator class. But now we have three noticeable advantages:

  • code is much easier to understand
  • only a single registration into the container is required
  • changes to the constructors will generate compile time instead of runtime errors.

 

Solution 3: Using a custom Unity Container Extension

You can use a container extension like this DecoratorContainerExtension in order to use the same convention available for example in the Castle Windsor container:

[TestMethod]
public void UnityContainer_Should_Resolve_The_ServiceDecorator_With_DecoratorContainerExtension()
{
  var container = new UnityContainer();
  container.AddNewExtension<DecoratorContainerExtension>();
  container.RegisterType<IService, ServiceDecorator>();
  container.RegisterType<IService, Service>(); 
 
  var service = container.Resolve<IService>();
  Assert.IsInstanceOfType(service, typeof(ServiceDecorator));
}

This is absolutely my favourite solution.  It’s less code, and most importantly it describes the intent in a better way, because it’s focused on the developer’s object model and not the on the Unity’s one.

Posted in .NET Framework, C#, Microsoft Technology, Programming | Tagged: , , | Leave a Comment »

Experimenting with Ext.NET support for Razor: a GridPanel with AJAX proxy

Posted by dariosantarelli on June 2, 2012


In these days I’m having fun experimenting the Razor View Engine support introduced in Ext.NET v.2.0 (Beta3 at the time of writing) and I’m appreciating how fluently you can configure any Ext.NET component. Nowadays there isn’t a good documentation about these new features (on Ext.NET official site you can read “Server-side Ext.NET API documentation is being worked on”) so if you want more info about Razor support please have a look at the Ext.NET official forum (I’ve found this thread particularly helpful!). Moreover, in the Ext.NET Examples Explorer you can try to get the necessary knowledge for translating WebForms code examples into Razor views.
In this post I’d like to show one of my first tests: a simple GridPanel supporting server-side data paging via AJAX proxy.
Here the interesting Razor syntax:

@Html.X().ResourceManager()
@(Html.X().GridPanel()
        .Title("Customers")
        .Store(store => store.Add(Html.X().Store()
            .AutoLoad(true)
            .RemoteSort(false)
            .IsPagingStore(true)
            .RemotePaging(true)
            .PageSize(20)
            .Proxy(proxy => proxy.Add(Html.X().AjaxProxy()
                            .Url("/Customers/GetCustomers")
                            .Reader(reader => reader.Add(Html.X().JsonReader()
                                                                   .Root("data")
                                                                   .TotalProperty("total")
                                                                   .IDProperty("CustomerID")))))
            .Model(model => model.Add(Html.X().Model()
                        .Fields(fields =>
                        {
                            fields.Add(Html.X().ModelField().Name("CustomerID"));
                            fields.Add(Html.X().ModelField().Name("ContactName"));
                            fields.Add(Html.X().ModelField().Name("CompanyName"));
                            fields.Add(Html.X().ModelField().Name("Phone"));
                            fields.Add(Html.X().ModelField().Name("Fax"));
                            fields.Add(Html.X().ModelField().Name("Region"));
                        })))))
        .ColumnModel(columnModel =>
        {
            columnModel.Columns.Add(Html.X().Column().Text("ContactName").DataIndex("ContactName").Flex(1));
            columnModel.Columns.Add(Html.X().Column().Text("CompanyName").DataIndex("CompanyName").Flex(1));
            columnModel.Columns.Add(Html.X().Column().Text("Phone").DataIndex("Phone"));
            columnModel.Columns.Add(Html.X().Column().Text("Fax").DataIndex("Fax"));
            columnModel.Columns.Add(Html.X().Column().Text("Region").DataIndex("Region"));
        })
        .BottomBar(bar => bar.Add(Html.X().PagingToolbar()
                                          .DisplayInfo(true)
                                          .DisplayMsg("Displaying customers {0} - {1} of {2}")))
        .View(view => view.Add(Html.X().GridView())))

 

First of all, please note the Html.X() helper method. This is the entry point for configuring any Ext.NET component. As requisite for getting started, you can call the Html.X().ResourceManager() helper method. Like the counterpart of Ext.NET for WebForms, it automatically injects every script and stylesheet you need into your page. The output should be something like this:

<link type="text/css" rel="stylesheet" href="/extjs/resources/css/ext-all-gray-embedded-css/ext.axd?v=25767" />   
<link type="text/css" rel="stylesheet" href="/extnet/resources/extnet-all-embedded-css/ext.axd?v=25767" />
<script type="text/javascript" src="/extjs/ext-all-js/ext.axd?v=25767"></script>
<script type="text/javascript" src="/extnet/extnet-all-js/ext.axd?v=25767"></script> 

OK, now through the Html.X() helper you can start configuring the GridPanel. In my example I have an AjaxProxy which calls a controller action in order to get back some JSON data to bind to the GridPanel. Some point of interest:

  • start and limit are the two standard ExtJs querystring parameters sent by the proxy to the remote data source in order to tell it how to page data.
  • AjaxProxy can process the resulting JSON via a JsonReader. In particular, pay attention to the Root() and TotalProperty() methods. They tell the reader respectively which root property in the JSON response contains the data rows and which property contains the total results count. They are two fundamental info for the right grid rendering.

Finally, the controller action code:

public ActionResult GetCustomers(int start, int limit)
{
    IEnumerable dtoArray;
    int total;

    using (var unitOfWork = _unitOfWorkFactory.Create())
    {
        var customerRepository = _repositoryFactory.CreateCustomerRepository(unitOfWork);
        var customers = customerRepository.Query()
                                          .Skip(start)
                                          .Take(limit);

         dtoArray = (from customer in customers
                        select new
                                {
                                    customer.CustomerID,
                                    customer.CompanyName,
                                    customer.ContactName,
                                    customer.Phone,
                                    customer.Fax,
                                    customer.Region
                                }).ToArray();

         total = customerRepository.Query().Count();
    }

    return Json(new { data = dtoArray, total = total }, JsonRequestBehavior.AllowGet);
}

 

Posted in AJAX, ASP.NET, ASP.NET MVC, C#, Programming, Web Development | 8 Comments »

Using MEF in a Request/Response Service Layer

Posted by dariosantarelli on December 30, 2011


In a project of mine I’m using a simple Request/Response service layer very similar to the amazing Davy Brion’s Agatha project. Everything started a few time ago when I was searching for a smart way to design a client-server infrastructure which was focused on messages and not on operations. This layer would be not only a classic WCF-based service, but also a some kind of in-process facade to my business layer where I could centralize any cross cutting concern. So I was focused on the capability of moving my service layer and its business logic to a separate machine and hosting it through WCF without any significant modifications to my code (admitting that service layer doesn’t share state with upper layers like the presentation layer). After reading Davy’s “Why I Dislike Classic Or Typical WCF Usage” , I was convinced to address myself to one service contract with one service operation, avoiding to spend time thinking about how to design and implement service contracts and operations. In this way, the first (great) advantage I got is that I can add functionalities simply defining a request message, a response message and a request handler which executes the logic needed between a request receiving and a response sending. Very simple and effective!

Overview of the service layer

Everything starts from an interface called IRequestHandler:

public interface IRequestHandler 
{
  Response HandleRequest(Request request);
}

Request and Response are empty base abstract classes:

public abstract class Request {}
public abstract class Response {}

Now let’s define a simple rule: every concrete request type must be corresponded by a concrete response type. The idea is to basically consider each service operation as a request which must have a response. For each request you define, you need to provide an handler which does whatever it needs to do to handle the request and returns a response. In my solution, a simple generic base request handler has been defined in the following way:

public abstract class RequestHandlerBase<TRequest, TResponse> : IRequestHandler 
                                                              where TRequest : Request 
                                                              where TResponse : Response 
{
    public Response HandleRequest(Request request)
    {
        return HandleRequest((TRequest)request);
    }

    public abstract TResponse HandleRequest(TRequest request);
}

For example, by inheriting this RequestHandlerBase base class, we could create a login request handler, which implements the business logic for validating a user:

public class LoginRequestHandler : RequestHandlerBase<LoginRequest, LoginResponse>
{
    public override LoginResponse HandleRequest(LoginRequest request)
    {
      // validate the user credentials contained in the LoginRequest 
      // and return a LoginResponse containing, for example, a session token 
    }
}

Having each request handler implemented in the same fashion as the LoginRequestHandler, I’d like to reach a service implementation like this:

public class MyService : IRequestHandler 
{
    private readonly IRequestHandlerProvider _requestHandlerProvider;

    public MyService(IRequestHandlerProvider requestHandlerProvider)
    {
        _requestHandlerProvider = requestHandlerProvider;
    }

    public Response HandleRequest(Request request)
    {
        return _requestHandlerProvider.GetRequestHandler(request.GetType()).HandleRequest(request);
    }
}

As you can see, the service itself implements the IRequestHandler interface and the actual implementation is very minimal: it’s just a small class which resolves the appropriate handler through an abstraction called IRequestHandlerProvider which internally may use an IoC container capable of resolving the request handler associated to a request type. Then, the service delegates the execution to an handler by passing the request to it, and finally it returns a typed response to the client.

Enter MEF

Now we could need a IoC container to resolve and create the instances of the request handlers. As shown in this post, you can use the Castle Windsor IoC container to use dependency injection. That basically allows you to register each valid request handler that is present, for example, in a given assembly. Even my purpose was to find a simple way to plug in request handlers defined in external assemblies, getting everything registered automatically in a centralized request handler provider when the application starts up. So, I was focused on MEF. What I tried to do is to treat each request handler as an extension, because in my project each tuple “Request-Response-Handler” represents an extension unit. Moreover,

  • MEF is an integral part of the .NET Framework 4
  • MEF offers a set of discovery approaches for locating and loading available extensions even in a “lazy” fashion
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering so an extensibility element can provide metadata to exported items.

Following this philosophy, beyond the classic Export attribute I introduced a RequestHandlerMetadataAttribute useful for simplifying the process of resolving an handler related to a specific request type. So, the LoginRequestHandler defined before could be decorated as the following…

[Export(typeof(IRequestHandler))] // I am a request handler!!!
[RequestHandlerMetadata(typeof(LoginRequest))] // I can handle Login requests!!!
public class LoginRequestHandler : RequestHandlerBase<LoginRequest, LoginResponse>
{
  ... 
}

And here is the RequestHandlerMetadataAttribute definition.

public interface IRequestHandlerMetadata 
{
    Type RequestType { get; }
}

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class RequestHandlerMetadataAttribute : ExportAttribute 
{
    public Type RequestType { get; set; }

    public RequestHandlerMetadataAttribute(Type requestType)
        : base(typeof(IRequestHandlerMetadata))
    {
        RequestType = requestType;
    }
}

In order to allow us to access the metadata, MEF introduces a special kind of Lazy<T,M> that has attached metadata. M in this case is an interface (called “metadata view”) that contains only getter properties. MEF automatically generates a proxy class that implements this interface and it plugs all the metadata in for us. This is very cool! What is happening behind the scenes is that MEF is using reflection emit in order to construct the typed metadata view.

As result, I’ve used the metadata view IRequestHandlerMetadata to easily find the right handler for a request of a given type, as shown in the GetRequestHandler() method of the following MefRequestHandlerProvider.

public class MefRequestHandlerProvider : IRequestHandlerProvider 
{
    private readonly List<Lazy<IRequestHandler, IRequestHandlerMetadata>> _registeredHandlers =
                                              new List<Lazy<IRequestHandler, IRequestHandlerMetadata>>();

    public MefRequestHandlerProvider(IEnumerable<ComposablePartCatalog> catalogs)
    {
        foreach (var catalog in catalogs)
        {
            var container = new CompositionContainer(catalog);
            var exportedHandlers = container.GetExports<IRequestHandler, IRequestHandlerMetadata>();

            foreach (var exportedHandler in exportedHandlers)
            {
                foreach (var registeredHandler in _registeredHandlers)
                {
                    if (registeredHandler.Metadata.RequestType == exportedHandler.Metadata.RequestType)
                        throw new NotSupportedException(string.Format("A request handler for type {0} is already registered.",
                                                                      exportedHandler.Metadata.RequestType));
                }
            }

            _registeredHandlers.AddRange(exportedHandlers);
        }
    }

    public IRequestHandler GetRequestHandler(Type requestType)
    {
        var handler = _registeredHandlers.SingleOrDefault(r => r.Metadata.RequestType == requestType);
        if (handler != null) return handler.Value;
        throw new RequestHandlerNotFoundException(string.Format("No request handler has been found for type {0}", requestType));
    }
}

Putting all together, in the application startup I placed the following initialization code which uses the MefRequestHandlerProvider. As you may know, request handlers can be located inside catalogs (e.g. AssemblyCatalog, AggregateCatalog etc.). When using a client proxy, I need to expose just one method which never needs to be updated. That’s a good advantage!

// Server-Side 
var catalog = new AssemblyCatalog(typeof(IRequestHandler).Assembly);
var mefRequestHandlerProvider = new MefRequestHandlerProvider(new[] { catalog });
MyService service = new MyService(mefRequestHandlerProvider);

// Client-Side (when using a proxy)
LoginResponse response = (LoginResponse)serviceProxy.HandleRequest(new LoginRequest("username", "password"));
Console.WriteLine(response.AccessToken);

Conclusion

In this post I’ve tried to show how I used MEF to plug request handlers in a request/response service layer similar to Agatha. I have not written anything about serialization issues when exposing the service layer through WCF. Moreover, I haven’t treated any aspects about request handlers such as objects lifecycles or error management. I think that any question about these service layer insights can find good answers after reading the Davy Brion’s Request/Response Service Layer Series.

HTH

Posted in .NET Framework, Microsoft Technology, Programming | Tagged: , | 1 Comment »

Programming languages history

Posted by dariosantarelli on June 22, 2008


Here you can find an interesting diagram of programming languages history. Years go by, but surprisely you can see how apparently incompatible paths (OO and functional programming) are slowly fusing in time.  For about 50 years, computer programmers have been writing code. New technologies continue to emerge, develop, and mature. Now there are more than 2,500 documented programming languages!

Here a preview 😉

diagram

Moreover, O’Reilly has produced a poster called History of Programming Languages  which plots over 50 programming languages on a multi-layered, color-coded timeline.

Posted in Programming | Leave a Comment »

Installing Enterprise Library 3.1 in VS2008

Posted by dariosantarelli on March 14, 2008


The patterns & practices Enterprise Library 3.1 is a library of application blocks published for Visual Studio 2005 and designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used “as is,” extended, or modified by developers to use on enterprise development projects. This release of Enterprise Library includes application blocks for Caching, Cryptography, Data Access, Exception Handling, Logging, Policy Injection, Security and Validation.
In this post you can find how to to get the integrated tool to work in Visual Studio 2008. Simply you have to run a registry script that will change the keys where VS looks to load the integrated tool package. After you run the script, you will need to run devenv /setup from the Visual Studio 2008 command prompt. You can download the file from the EntLibContrib project on CodePlex.

P.S.: If you already have the Enterprise Library 3.0 installed, you must uninstall it before installing the Enterprise Library 3.1.

Posted in .NET Framework, Microsoft Technology, Programming | Leave a Comment »

LINQ to Objects in .NET 2.0/3.0 projects

Posted by dariosantarelli on March 1, 2008


LINQ’s query operators are implemented in .NET Framework 3.5. And here lies a difficulty: you might be unsuccessful in demanding that all your customers install Framework 3.5 right away. So what does this mean if you want to code in C# 3.0 and write LINQ queries?
You can use LINQBridge, a reimplementation of all the standard query operators in Framework 3.5’s Enumerable class by Joseph Albahari.

  • LINQBridge is designed to work with the C# 3.0 compiler, as used by Visual Studio 2008.
  • LINQBridge comprises a “LINQ to Objects” API for running local queries. (It doesn’t include an implementation of LINQ to SQL, nor LINQ to XML).
  • LINQBridge also includes Framework 3.5’s generic Func and Action delegates, as well as ExtensionAttribute, allowing you to use C# 3.0’s extension methods in Framework 2.0. In fact
  • LINQBridge lets you use nearly all of the features in C# 3.0 with Framework 2.0—including extension methods, lambda functions and query comprehensions. The only feature it does not support is compiling lambdas to expression trees (i.e., Expression<TDelegate>).

Posted in .NET Framework, C#, Microsoft Technology, Programming | Leave a Comment »

VS2008: Embedding UAC Manifest Options

Posted by dariosantarelli on November 21, 2007


A very useful feature included in VS2008 concerns the possibility of embedding a manifest resource which specifies UAC options in applications running on Windows Vista. First, you can create a manifest file by adding an “Application Manifest File” Item to your project (default name: app.manifest), then you can set it through the Application Tab in the Project Properties.
If you want to change the Windows User Account Control level in your manifest file, all you need is to set the value of the level attribute of the requestedExecutionLevel node with one of the following:

  • asInvoker (default): the application will run using the current Windows user provileges
  • requireAdministrator: the application requires an Administrator user
  • highestAvailable: highest privileges for the current user will be used

Posted in .NET Framework, Microsoft Technology, Programming | 4 Comments »

Protecting data using ProtectedMemory

Posted by dariosantarelli on November 8, 2007


If you are looking for a smart way to encrypt/decrypt sensitive data in memory in order to make them unreadable even in malicious memory dumps, maybe you need to use the ProtectedMemory class (namespace System.Security.Cryptography). This class is a managed wrapper included in the DPAPI (Data Protection API) and it works in the same way as ProtectedData (a similar class indeed used to persist encrypted strings in file/database): it exposes two static methods, Protect and Unprotect,  which allow you to encrypt/decrypt strings in memory. The only requirement you have to consider in order to avoid a CryptographicException  is about using 16-bytes blocks for computing encrypted/decrypted data. For example, the following code shows how to protect/unprotect a sensitive string in memory during a process execution:

using System.Security.Cryptography;

string OriginalString = “xxxxxxxxxxxxxxxx”;
Console.WriteLine(“Before Protect: “ + OriginalString);
byte[] OriginalBytes = Encoding.UTF8.GetBytes(OriginalString);
ProtectedMemory.Protect(OriginalBytes, MemoryProtectionScope.CrossProcess);
UTF8Encoding enc = new UTF8Encoding();           
Console.WriteLine(“After Protect: “ + enc.GetString(OriginalBytes));
ProtectedMemory.Unprotect(OriginalBytes, MemoryProtectionScope.CrossProcess);
OriginalString = Encoding.UTF8.GetString(OriginalBytes);
Console.WriteLine(“After Unprotect: “ + OriginalString);

Here the output:
Before Protect: xxxxxxxxxxxxxxxx
After Protect: 7j??‼8y_??PQ<?¶-
After Unprotect: xxxxxxxxxxxxxxxx

Some further considerations:

  • The Protect()/Unprotect() method works directly on the original data, not on a copy. So, we don’t need to explicitly destroy our sensitive strings after the use.
  • Many people use SecureString, a more intuitive class using ProtectedMemory to automatically encrypt strings. A SecureString can be modified till the MakeReadOnly() method call and can be programmatically disposed. Finally, its MemoryProtectionScope is SameProcess: a SecureString can’t be used in CrossProcess and SameLogon scenarios, in which there’re multiple applications running in different processes (CrossProcess) and allowing data encryption/decryption to the same Windows user (in particular cases, consider the impersonation technique).
  • I’ve noticed some strange behaviours by randomly analyzing the memory dump file after invoking the Protect() method on a string: sometimes the text I’d like to protect appears as clear text…mmmm…. Does Windows operate a swap on file system before data encryption? If this is a possibility, are my efforts unuseful?

Posted in .NET Framework, C#, Programming | 1 Comment »

Getting a DataRow from a DataGridViewRow

Posted by dariosantarelli on September 5, 2007


If you want to retrieve a DataRow from a DataGridViewRow (for example starting from a DataGridViewSelectedRowCollection), you simply need to get the Row property of the DataRowView obtained by converting the DataBoundItem object of the DataGridViewRow :

DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;               
foreach (DataGridViewRow row in rows)
{
 
DataRow myRow = (row.DataBoundItem as DataRowView).Row;
 
// do something with your DataRow…
}

Hope it helps 😉

Posted in .NET Framework, C#, Programming | 17 Comments »

Extension Methods in C#

Posted by dariosantarelli on August 6, 2007


An interesting feature of the .NET Framework 3.5 is that any set of methods available on an instance of a particular type is open to extension. Effectively, adding new methods to existing types is now possible.By using extension methods, we can declare static methods that can be invoked using the instance method syntax. In order to declare an extension method we must specify the keyword this as the first parameter of the static method.
Let’s show an example:

1. We have a Customer class, which needs of another method “Logout”:
 
2. Instead of using an inherited class, we add the “Logout” method to our Customer class by declaring a static method which can be invoked directly in any Customer class instance.

3. Finally, in our code we can invoke our “Logout” extension method in this way:

When extension methods are consumed, the argument that was declared with the keyword this is not passed, while all other arguments will be passed and seen by intellisense.  So, the first argument in the declaration (keyword this) allows the compiler to determine the class instances on which the extension method is called.
Remember that extension methods, though declared as static, can be called only on instances values!!!

Posted in .NET Framework, C#, Programming | 4 Comments »

MOSS 2007: Programmatically Configure Search Scopes

Posted by dariosantarelli on April 20, 2007


In the code below you can find a way to use the MOSS 2007 Administration Object Model to programmatically create a search scope in your Shared Service Provider and include your content sources to the created search scope.
Hope it helps… 😉

using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;



SearchContext context;
using (SPSite site = new SPSite(“http://<SSPsite>&#8221;))
{
context = SearchContext.GetContext(site);
}
Schema sspSchema =
new Schema(context);
ManagedPropertyCollection properties = sspSchema.AllManagedProperties;
Scopes scopes =
new Scopes(context);
ScopeCollection sspScopes = scopes.AllScopes;
Scope newScope = sspScopes.Create(“Name”, “Description”,
null, // System.Uri object representing the owning site URL
true, // True to display the scope in the SSP Administrator UI
null, // A string specifying the alternate results page for the scope
ScopeCompilationType.AlwaysCompile);
// Includes your content sources to the created Scope
foreach (string ContentSourceName in YourContentSourcesNames)
{
newScope.Rules.CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include,
properties[“ContentSource”], // Managed Property
ContentSourceName);
}
// Update Scopes
scopes.StartCompilation();

Posted in .NET Framework, C#, Microsoft Technology, Programming | 2 Comments »

LINQ Samples

Posted by dariosantarelli on April 3, 2007


The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities. In other words, LINQ (“Language Integrated Query”) allows developers to query in-memory data inline.
If you aren’t familiar with this language, try this link: 101 LINQ Samples (why 101 and not 100???)
As a developer, I’ve always thought that sample code is the best way to learn a technology ;). 
In addition, there are different versions of LINQ: for database queries and XML queries we have,  DLINQ  and XLINQ (files .doc from Microsoft) respectively. 

Posted in .NET Framework, C#, Microsoft Technology, Programming | Leave a Comment »

Reflector 5.0 available

Posted by dariosantarelli on March 12, 2007


Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL. The new version (5.0.7.0) also supports .NET 3.5 and query expression reverse engineering. Moreover,  you can find a lot of Add-Ins here (Codeplex).

Posted in .NET Framework, Programming | Leave a Comment »

Zope Behind IIS6… SCRIPT WAR!!!

Posted by dariosantarelli on February 2, 2007


Some days ago I started configuring Zope for Plone. When I was ready for deploying, I found a Windows Server 2003 SP1 based production environment with IIS6 as Web Server. I knew there is a script which forwards IIS requests to Zope (much like ProxyPass does for Apache), using Virtual Host Monster to generate correct dynamic URLs, just setting IIS5 to handle 404/405 (Not Found) errors with it.
Well, I didn’t know IIS6 breaks POST methods used in the forms inside Zope/Plone. I bang my head on the screen for a while, after a 6 hour hard-coding session, when I find a discussion in the Zope Community about my problem!!!
At the moment, a proposed “open” solution involves a Java Proxy for host-header analyzing, requesting data from Zope, and returning it back to the client.  
Well, waiting for other solutions, If you want to to speed up your Plone site by integrating it with IIS, you can still purchase Enfold Proxy

Posted in Programming, Web Development | Leave a Comment »

ASP.NET AJAX v1.0 Released!!!

Posted by dariosantarelli on January 30, 2007


Finally, ASP.NET AJAX v1.0 Released!!!
This technology enable a developer to create next-generation interfaces with reusable AJAX components. Moreover, it enhances existing Web pages using powerful AJAX controls with support for all modern browsers such as IE, Firefox and Opera.
You can continue using Visual Studio 2005 to take your ASP.NET 2.0 sites to the next level and access remote services and data directly from the browser without writing complicated script.
Downloads:
ASP.NET AJAX consists of the two essential downloads shown below. In the ASP.NET AJAX Downloads Page You’ll also find related downloads on this page including the Futures CTP, the sample applications, and the Microsoft AJAX Library for development on non-Windows platforms.

  • ASP.NET 2.0 AJAX Extensions 1.0
  • ASP.NET AJAX Control Toolkit (a shared-source community project from CodePlex consisting of samples and components that make it easier to work with AJAX-enabled controls and extenders. The Control Toolkit provides both ready-to-run samples and a SDK to simplify creating custom ASP.NET AJAX controls and extenders. Make sure you install ASP.NET AJAX 1.0 first!)

Posted in .NET Framework, AJAX, ASP.NET, Programming, Web Development, Web Services | Leave a Comment »

REALbasic 2007

Posted by dariosantarelli on January 9, 2007


REALbasic is a cross-platform development  system to create software for Windows, Macintosh and Linux from a single set of source code. Now applications built with REALbasic 2007 will run on Windows Vista.
Check it out!!!

Posted in Programming | Leave a Comment »