I really love the “var” keyword because it simplifies the code.  Var can be switched from one type to another without any potential code changes (as long as the signatures match), and all of this is referenced at compile time.  But i noticed a side-effect with var within Visual Studio.  Right-clicking find all references of a specific type missed a reference to a type because of var.  Instead of actually looking up the type, Find references matches the type by name, and as such, var can be easily missed within the found results.  So while the var keyword makes future code changes a breeze and reduces code, there are some editor-specific fallbacks to it.

Being that I’ve been undertaking several Model-View-Presenter projects, I’m writing this post to illustrate the way a view uses an event.  In the Model View Presenter pattern, the primary means a view communicates with the presenter is using events.  Methods of the view can be called from the presenter, but typically I’ve seen mostly events.  An event signals that some action is happening within the system.  The user saved a record, selected an object, cancelled their changes, etc.   These actions translate from a button click, etc. in the UI to the view passing up a corresponding event to the presenter.  The presenter only knows about the view’s events through the view’s interface, which, of course, the view has to implement.  Since the view is required to implement X event, X event can be listened to in the presenter, and this completes the first round of the process.

Be careful that you understand the reasoning for the event; the event is not used solely to serve the presenter.  For instance, if the view attempts to load data on demand solely for pushing data to the view, its not the responsibility of the view to do this necessarily; the presenter is the controller driving what happens during the request; the view is responsible for managing the UI.

For instance, suppose that this happened in the view:

protected override void OnLoadReferenceData(EventArgs e)
{
    var args = new DataEventArgs();
    if (LoadReferenceData != null)
        LoadReferenceData(args);

    //Commence with loading the data here
}

In this example, who is in control of the process?  The presenter is supposed to be in control, but the view oversteps its bounds and starts making demands for its needs.  In this way, we can circumvent the presenter from performing the responsibilities it is supposed to be performing.  This is especially true if we see many On<X> methods, each loading a portion of its data.  Why do I say this?  The presenter can become a data access class, primarily serving the view, rather than controlling the flow of the process, and having the presenter load and push down data at the right time through the model.

Playing devil’s advocate, can there be times when view loading of demand is needed?  Certainly.  Can a view load the data directly from event args, instead of the model.  Sure, however, I would recommend to leave the presenter as the sole responsibility over the process, otherwise the view and presenter may become chaotic to maintain.

So what is essentially the difference between the two?  On one level, its grammar.  A view event named RefreshPage appears differently to the user than LoadData or NeedData.  It can also be by action; if the view fires an event and immediately loads its data from the event args, then what is the presenter really doing?  Is it controlling the process, or is it a data access layer?  Does the view respond to the model passed from the presenter?  This is a proper way for the communication chanel.

Some food for thought.  I would love to hear your opinion.  Please comment using the form below.

In the interest of standardization, the RadComboBox allows a custom CSS clas to be specified for the dropdown, via the DropDownCssClass property (as if you probably couldn’t figure that one out :-D).  In an application I’m working on, we have a set of pre-built CSS classes of varying sizes, and we apply styles to the drop down to be consistent.  However, after applying the style, it didn’t quite seem to take affect.  This is because the CSS for the RadCombo looked something like the following:

<div class=”.. Telerik CSS Classes .. MyDropDownClass”>
    <div class=”rcbScroll rcbSlide” style=”… height:380px;”>

I don’t know where it got the 380 px, but then changing my CSS to:

.MyDropDownClass
{
    width: 250px;
    max-height:300px;
}

.MyDropDownClass > rcbScroll
{
    max-height:300px;
}

Did the trick for me.  May need to adjust slightly, as I haven’t fully tested cross browser.

In continuing the series on the Nucleo MVP framework, we’re going to look at how easy it may be to use AJAX.  Like the web services proxy generation to the server-side web server, the Nucleo MVP currently supports limited AJAX proxy support (with more support to come).  Using the Nucleo.Web.MVP framework, the project and the BaseWebPresenter presenter class, a client-side proxy can be generated to call server-side static methods first by adding the following attribute:

 [PresenterAjax(EnableWebMethods = true)]
public class AjaxCallbackPresenter : BaseWebPresenter<IAjaxCallbackView>

The EnableWebMethods setting triggers a look for the [PresenterWebMethod] attribute on a static method.  The process would find the following two methods:

 [PresenterWebMethod]
public static void AddItem(string item)
{
 List<string> items = HttpContext.Current.Cache.Get(“Items”) as List<string>;
 if (items == null)
  items = new List<string> { };

 items.Add(item);

 HttpContext.Current.Cache[“Items”] = items;
}

[PresenterWebMethod]
public static List<string> GetItems()
{
 List<string> items = HttpContext.Current.Cache.Get(“Items”) as List<string>;
 if (items != null)
  return items;

 return new List<string> { “A”, “B”, “C”, “D”, “E” };
}

The PresenterWebMethod attribute points these two methods as methods to be proxied in client-side JavaScript.  Right now, the methods have to be static; though, I am working on adding to the process the ability to talk to instance methods too.  At runtime, the n$.Presenters collection contains our AJAX presenter, and renders a proxy for the two methods, AddItem and GetItems.  We can see this in the works through the following proxy:

n$.Presenters[“AjaxCallbackPresenter”] = (function() {
return {
 AddItem: function(item, successCallback, failedCallback) { .. },
 GetItems: function(successCallback, failedCallback) { .. }
};
})();

The proxy makes a web request to a handler that invokes the corresponding presenter on the server, which happens the following way:

 n$.Presenters[“AjaxCallbackPresenter”].GetItems(function (response) {
       $get(“<%= lblOutput.ClientID %>”).innerHTML = response.data.toString();
});

 n$.Presenters[“AjaxCallbackPresenter”].AddItem($get(“<%= txtValue.ClientID %>”).value, function (response) {
 updateLabel();
 $get(“<%= txtValue.ClientID %>”).value = “”;
});

And as such, we have client/server integration to the presenter, just like ASP.NET MVC or  web services/page methods.

I’ve been using the MVP pattern for a new project and have developed an open-source framework (available here).  I’m not an MVP expert, but I’ve learned a lot about the pattern and UI patterns at a whole.  One important idea about the pattern that I’ve learned is to ensure that the layers are properly separated.  For instance, some of the errors that happen in the framework happen because the proper separation of concerns is violated, which can lead to a harder-to-maintain application, bugs, or application errors.  A good understanding of this separation is important.

The presenter itself is responsible for:

 

  • computational logic generated by business rules
  • validation rules that fire across the domain to ensure some business rule related to other data in the database is in a correct state
  • loading of data that the view will use
  • communicating with other presenters

 

The view itself is responsible for:

 

  • Binding model data to the UI
  • Managing the UI

 

There are some gray areas to evaluate, such as the following:

  • Should the view request data from the presenter via an event?
  • Should the view be reactive to the existence of data in the model, or should code to bind to the view fire after an event happens?

The Nucleo MVP framework, at the presenter level, contains a complex system for cross-presenter messaging that each presenter can act on.  Using the presenter’s CurrentContext property, the EventRegistry object contains methods to subscribe and publish to events using a variety of syntaxes.

For instance, a presenter can subscribe to an event using the following syntax.  The event subscription can take place in the Initializing event of the view, or it can be in the constructor.  This example uses the former.

 

public ManyMessagesSamplePresenter(IManyMessagesSampleView view)
base(view)
{
view.Initializing += new EventHandler(View_Initializing);
}

void View_Initializing(object sender, EventArgs e)
{
this.CurrentContext.EventRegistry.Subscribe(
ListenerCriterion.EntityType<ManyMessagesPresenter>(),
(d) => 
{
HttpContext.Current.Response.Write(string.Format("A subpresenter published an event: {0}<br/>", id++)); 
});
}

 

The Subscribe method call takes two parameters.  The first parameter identifies the subscription, whereas the second parameter is the subscriber.  Let’s look at each individually.  There are a variety of ways to listen to events:

 

  • ListenerCriterion.Entity – Uses an object reference to filter events to.
  • ListenerCriterion.EntityType – Uses the type of some object to subscribe to events.
  • ListenerCriterion.Event – Uses an IEvent instance to attach to an event.  This will have more significance with the next release.
  • ListenerCriterion.Identifier – Uses a string (ideally a constant) to attach to as an event.

 

What this means is that there are many choices to use as the means to subscribe and publish events to.  An object can be the subscription key, a type, or a string identifier, is the primary purpose for this.  Next, we can supply one of two types of subscribers.  First, an action statement can listen to the event, and when the event fires, the action is called directly.  Secondly, an object implementing IEventReceiver can receive the event, if that is preferred.

Using this approach, when the event fires (is published), the PublishedEventDetails object contains the details about the event published.

 

public class ManyMessagesPresenter : BasePresenter<IManyMessagesView>
{
public ManyMessagesPresenter(IManyMessagesView view)
base(view) 
{
view.Loading += new EventHandler(View_Loading);
}

void View_Loading(object sender, EventArgs e)
{
this.CurrentContext.EventRegistry.Publish(
new PublishedEventDetails(ListenerCriterion.EntityType<ManyMessagesPresenter>()));
}
}

At any point in the process (here its when the view is loading, but it could be in response to any other event), the Publish method is responsible for the publishing of the event. The details of the event are also passed to the subscribe to the action or IEventReceiver instance.

In this way, messages can be passed through multiple presenters. Multiple presenters can subscribe to a single event, and vice versa.

You can get this framework at http://nucleo.codeplex.com.

The new ClientIDMode property is a new .NET 4.0 features that allows a developer to take control over the ClientID property.  In .NET 3.5 and earlier, the ClientID property renders in the ID HTML attribute for all controls.  The system generated ID would be very long, may be looking something like ct100_ct100_BOdyPlaceholder_Ctl for a control that has an ID property of Ctl, and as such, ClientIDMode gives you much better control over this rendering process.  For instance, a mode of Static takes whether the ID value is and renders it directly, which is very useful but potentially dangerous (as then you have to ensure that each ID is unique).  It seems a lot of people favor the Predicable, trimming down the “ID fat.”  ClientIDMode can be set per control, in the @Page declaration, and in the config file.

From an AJAX perspective, this can be helpful.  It was mostly required to find an AJAX control (especially if the application used a master page).  This required these types of lookups of AJAX components:

var control = $find(“<%= Button1.ClientID %>”);

This finds a button AJAX control, but as you can see, because the ID is never the same as the ClientID, we needed to render it from the server-side so that the correct client-side ID (always ClientID) is passed in and the control is properly found.

But with the addition of ClientIDMode, for controls we know are standard, we can define a control like:

<nucleo:Button id=”b1″ runat=”server” ClientIDMode=”Static” />

And can reference it on the client as:

var control = $find(“b1”);

Because both the ID and the ClientID match on the server, thus the server-side ID of b1 is also the client side ID of b1, and it makes it easier for lookups, though the previous approach wasn’t that much more difficult.  There are only a handful of scenarios where the <%= %> syntax doesn’t work, such as templated controls that are not marked with [TemplateInstance(TemplateInstance.Single)] attribute definition, or repeating templates.  The syntax must also be specified in the same container (same page, same user control, etc.).

I’d recommend using ClientIDMode=”Static” for central controls, such as the scriptmanager, or if you use Telerik the RadAJaxManager and other Rad manager controls.  Additionally, other master page controls can use a static ID, and then it makes it easier to target these controls from client-side JavaScript, as we don’t have to mess around with the <%= control.ClientID %> syntax and any general scoping issues that may bring.

There is an AJAX benefit to the new ClientIDMode property.

The issue with the UpdatePanel control is that it’s not possible to invoke an AJAX request from client-side JavaScript.  Though possible to refresh the UI from client-side JavaScript using various means, the UpdatePanel control itself doesn’t invoke a postback explicitly through some API call; instead, it reacts to form posts through specifically targeted controls.  The Telerik RadAjaxPanel control is very nice control to have in your .NET developer toolbelt.  By calling the following client-side code:

var panel  = $find(“<%= RAP1.ClientID %>”);
panel.ajaxRequest(“data”);

This code invokes a server-side postback, firing the entire lifecycle, and calling the AJaxRequest server-side event with the data passed as an argument as in the following:

protected void RAP1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
   if (e.Argument == “data”)
   {
       //Act on async postback
    }

This comes in very handy, and can setup performance-adding features like lazy loading of tabs, dynamic loading of content after the page initially loads (working like pageflakes.com), and more.

There are some additional features to be aware of.  Both the RadAjaxPanel and the RadAjaxManager controls allow you to do more than just that; these controls support running scripts after the response is written to the browser.  The ResponseScripts collection can take a string statement that outputs JS code and do any additional processing, like the following:

RAP1.ResponseScripts.Add(“alert(‘here’);”);

When the async update, the alert will run afterwards.  This can also be used to work with a control’s API too, or whatever else you may need to do.  For instance, to call a method on the client of an AJAX control, we can do something like:

RAP1.ResponseScripts.Add(string.Format(“$find(‘{0}’).set_text(‘Some text’);”, this.RadTextBox1.ClientID);

Here you can see we’re calling the set_text method on an AJAX RadTextBox control.

Additionally, for more information on lazy loading content from the client-side AJAX calls, check out this very helpful forum post: http://www.telerik.com/community/forums/aspnet-ajax/ajax/multiple-radajaxpanel-s-invoked-on-pageload-causes-errors.aspx

Most people understand how to use the Unity framework, or at least I hope.  Microsoft Unity is a pretty useful DI container.  If you need to learn more about it, check out my article on dotnetslackers here: http://dotnetslackers.com/articles/aspnet/Using-Microsoft-Unity-in-ASP-NET-MVC.aspx.  In this example, there is a sample custom configuration file that registers unity contract types to their mapped implementation types.  Take a look at the configuration snippet below.

 

<unity
  <typeAliases
    <typeAlias alias="CommonInt" type="Nucleo.Context.IService, Nucleo" /> 
  </typeAliases
  <containers
    <container name="Repositories"
      <types
        <type type"App.ICustomerRepository, App.Business" mapTo="App.CustomerRepository, App.Business" />      
        <type type"App.IProductRepository, App.Business" mapTo="App.ProductRepository, App.Business">
          <constructor />
        </type>
      </types
    </container>
  </containers
</unity>
Here is where the challenge comes in.  If, for some reason, say the mapped type App.CustomerRepository was mapped incorrectly, or may not implement App.ICustomerRepository, Unity gives you this vague message about the error with no actual details to the problem.  This problem has been common to many developers that you see it plastered on forums or blogs across the web.  I’m posting this because I resolved the issue, but it requires some additional work.
To start, we need to directly access the unity configuration section by loading up the config section as so:
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(“unity”);
Rather than letting unity register the types, which it has a method to do this for you, I register the types directly by doing something like the following:
foreach (var typeEntry in section.Containers[“Repositories”].Registrations) //Repositories specified in config
{
   Type fromType, toType;

    try
    {
       fromType = Type.GetType(typeEntry.TypeName);
    }
    catch
    {
       throw new Exception(“Could not create the contract type: ” + typeEntry.TypeName);
    }

    try
    {
      toType = Type.GetType(typeEntry.MapToName);
    }
    catch
    {
        throw new Exception(“Could not create the mapped type: ” + typeEntry.MapToName);
    }

    try
    { 
       container.RegisterType(fromType, toType);
    }
    catch
    {
        throw new Exception(“Could not register the mappings: ” + typeEntry.TypeName + ” to ” + typeEntry.MapToName);
    } 

A little extra work, but this exception handling scheme points directly to the root cause of the problem.  It really saved me a lot of time.  Additionally, this works really well if you make it an extension method, or a static utility method.

The open source framework I created has been released for the 0.6 version, which includes:

Some AJAX control updates

New MVC helpers

An MVP framework agnostic to a specific environment (though with only an ASP.NET implementation at the moment, but more to come there).

Framework Plumbing updates/issue fixes

Several ways to develop custom AJAX components

Sample Code

Some Entity Framework Add-Ons (Optional)

Its available here: http://nucleo.codeplex.com/.  I will follow up with documentation/screencasts.  Please let me know what you think if you try it out.

« Previous PageNext Page »