MS MVC with Ajax

Nikhil Kothari from the asp.net development team has posted information about using Ajax within the new MS MVC, Ajax with the ASP.NET MVC Framework.

Although we don’t have the bits yet, it’s looking quite interesting. 

Advertisements

Simple Publisher/Subscriber (Observer Pattern) Sample With Delegates/Events in C#

I was having a great conversation with one of the developers where I work last week and he was asking me about delegates and events. I figured I’d create a sample for him – and hey, why not – let’s post it here (easier than emailing the code anyway…)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace DelegateEventSample
{
    [TestFixture]
    public class TestSample
    {
        [Test]
        public void Main()
        {
            Publisher publisherService = new Publisher();
            ESPNNEws espnNews = new ESPNNEws(publisherService);
            CBSSportsNews cbsNews = new CBSSportsNews(publisherService);

            publisherService.NewsUpdate("Mizzou 14, Kansas 0 at the half...");
        }
    }

    public class Publisher
    {
        public delegate void NewUpdateDelegate(object sender, NewsInfoArgs args);
        public event NewUpdateDelegate NewUpdateEvent;

        public void OnNewUpdateEvent(object sender, NewsInfoArgs args)
        {
            if(NewUpdateEvent != null)
                NewUpdateEvent(sender, args);
        }

        public void NewsUpdate(string news)
        {
            OnNewUpdateEvent(this, new NewsInfoArgs(news));
        }
    }

    public class NewsInfoArgs : EventArgs
    {
        private readonly string thenews;

        public NewsInfoArgs(string thenews)
        {
            this.thenews = thenews;
        }

        public string TheNews
        {
            get{ return thenews;}
        }
    }

    public class ESPNNEws
    {
        private Publisher newPublisher;
        public ESPNNEws(Publisher newPublisher) //inject publisher service
        {
            this.newPublisher = newPublisher;
            newPublisher.NewUpdateEvent += newPublisher_NewUpdateEvent;
        }

        static void newPublisher_NewUpdateEvent(object sender, NewsInfoArgs args)
        {
            Console.WriteLine("ESPN reporting... " + args.TheNews);
        }
    }

    public class CBSSportsNews
    {
        private Publisher newPublisher;
        public CBSSportsNews(Publisher newPublisher) //inject publisher service
        {
            this.newPublisher = newPublisher;
            newPublisher.NewUpdateEvent += newPublisher_NewUpdateEvent;
        }

        static void newPublisher_NewUpdateEvent(object sender, NewsInfoArgs args)
        {
            Console.WriteLine("CBSSportsNews on 11 oclock news... " + args.TheNews);
        }
    }
}

ASP.NET MVC Framework and Spring.NET

Great blog post here – this is but one of the parts of the MVC Framework I’m looking forward to!

public IController CreateController(RequestContext context, Type controllerType)
        {
            IResource input = new FileSystemResource(context.HttpContext.Request.MapPath("objects.xml"));
            IObjectFactory factory = new XmlObjectFactory(input);

            return (IController)factory.GetObject(controllerType.Name);
        }

This is quite impressive. This is very straightforward and simple to grasp. Later it shows here

protected void Application_Start(object sender, EventArgs e)
{
   ControllerBuilder.Current.SetDefaultControllerFactory(
                           typeof(MvcApplication.Models.Infrastructure.SpringControllerFactory));
   ...
}

how easy it is to setup your own controller factory.

The attention that MS is paying to allowing Spring.NET/Windsor, etc… to use MS MVC is music to my ears.

What I’m not looking forward to: convincing coworkers who only know Webforms what the value of all this is. Sometimes I feel like I’m the only guy on the island… 🙂

WCF

Well, just brought home a WCF book, ‘Pro WCF – Practical Microsoft SOA Implementation’. Not a bad read so far.

I’ll be hopping into the realm of SOA and ‘message-oriented’ development.

I’ll try to write up some of my experiences going forward.

I did manage to write a console app ‘ServiceHost’, along with a WCFService.

The nice part is how WCF utilizes interfaces for the service contracts. Something I didn’t see in straight up WebServices.

 

[ServiceContract()]
    public interface IService1
    {
        [OperationContract]
        string MyOperation1(string myValue);
        [OperationContract]
        string MyOperation2(DataContract1 dataContractValue);
    }

WCF seems to be a good thing, so wish me luck 😉

Learning from the best

My good friend Rob reminds me often that it’s about understanding the principles of software design, not just the latest greatest fads that really matures the developer. I’m in 100% agreement. Although I like to fiddle with all the fancy new stuff, it’s the learning of the basic OO principles that continue to really guide me.

Another wise developer, Billy McCafferty echo’s Rob’s mentoring advise in his post ‘Standing on the Shoulders of Giant’s’. The simple fact is that development is not only a science, but I feel an art as well. As a developer, I must admit I get a bit unsettled when looking at modifying API’s such as working with Biztalk, vs. working directly with code. At the same time you can, I believe, incorporate the same fundamentals with any of these technologies – Single Responsibility Principle, Loosely coupled and cohesive, etc…

What really sums it up I believe is that a principle that lives deep to my heart – ‘our challenges in life build our character’. We must see our challenges in this light.

Rob really illustrates this in his post ‘The Pain of Learning is Worth It‘ and ‘You Gotta Have Faith‘. I was glad to read these because it’s a true lesson in life, that as you climb each mountain, no matter how tough or daunting it might seem, there is a lesson learned that just adds to our life’s experiences and our character. Without some of these challenges, I doubt we’d really learn the powerful lessons at hand.

It’s exciting to have a profession where these lessons can be learned. I know personally that I’ve been fearful many times of the demons of ‘future fear’. But it’s amazing how I can look back and see a path carved out with it’s life’s lessons guiding the way.

At some point you have to really grab life by the horns and overcome the fears, realizing that those fears are but obstacles to realizing your own potential.

It’s good to have mentors along the way that can help point to the moon and remind me not to be focused on the finger pointing but the moon itself!

Part III – How does Monorail Work?

Tonight I’m going to discuss Layouts and Rescues.

Layouts

Layouts are another term that webform developers are going to relate to ‘master pages’ and asp developers will call an ‘include’ file.

There are several ways to approach a layout — you can span one layout over several controllers or you can assign a layout to each controller separately. Either way, it’s quite easy to do in Monorail.

Here is the example from the Monorail msi installer project:

[Layout("default")]
public abstract class BaseController : SmartDispatcherController
{
}

It’s rather obvious here: the BaseController is going to use the layout ‘default’. In the Monorail folder structure, there is a ‘layout’ folder in the Views folder. All layouts can go in there.

When using NVelocity this file will be default.vm

The Layout makes for a great place to include any javascript libraries used by your controllers. For example:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>ForgottenSkies</title>
    <link rel="stylesheet" href="$siteRoot/Content/css/base.css" />
   <!-- We have added the common js files to the project. You can either bring them as static files: -->
        $!head
        <script type="text/javascript" src="$siteroot/Content/js/prototype.js"></script>
        <script type="text/javascript" src="$siteroot/Content/js/scriptaculous.js"></script>
        <script type="text/javascript" src="$siteroot/Content/js/behaviour.js"></script>
        <script type="text/javascript" src="$siteroot/Content/js/formhelper.js"></script>

        $Ajax.InstallScripts()
        $Behaviour.InstallScripts()
        $Scriptaculous.InstallScripts()
        $Form.InstallScripts()

        <script type="text/javascript">
        $!scripts
        </script>
</head>

To dive into this a bit: you’ll notice the use of $siteRoot. This is a NVelocity way of referring to the virtual directory root path. There are a few ‘helper’ functions as well with the ‘InstallScripts’

I use the layouts to wrap up common UI elements to display from page to page. The directive to tell Monorail where to insert the current page is defined as:

<div id="content">$childContent</div>

Again, it’s rather easy to create separate layouts – if you have a controller that you want to take on a separate layout, you can simply define in the attribute and create the corresponding .vm file (assuming NVelocity).

Rescues

Next is the concept of a ‘rescue’. I left this out of the above controller sample – but as with layouts, rescues can be defined on the controller by using the attribute as follows:

[Rescue("generalerror")]
public abstract class BaseController : SmartDispatcherController
{
}

Similiar to a layout, the rescues go into the ‘rescues’ folder under Views. Rescues are similiar to the concept of the global application error handler. Basically you can define different views for handling unexpected application exceptions.

Again, the default install of Monorail includes a sample rescue called ‘generalerror’ – as you can see below, it uses an NVelocity ‘macro’

#macro(showexception $exc)
<b>$exc.GetType().Name</b>

Message:
$exc.Message

#if($exc.StackTrace)
StackTrace:
$exc.StackTrace
#end

#if($exc.InnerException)
<b>Inner exception:</b>
#set($inner = $exc.InnerException)
#showexception($inner)
#end
#end

<h2>Unexpected error happened</h3>

<p> This is the rescue page. See the exception details below </p>

<pre>
#set($exception = $context.LastException)
#showexception($exception)
</pre>

As with layouts, you can define unique rescues per controller.