About the author

Brian Keating is a developer addicted to Microsoft Technologies.

Month List

RecentComments

Comment RSS

Uploading a file in MVC4 C#5 .NET 4.5

clock April 4, 2012 23:11 by author Brian Keating |

 

Back on the bleeding edge again Hot smile I’m in the early stages of my next killer app and I’m investigating the pros and cons of using the new ASP WebApi.

One of the features of this so called killer app will be to upload pictures (nothing special I agree). But how would I do this for all the clients I hope to support (WinRT/WP7/Html5/IOS).

Let me first present the server that will be used for all these clients, I’ll then follow up with what I consider to be the simplest client a html5 browser!

Server

So I fired up VS11 and created a new MVC4 application using .net 4.5 / C#  and the WebApi template.

I then added a controller called FileUploadController.cs

   1:  using System.Collections.Generic;
   2:  using System.Linq;
   3:  using System.Net;
   4:  using System.Net.Http;
   5:  using System.Threading.Tasks;
   6:  using System.Web.Http;
   7:   
   8:  namespace MvcApplication16.Controllers
   9:  {
  10:      public class FileUploadController : ApiController
  11:      {
  12:          public async Task<IEnumerable<string>> PostMultipartStream()
  13:          {
  14:              // Check we're uploading a file
  15:              if (!Request.Content.IsMimeMultipartContent("form-data"))            
  16:                  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  17:                 
  18:              // Create the stream provider, and tell it sort files in my c:\temp\uploads folder
  19:              var provider = new MultipartFormDataStreamProvider("c:\\temp\\uploads");
  20:   
  21:              // Read using the stream
  22:              var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);            
  23:          
  24:              // Create response.
  25:              return provider.BodyPartFileNames.Select(kv => kv.Value);            
  26:          }
  27:      }
  28:      
  29:  }

You can see from line 12 that I’ve made this operation async, you’ve really got to admire the simplicity of async/await construct in .net 4.5! In line 22 you can see that the compiler and some state machine magic allow the freeing up of the asp worker thread….. (If you have read my previous posts you may be a little confused now.. didn’t I say that Tasks will use use the same threadpool!?  have a look at this link for someone that pondered the very same concerns )

 

HTML5 Client

The client couldn’t have been easier, fist a look at it in the browser

image

   1:  <!DOCTYPE html>
   2:  <html lang="en">
   3:  <head>
   4:      <meta charset="utf-8" />
   5:      <title>ASP.NET Web API</title>
   6:      <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
   7:      <meta name="viewport" content="width=device-width" />
   8:  </head>
   9:  <body>
  10:      @using (Html.BeginForm("FileUpload", "api", FormMethod.Post, new { enctype = "multipart/form-data" }))
  11:      { 
  12:          <div>Please select some files</div>
  13:          <input name="data" type="file" multiple>
  14:          <input type="submit" />            
  15:      }
  16:  </body>
  17:  </html>

 

The important part above is using the enctype attribute, in fact line 10 loosely translates to

<form action="~/api/upload" enctype="multipart/form-data" method="POST">
 

Don’t believe me? Then try VS11’s awesome new feature – page inspector

Right click on the html and choose view in page inspector

image

 

 

and we’re done! Of course in the real world we’ll use ajax, e.g. $getJSON but here’s the response in the browser with xml.

image

I’ll hopefully follow up with the samples for the client list below when I get to the respective development machines.

  • WinRT (c#/xaml)
  • iPhone (objective c)
  • Android (java)

 




Full height divs in html5

clock November 26, 2011 22:50 by author Brian Keating |

 

Hi all,

 

This has probably been beaten to death elsewhere, but somehow it’s the first time I’ve ever come across it.

I’m working on the LiveResume website this evening (hey it was this or watch XFactor.

Anyway, I wanted to ensure that all different views of my web app filled the screen, for example if the personal details only occupied 30% of the height, I wanted to containing div to go the whole way to the bottom of the screen given it is a different color.

This secret to this is ensuring that the parent has an explicit height or the div reverts to auto.

So lets look at the simplified sample I’ve put together.

 

<!DOCTYPE html>
<html>
<head>
</head>
 
<style>
BODY {
     BACKGROUND:#ff0000; height:100%; 
}    
#one {
     BACKGROUND:#00ff00; height:100%; 
}
 
#two {
     BACKGROUND:#0000ff; height:100%; 
}
 
</style>
 
<body>    
    <div id="one">    
                
        <div id="two">
            gdxg
        </div>      
    </div>
    
</body>
<html>

This is what the rendered webpage looks like in IE9

image

I was expecting the green section to be full height, I mean this always worked fine before.

 

So what has happened

html5 <!DOCTYPE html>

requires a height on the html element too…and for whatever reason I never noticed this before.

Solution:

Add html to the first style

image

 

image




HTML 5 Audio

clock August 16, 2011 08:21 by author Brian Keating |

 

So does your browser support the html5 audio tag when it comes to MP3s?

Browsers in order of my preference

 

IE9 – Nope

image

 

Firefox 5 – Nope, Moreover doesn't gracefully degrade to my fallback text!

image

 

Chrome 13 – Sure

image

 

Safari 5 – Arguably the best default experience

image

Try for your self and let me know how you get on (excuse the lack of the DOCTYPE, encoding etc.

It’s quote a catchy song, you’ll miss out if your browser doesn’t support it (or you are not familiar with view source Smile )




Sample html5 canvas drawing

clock August 8, 2011 08:16 by author Brian Keating |

 

So how hard is it to draw on a html5 canvas? Well if you ever lived in a GDI+ world like I once did, then it’s pretty simple. In fact it’s somewhat familiar to silverlight/wpf people too, the parameters passed to draw a rectangle for example are , left, top, width, height. (GDI/Windows API people would me more familiar to using left,top,right,bottom (the RECT struct). Nonetheless, IMO drawing with the html5 canvas couldn’t be easier.

image

 

Here’s the code

   1:  @{
   2:      ViewBag.Title = "Home Page";
   3:  }
   4:  <h2>@ViewBag.Message</h2>
   5:   
   6:  <canvas id="canvas" width="300" height="300">
   7:      Canvas not supported
   8:  </canvas>
   9:   
  10:   
  11:  @section Scripts
  12:  {
  13:      
  14:   
  15:      <script type="application/javascript">
  16:      
  17:          $(function() {
  18:              draw();
  19:          });
  20:      </script>
  21:   
  22:      <script type="application/javascript">
  23:          function draw() {
  24:              if (Modernizr.canvas ) {
  25:                  var canvas = document.getElementById("canvas");
  26:                  var ctx = canvas.getContext("2d");
  27:   
  28:                  ctx.fillStyle = "rgb(200,0,0)";
  29:                  ctx.fillRect(10, 10, 100, 1000);
  30:              }            
  31:          }
  32:      </script>
  33:  }

That’s all you need to get started, there are some nice libraries starting to emerge that use html5 canvas (graphing etc)




Progressive Enhancement with Modernizr

clock July 16, 2011 00:16 by author Brian Keating |

 

If you’ve been to a HTML5 session or lived in the html5 world for any length of time you’ll have come across the term “Progressive Enhancement”. It’s about taking a base application that works on downstream browsers and detecting features and increasing functionality if you have certain features.

Take example local or session storage, in older versions of browsers there was no local storage so there would be more round tripping.

So how do we detect these features? One method is a javascript file called Modernizr that detects feature availability (rather than using a database etc).

Syntax:

   1:  if (Modernizr.localstorage) 
   2:  {    
   3:      // browser supports local storage
   4:  }
   5:  else 
   6:  {    
   7:      // browser doesn't support local storage
   8:  }
   9:   

 Check out modernizer it's got many detection and abstracts you from detection techniques.

You’ll get this script added to your project for free in MVC3.