19 Dec 2013

Ordinal Suffix in C# / .NET e.g. the postfix part of 1st, 2nd, 3rd, 4th

DEFINITIVE ANSWER TIME :)

Here's a natty extension method to get the Ordinal Suffix of a number.

public static string GetOrdinalSuffix(this int number, bool includeNumberInResult = false)
{
 string suffix = "th";
 if (Math.Floor(number / 10f) % 10 != 1)
 {
  switch (number % 10)
  {
   case 1:
    suffix = "st";
    break;
   case 2:
    suffix = "nd";
    break;
   case 3:
    suffix = "rd";
    break;
  }
 }
 return includeNumberInResult ? number + suffix : suffix;
}

Yes, this handles teens correctly i.e.

1: 1st
11: 11th
21: 21st
111: 111th
1011: 1011th

etc.....

16 Dec 2013

Handling File Uploads from Dropzone.js with ASP.NET MVC

I had a need recently on an MVC project to allow the upload of image files. Having a look around to check if I was still using the best tools for the job, I came across DropzoneJS , which is excellent.

However, the documentation is a little terse and there are no MVC integration guides yet, so let me present a sample Controller Action for anyone who wants to simply see how to use it.


public string UploadFile()
{
 string errorMessage = "";

 foreach (var fileKey in Request.Files.AllKeys)
 {
  var file = Request.Files[fileKey];
  try
  {
   if (file != null)
   {
     YourInputStreamSaveMethod(file.FileName, file.InputStream);
     // Hint, google the phrase 'save inputstream file .net'
   }
  }
  catch (Exception ex)
  {
   errorMessage = ex.Message;
  }
 }

 if (errorMessage != "")
 {
  Response.StatusCode = 418; // Teapot Fail!
 }
 return errorMessage;
}
If I helped you out today, you can buy me a beer below. Cheers!