Html helper for showing line breaks from a text area in ASP.NET MVC

5 Apr

This is a quick tip. When getting started with ASP.NET MVC I used to have problems for example when I got some user input inside a textarea and wanted to show this text with the html <br /> tags instead of the system newlines.  I couldn’t get it to work. The line breaks never used to display and the text displayed as one really long paragraph.

So I created this simple custom html helper that takes input from your source and properly formats it to show the line breaks. For lack of a better name,  I called it FormatLines. Here’s the code.


namespace WebUI.Helpers
{
    public static class FormatLinesHelper
    {
        public static string FormatLines(this HtmlHelper helper, string stringToFormat)
        {
            StringBuilder sb = new System.Text.StringBuilder();
            StringReader sr = new System.IO.StringReader(stringToFormat);
            string buffer = null;
            do
            {
                buffer = sr.ReadLine();
                if (buffer != null)
                {
                    sb.Append(buffer);
                    sb.Append("<br />");
                }
            } while (buffer != null);

            return sb.ToString();
        }
    }
}

Usage.

Before you use it make sure to compile the code and import the namespace containing this helper method. You can do the import right in your target view like so …

<%@ Import Namespace=”WebUI.Helpers” %>

or include it in the web.config file under the namespaces section like so …

<add namespace=”WebUI.Helpers”/>

Use the helper anywhere in your view like so …

<%= Html.FormatLines (Html.Encode(Model.Notes)) %>

And your text will clearly be displayed with the new lines.

If you look at the source of the page, you’ll see the <br /> tags placed where your new lines used to be.

Hope this was helpful,

Till next time, yours truly.

ASP.NET MVC 2 Partial Validation

17 Mar

This post was inspired by the technique from Steven Sanderson’s blog post on this same topic.  Since the introduction of validation with the DataAnnotations, the behavior with ASP.NET MVC 2 now is that the framework validates all your model fields when you post a form, regardless of how many fields the form submitted.

This brings some frustration if you need to do some partial validations.  For example if you need to validate just a subset of the fields in your model, and you create a view just for those fields, but when you submit the form you see errors for all the other fields in your model that were not shown in the view. This will bring some confusion for your users.

Partial Validation in Asp.NET MVC

I recently had this scenario where I had a model that goes through four stages. A user creates a document (View 1), submits to the first approving officer(View 2) who approves and submits to the second approving officer(View 3) , who approves and finally submits the approved document back to the initial user(View 4).  Each step has a different view, all of which are bound to the same model. I wouldn’t want the second approving officer to see errors for the third approving officer, etc.

So I tried to use the custom filter “as is”  from Steve’s blog post but it didn’t work.  UpdateModel was throwing the model errors without applying the filter.  I coudn’t trace the source for this behavior. So I modified the code into some kind of a hack just to get the job done, right there in the controller Action.

How it works

I wrap the UpdateModel process in a try catch.  When it throws and exception I catch it and clear all the errors from ModelState for the model fields that were not included/posted in the form.  I then validate the model, now for the fields that were posted with the form and catch any model errors . I then resubmit the view with the right error messages.  It works like a charm.


[HttpPost]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Document doc = GetDocumentFromDB(id);

            try
            {
                var valueProvider = formValues.ToValueProvider();

                try
                {
                    //tries to update all properties in the model
                    //throws an exception for properties  which were not posted in the form
                    UpdateModel(doc, valueProvider);
                }
                catch (Exception)
                {
                  //clear all the errors for the properties whose values were not posted by the form

                   var keysWithNoIncomingValues = ModelState.Keys.Where(x => !valueProvider.ContainsPrefix(x));

                    foreach (var key in keysWithNoIncomingValues)
                    {
                        ModelState[key].Errors.Clear();
                    }
                }

                //Now we validate only against those properties whose values were posted in the form.
                if (ModelState.IsValid)
                {
				// do your stuff here

                       //commit changes to the database
                        docsRepository.SaveChanges();
                else
                {
                    return View(doc);
                }
            }
            catch (Exception)
            {
                return View(doc);
            }

        }

And thats it.  If you can find a way to create an action filter for the functionality then it’ll be even better because you can use the same attribute in different places in your code and hence DRY.  Hope it was helpful.  Till next time, yours truly.

Custom Action Filters in ASP.NET MVC

23 Feb

In this post we are going to see how to create a custom action filter in ASP.NET MVC.  I am still using MVC 1 but I’m sure this’ll work just fine with MVC 2. I’ll update the post if it works differently on MVC 2.

See this link for an overview of action filters.

Say you have this problem like I did in one of my recent projects.
I needed to show a company logo on all pages but the home page. I know there are a million ways of doing this but I chose to use a custom action filter.

Here’s how I did.

Step 1.
I created a folder called Helpers and added the following class.  The only thing you need to do is inherit from ActionFilterAttribute class. For this particular case I am making the filter work with non AJAX, GET requests only. Notice that I am only adding some text ViewData which will be passed by the action method where we will apply the filter.

public class DataForMasterPageAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //work fot GET requests only
            if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
                return;

            //DO NOT work with AJAX requests
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                return;

            filterContext.Controller.ViewData["message"] = "NoLogo";
        }

    }

Step 2.
I applied the filter on my action method in the controller, in this case its the index action method which serves my homepage ( where the logo is not needed)

        [DataForMasterPage]
        public ActionResult Index(int? page)
        {
            //implementation
            return View();
        }

Step 3.

I added a simple conditional check on the master page thats checks if the page has the viewdata we passed with the filter. If it doesn’t exist we show the logo. If it exists we know its the home page so no logo is shown.

Simple as that.

<% if((string)ViewData["message"] == null){ %>
    <img src="../../Content/images/logo.jpg" alt="logo" height="77" width="263" />
 <% } %>
  

And that’s it.
This is just a very simple way to use custom filters. You can do much more powerful stuff with them.
Till next time, yours truly.

Extending NerdDinner: Using AJAX to cancel RSVPs

4 Dec

This is my first post on ASP.NET MVC.  So I decided to choose something small to start with. I’m going to add functionality to the Nerddinner application that will enable users to cancel their RSVPs using a simple AJAX call to a controller.

Okay, if you totally have no idea or clue about what I’m talking about, have a look here, download and read this pdf here and then see the definition below from wikipedia.

The ASP.NET MVC Framework uses a Model-view-controller pattern. Microsoft added this framework to ASP.NET. It allows software developers to build a Web application as a composition of three roles: ModelView and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that

I personally love ASP.NET MVC. Having a strong background in windows development, I totally get it. I didn’t get webforms at all. I tried, but it was too much for me. When I saw MVC for the first time I couldn’t help saying “hellow beautiful!” Its simple and straight forward.

Okay enough talking lets see some code now.  I’ll skip all the deep explanations by assuming that you have read the e-book and probably have built the nerddinner application.  So I’ll go straight to the code and details.

This is how a particular dinner looks like after you log in but before you RSVP.

When you click the link to RSVP you see a smooth animation confirming you reservation, like the image below shows.

And when you come back to the dinner, if you are logged in you’ll just see a notice that you are registered for the event but no option whatsoever for you to Cancel your RSVP, incase you change your mind or you couldn’t make it.

Cancelling RSVPs

Our aim is to enable the user to cancel their RSVP. And we’ll do this using a simple AJAX call to an Action method in the dinners controller.

Steps.

We’ll accomplish this in as a  few as three steps.

1. Create a DeleteRSVP method in dinner repository

The method takes a RSVP as a parameter and deletes it from the database.

Here’s the code,  one line thanks to LINQ to SQL.

public void DeleteRSVP(RSVP rsvp)
{
db.RSVPs.DeleteOnSubmit(rsvp);
}

2. Add an ActionResult method in the DinnersController.  Name it Cancel

The method takes a dinner ID and checks to see if the current user RSVP’d for the dinner. If yes, it cancels the RSVP (by calling our DeleteRSVP method above) and returns a simple message as content. We’ll use some javascript code to display the message to the user with some animation.  See the code below.

// AJAX: /Dinners/RSVPCancel/1

[Authorize, AcceptVerbs(HttpVerbs.Post)]
public ActionResult Cancel(int id)
{
Dinner dinner = dinnerRepository.GetDinner(id);

if (dinner.IsUserRegistered(User.Identity.Name))
{
RSVP rsvp = dinner.RSVPs.Single(r =&amp;amp;gt;       r.AttendeeName.Equals(User.Identity.Name,       StringComparison.InvariantCultureIgnoreCase));
dinnerRepository.DeleteRSVP(rsvp);
dinnerRepository.Save();
}
return Content("Sorry to hear you can't make it! ");
}

3. Add an Ajax.ActionLink to the partial view RSVPStatus.

The Ajax.ActionLink will call our CancelRSVP in the dinners controller and display an animation notifying the user that we are sorry to see them go.  See the full code for the view at the end of the post

Thats it.  Now if a user is logged in and registered for a dinner, they’ll see a link offering to cancel the RSVP (like on this image below.)

When they click the link, our view will call the cancel action method in our dinners controller and cancel the RSVP on the fly, without a full refresh of the page . The user will get an animated notification as shown on the image below.

So thats all. Simple functionality which I think would take longer and be more dificult to implement in web forms..well, at least for me. Till next time, yours truly.

Full Code for the RSVPStatus View. Sorry for the image quality wordpress wouldn’t allow me to post anything with even one line of javascript.



Framework Dependency & Software Deployment Issues

16 Oct

I love Microsoft.  Simply because a big part of my career relies on their products and they have products that make my job a little bit easier. But sometimes they piss me off. There, I said it.

When are we ever going to catch a breath? I mean with the speed they are releasing stuff, it’s hard to keep up. And it’s hard to stick to one product, because I agree that the new products they release make it easier to write software, but you need time to learn and get comfortable with the new versions, and by the time you are comfortable and ready to do the magic, KA-BOOM!! There is a newer version 4.x

42-15251289

My problem with this issue specifically is that I think MS if forgetting those of us in the growing market. I mean let’s take the .Net framework for example. Vista ships with .Net Framework 3. With my country, Tanzania as an example, very few people/companies are using Windows Vista. Most of the users there are still on windows 2000 with some of them using windows XP.

The Internet Speed Problem.

The internet here in Africa is still an issue. The speeds are very low and very few can afford speeds of up to 1.0 Gbps. Which cost a fortune by the way. I’d say 90 percent are in the ranges or 400 – 1024 KBps. So you’ll understand when I say it’s a pain for someone to download a 20MB file. So when I write an application based on the .Net Framework 2.0, I’d have to download the runtime setup file, and find some means of getting that to the client and installing it on every machine that’s going to use the application, before I install my 2MB application. Talk about pain.

Deployment Issues.

Now I’d like to say that the .Net Framework 3.5 makes it real easy to write data access or all kinds of applications, with the release of LINQ and other stuff in this version. Writing applications has been simplified a lot, and I love this framework and would love to write all my applications using this version. But now I am still forced to use the old framework 2.0 because of the smaller size of the runtime installer.

The problem is this. The .Net framework 3.5 runtime installer is 200MB. That is TWO HUNDRED megabytes. If I write and application based on the framework, say my application is 5MB. I’ll have to download, and install the 200 MB runtime version on every client machine that’s going to use my 5MB application.

Say I wanted to send my application installer by email to a client who’s like in another country. The prerequisite in order for the application to run on the user machine will be the 200MB .Net Farmework runtime. With a internet speed of 250Kbps, do you know how long it’s going to take to download the installer? 2 years that’s how long it’s going to take.

42-15251289

For a user, or anyone really, this doesn’t make sense. Why didn’t MS create a smaller runtime version which could be like 30 MB or something in that range, that can be downloaded in a day or two with our slow 20Kbps connections??

Scott Hanselman has a website here which is supposed to read your machine and advise you on the smallest framework to download or something like that.  If you do not have any version of the framework on your machine though, it’s still 200MB for you to download.

We can’t resist innovation and forward movement in terms of software development and tools that make the process a little less painful. What we are asking is for the big software vendors to think about us and make it a little easier for us to distribute the software as well. Otherwise it’ll be just hard to adopt to the new changes if they make it even harder for us to distribute our work.

An Overview of Processes and Threads in .Net

24 Sep

It’s been a while since I last posted. I had been tied to projects and couldn’t escape to update the blog. But now I am back and ready to roll.

Today I’ll define the differences between a Process and a Thread. First things first, let’s see the definitions.

A process:

Simply put a process is a term used to describe the set of resources (such as external code libraries and the primary thread) and the necessary memory allocations used by a running application.

For each .exe loaded into memory, the OS creates a separate and isolated process for use during it lifetime. Using this approach to application isolation, the result is a much more robust and stable runtime environment, given that the failure of one process does not affect the functioning of another.

Every win32 process is assigned a unique process identifier (PID).

A Thread:

A thread can simply be defined as a path of execution within a process. The first thread created by a process’s entry point is called the primary thread.

Every Win32 process has exactly one main thread that functions as the entry point for the application. A Win32 Graphical User Interface (GUI) application defines a method called WinMain() as the application entry point, while a console based application defines the Main() method as the entry point.

process-thread relationship

The .Net Framework provides the System.Diagnostics namespace that offers, among others, some types that help with the interaction and manipulation of processes programmatically.

This code below for example will enumerate and list all the running processes and all the active threads running under each process.

I will not go into the details of explaining all the keywords in the code at this moment, but this is simply to further elaborate the differences between a Process and a Thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//for processes
using System.Diagnostics;

namespace ThreadvsProcess
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("xxxxx Processes and Threads in .Net xxxxx\n");

ShowRunningProcesses();

//press Enter to exit
Console.ReadLine();
}

static void ShowRunningProcesses()
{
// List all the processes currently running on the local machine.
Process[] allProcesses = Process.GetProcesses(".");

// Show the Process ID (PID) and name of each process.
foreach (Process p in allProcesses)
{
string details = string.Format(" Process ID: {0}\tName: {1}",
p.Id, p.ProcessName);
Console.WriteLine(details);
//show the Threads running under this process
DisplayThreadsForPID(p.Id);
}
Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
}

static void DisplayThreadsForPID(int pID)
{
try
{
Process currProc = null;
currProc = Process.GetProcessById(pID);

// List out the details for each thread in the specified process.
Console.WriteLine(" Threads used by: {0}",
currProc.ProcessName);
ProcessThreadCollection allThreads = currProc.Threads;
foreach (ProcessThread th in allThreads)
{
string detail =
string.Format(" Thread ID: {0}\tTime Started: {1}\tPriority: {2}",
th.Id, th.StartTime.ToShortTimeString(), th.PriorityLevel);
Console.WriteLine(detail);
}
Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
}
catch (Exception)
{
//ignore the exception for simplicity
return;
}
}

}
}

If you run this code, you’ll see the output similar to the one shown in the  image below depending on the processes currently running on your machine.

output

There’s a lot more you can do with Processes and Threads apart from just enumerating and dumping them to the console window and this was just a scratch at the top to show the differences between the two.

Till next time, yours truly.

Sorting by IComparable vs IComparer

29 Jun

These are two interfaces that used to confuse me. I didn’t know when to use one or when to use the other. The aim of this post is to make it easier for someone to understand the differences and choose appropriately.

In as a few words as possible:
i)A class that implements IComparable can be sorted or compared to another class instance in a manner that you define.

ii)A class that implements IComparer can be used to sort or compare classes that do or do not implement IComparable.

The List.Sort() Method.

Every list(generic list, array, arraylist) has a built-in method called Sort(). The Sort() method knows how to sort all objects that implement the IComparable interface. The method uses an object’s CompareTo() method to compare it with other objects and use its return value to figure out which object comes first.

To sort objects that do not implement IComparable, you have the IComparer Interface. It’s used to assist the list’s Sort() method in sorting its members.

IComparable.
You implement this within the class you want to be sorted. The interface has only one method called CompareTo() that takes an object as a parameter, compares it with the class and returns an integer value that figures out which object comes first.

See the sample class below.

Public Class Person
    Implements IComparable(Of Person)
    'these should be properties
    Public FirstName As String
    Public LastName As String
    Public Age As Integer

    Public Sub New(ByVal first As String, ByVal last As String, ByVal age As Integer)
        Me.FirstName = first
        Me.LastName = last
        Me.Age = age
    End Sub

    Public Function fullName() As String
        Return Me.FirstName & " " & Me.LastName & ": Age - " & Me.Age
    End Function

    Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo
        If Me.Age > other.Age Then
            Return 1
        ElseIf Me.Age < other.Age Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

Notice the CompareTo() method. It takes another Person class as a parameter, compares the Ages and returns a number indicating
which one comes first. In this method you can create any sorting logic that you need.
You could for example compare by Age, FirstName or Lastname. In this sample the classes will be sorted by Age.

Implementation:
One you have a list of objects that implement IComparable, all you have to do to sort them is just call the List.Sort() method without
passing any parameters. See sample code for a button bellow.

Dim list As List(Of Person)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        list = New List(Of Person)
        list.Add(New Person("Nick", "Masao", 27))
        list.Add(New Person("Sydney", "Mtaita", 3))
        list.Add(New Person("Ruth", "Mtaita", 23))

        Debug.WriteLine("")
        Debug.WriteLine("Unsorted:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

'Just call the sort method without passing any parameters and you are done
‘The Sort() method uses the logic in the CompareTo() method in the class to ‘sort the list members

        list.Sort()

        Debug.WriteLine("")
        Debug.WriteLine("Sorted by Age:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next
End Sub

The code produces the following output.
IComparable_Output
As you can see the objects were sorted by age.

IComparer.

Implement this in a class that you will use to sort other classes that may or may not implement IComparable. This class will be a ‘comparer’ and will impose the sorting order in the List.Sort() method. The interface has only one method called Compare() that takes two objects and returns a value which determines which object comes first.

To sort a list using IComparer, you need to create a new instance of the class that implements it and pass that instance to the List.Sort() method. The list object will then use the class’s Compare() method to sort the members.

Say for example you have a person class with the following definition.  Note that it doesn’t implement any interface.

Public Class Person
    'these should be properties
    Public FirstName As String
    Public LastName As String
    Public Age As Integer

    Public Sub New(ByVal first As String, ByVal last As String, ByVal age As Integer)
        Me.FirstName = first
        Me.LastName = last
        Me.Age = age
    End Sub

    Public Function fullName() As String
        Return Me.FirstName & " " & Me.LastName & ": Age - " & Me.Age
    End Function
End Class

Now to use IComparer to sort a list of objects like the above, you need to create a simple class that implements IComparer and define the sorting manner, like so.

Public Class PersonComparer_ByAge
    Implements IComparer(Of Person)

    Public Function Compare(ByVal x As Person, ByVal y As Person) As Integer Implements System.Collections.Generic.IComparer(Of Person).Compare
        If x.Age > y.Age Then
            Return 1
        ElseIf x.Age < y.Age Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

The Class sorts the Person objects by Age. You could also sort by FirstName or LastName. The only limitation of
IComparer is that it has access to public members of the class only.

See another class that implements IComparer but this time sorts by the FirstName field.

Public Class PersonComparer_ByFistName
    Implements IComparer(Of Person)

    Public Function Compare(ByVal x As Person, ByVal y As Person) As Integer Implements System.Collections.Generic.IComparer(Of Person).Compare
        If x.FirstName > y.FirstName Then
            Return 1
        ElseIf x.FirstName < y.FirstName Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

Implementation:
If you have a list of objects, and you have a class that implements IComparer and has the sorting criteria like
the above class then you have to do the following to sort your list.

  1. Create an instance of your sorting class.
  2. Pass that instance to the list.sort() method.
  3. That’s it.

Sample button code that implements the code above.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        list = New List(Of Person)
        list.Add(New Person("Nick", "Masao", 27))
        list.Add(New Person("Sydney", "Mtaita", 3))
        list.Add(New Person("Ruth", "Mtaita", 23))

        Debug.WriteLine("Unsorted:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

        Debug.WriteLine("")

'instantiate the sorter/comparer class that implements IComparer

        Dim sortName As New PersonComparer_ByFistName

'pass it as criteria to the sort method

        list.Sort(sortName)

        Debug.WriteLine("Sorted by Firstname:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

        Debug.WriteLine("")
'instantiate the comparer class and pass it to the sort method
        Dim sortAge As New PersonComparer_ByAge
        list.Sort(sortAge)

        Debug.WriteLine("Sorted by Age:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next
    End Sub

The above code produces the following output.

IComparer_Output

Advantages & Limitations.

The advantage of IComparable is that you have access to the private members. i.e you can create your sorting criteria using private members in the class since the CompareTo() method is withing the class. The limitation is you only have that one way of sorting.

The limitation of IComparer is that the object that implements it doesn’t have access to private members of the objects it sorts. It only has access to public members.

Its advantages are, as seen in the sample code above, you can create a number of sorting options, and you have the option of passing the more specific and more appropriate sorting criteria to the Sort() method.

This post is getting too long  and I think I’ll end it here. Hopefully it was an eye opened of some sorts. Till next time, yours truly.

Follow

Get every new post delivered to your Inbox.