Register | Login

Stacking Code

public interface IBlog { string Dump(Stream consciousness); }

Simple Messages in ASP.NET MVC

Saturday, 4 December, 2010 @ 3:47 PM < Adam Boddington
Tags: ASP.NET MVC, Building Neno, CSS

This is post #11 in the Building Neno series. Please click here for a description of the Building Neno project and instructions on how to access the source code for this post.

Before I can start building screens, I need a simple yet effective way to stack up messages I want displayed to the user. This probably belongs in Moja, so I will start a new project for the dependency on MVC. I'll call it StackingCode.Moja.Web.Mvc.

Say Something

I need to communicate text. In addition, I want a message type to help communicate the severity of the text. So the first order of business is to create a simple message class to hold that information.

public enum MessageType
{
    Information,
    Warning,
    Error
}

public class Message
{
    public Message(MessageType type, string text)
    {
        Type = type;
        Text = text;
    }

    public MessageType Type { get; private set; }
    public string Text { get; private set; }
}

Recording

There may be more than one message. Whether an action generates two messages by itself, or redirects to another action which generates an additional message, I want to collect all the messages until I get a chance to display them to the user. So I need a message collection. Some convenience methods for creating messages might also be useful.

public class Messages : IEnumerable<Message>
{
    public Messages()
    {
        MessageList = new List<Message>();
    }

    private IList<Message> MessageList { get; set; }

    #region IEnumerable<Message> Members

    public IEnumerator<Message> GetEnumerator()
    {
        return MessageList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return MessageList.GetEnumerator();
    }

    #endregion

    public void Add(string text)
    {
        Add(MessageType.Information, text);
    }

    public void Add(MessageType type, string text)
    {
        MessageList.Add(new Message(type, text));
    }

    public void Add(Exception ex)
    {
        if (ex == null)
            return;

        // Once logging is added, all this stack trace and inner exception information should be removed. There is no need to show it in the UI.

        string text = ex.Message;

        if (!string.IsNullOrWhiteSpace(ex.StackTrace))
            text += "<br /><br />" + ex.StackTrace.Replace(Environment.NewLine, "<br />" + Environment.NewLine).Replace("  ", "&nbsp;&nbsp;");

        Add(MessageType.Error, text);
        Add(ex.InnerException);
    }
}

Storing

In MVC, TempData is preserved between redirects until a request is completely done -- it's the perfect place to store messages. So I'm going to create an extension method to expose the Messages collection on TempData. As long as something can see TempData, it will also be able to see Messages.

public static class TempDataDictionaryExtensions
{
    private const string MESSAGES = "Messages";

    public static Messages Messages(this TempDataDictionary tempData)
    {
        var messages = tempData[MESSAGES] as Messages;

        if (messages != null)
            return messages;

        messages = new Messages();
        tempData[MESSAGES] = messages;

        return messages;
    }
}

Playback

I'll create a partial view for displaying the messages which I'll whack into the master page for now. I want to cycle through each message in order and format them according to message type. The form classes in Blueprint will help nicely with that -- and it's already included.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%
    foreach (Message message in TempData.Messages())
    {%>
<div class="<%=message.Type == MessageType.Error ? "error" : message.Type == MessageType.Warning ? "notice" : "success"%>">
    <%=message.Text%>
</div>
<%
    }%>

Testing, Testing

Time to check if any of this works. Before I do though, I'll make a base controller with a Messages property that short-circuits to TempData.Messages. Just to make usage a bit cleaner.

public abstract class Controller : System.Web.Mvc.Controller
{
    protected Messages Messages
    {
        get { return TempData.Messages(); }
    }
}

Now to throw out some messages in HomeController.Index.

Messages.Add("Asteroid entering system.");
Messages.Add(MessageType.Warning, "Collision course detected.");
Messages.Add(new Exception("Impact imminent!", new Exception("Bruce Willis, save us!")));

Play it, please.

Armageddon

That'll do for now. Eventually I would like to pair it up with logging, but that's a fair way down the track.

There are 0 comments.


Comments

Leave a Comment

Please register or login to leave a comment.


Older
Configuring Spring

Newer
Implementing OpenID in ASP.NET MVC

Older
Configuring Spring

Newer
Implementing OpenID in ASP.NET MVC

browse with Pivot


About


Projects

Building Neno


RSS
Recent Posts

Codility Nitrogenium Challenge
OS X Lock
HACT '13
Codility Challenges
Priority Queue


Tags

Architecture (13)
ASP.NET (2)
ASP.NET MVC (13)
Brisbane Flood (1)
Building Neno (38)
C# (4)
Challenges (3)
Collections (1)
Communicator (1)
Concurrency Control (2)
Configuration (1)
CSS (5)
DataAnnotations (2)
Database (1)
DotNetOpenAuth (2)
Entity Framework (1)
FluentNHibernate (2)
Inversion of Control (5)
JavaScript (1)
jQuery (4)
Kata (2)
Linq (7)
Markdown (4)
Mercurial (5)
NHibernate (20)
Ninject (2)
OpenID (3)
OS X (1)
Pivot (6)
PowerShell (8)
Prettify (2)
RSS (1)
Spring (3)
SQL Server (5)
T-SQL (2)
Validation (2)
Vim (1)
Visual Studio (2)
Windows Forms (3)
Windows Service (1)


Archives


Powered by Neno, ASP.NET MVC, NHibernate, and small furry mammals. Copyright 2010 - 2011 Adam Boddington.
Version 1.0 Alpha (d9e7e4b68c07), Build Date Sunday, 30 January, 2011 @ 11:37 AM