File Upload MCV4 Web API, Knockout.js

 

I wish to follow up on my previous post Uploading a file in MVC4 C#5 .NET 4.5

I promised a few things here, an Ajax client, WinRT, iOs, Droid, This post addresses the ajax upload.

First some background, I’m working on an expense tracking system at the moment, the core technologies involved in this Single Page Application are:

  • ASP MVC4 WebApi
  • Html5 SPA
  • Knockout.js

A fundamental part of this system is the ability to upload receipts.
 image

When the user browses to an image file, it gets converted to base64 and uploaded via a MVC4 Api controller.

Here are the important parts:

Html

image

First we create an image where we can display either the previously selected image or the newly selected image.
We only display this image if it’s in the javascript model.

Secondly we bind the html5 input file with a knockout binding.

Javascript

Model

image

The important parts are the image and imageType properties, there also exists a computed property that joins these two so it can be displayed in an image tag. The reason i keep these separated is that I can’t post the source as is without further encoding.

Knockout Bindings

In knockout.js you are not limited to the built in bindings like, click and value, you can create your own,
I’ve taken https://github.com/khayrov/khayrov.github.com/blob/master/jsfiddle/knockout-fileapi/ko_file.js as my start point, this pretty much does what I want, however I made a slight tweak in that i wanted base64. (basically because I’ve written some of the objective-C iOS app already and didn’t fancy changing it).

 

image

WebApi

image

ExpenseDto

image

All source can be viewed @ https://github.com/brianbruff/Expenses

ASP MVC4 Web API file upload: Unexpected end of MIME

 

So I’ve had a problem uploading a file using a HTML5 input of type file field.

image

For love nor money could I see a problem with the code above (in my defence I’m working on this project late in the evening and have my First dose of Man Flu this year, I’m a 2012 survivor see: www.manfluanonymous.com )

When i get into my server code an exception was getting thrown when i read the multipart post.

image

All the Googling in the world didn’t help me, I saw lots of people adding “\r\n” which I’m still scratching my head over to be honest, I saw others complain about the MVC4 beta..

 

But hang on: I’ve done this before: So what has changed? actually something really silly ,

I simply forgot to set the input name attribute!!!

image

Hope this helps somebody …

Enabling Facebook OAuth in MVC4 SPA

 

There are two steps, the first step is to register a facebook application, after you register you will have a key and password. The next step will be to insert these into you application.

 

Step 1.

    Enable OAuth login using Facebook, Twitter

    Steps to get keys for Facebook

    • Go to the Facebook developers site (log in if you're not already logged in).
    • Choose the Create New App button, and then follow the prompts to name and create the new application.
    • In the section Select how your app will integrate with Facebook, choose the Website section.
    • Fill in the Site URL field with the URL of your site (for example, http://www.example.com). The Domain field is optional; you can use this to provide authentication for an entire domain (such as example.com).
      Note   If you are running a site on your local computer with a URL like http://localhost:12345 (where the number is a local port number), you can add this value to the Site URL field for testing your site. However, any time the port number of your local site changes, you will need to update the Site URL field of your application.
    • Choose the Save Changes button.
    • Choose the Apps tab again, and then view the start page for your application.
    • Copy the App ID and App Secret values for your application, here is what it looks like, I’ve blurred my app id and secret.
    • image
    • Exit the Facebook developer site
    •  

      Step 2.

      Edit your App_Start/AuthConfig.cs with these new settings

       

      image

      That’s it, you can no log in with facebook, see the placeholder template below.
    image

JAX-WS, Eclipse, JBoss

 

Ok another Java post, they are few and far between, but I’ve already polluted this blog with objective-c, javascript and other non .net languages so why not.

So I was lying in bed last night my wife was hogging the windows machine watching some film or other, so I’d a choice between reading 50 shades of grey or firing up my mac book air, no contest there…

 
I recently interviewed a guy that had moved from Apache Axis to JAX-WS, the way he described it sounded a lot like WCF (windows communication foundation) so I wanted to see for myself.

 

  • Install Jboss 7.1.1 for an application server
  • Install Eclipse juno IDE for Java
  • Install Mono Develop (not necessary but i had this already for iPhone dev so thought what the heck I’ll use it for the client)

So what is JAX-WS? The Java API for XML Web Services (JAX-WS) is a Java programming language API for creating web services. It is part of the Java EE platform from Sun Microsystems. Like the other Java EE APIs, JAX-WS uses annotations. Here’s how I created a sample one.

Ensure JBoss can run

Start the standalone shell script and check you can see http://localhost:8080 page below in your browser

clip_image001

Choose JavaEE perspective in Eclipse

clip_image002

Create a new project in Eclipse  (dynamic web)

clip_image003

Add the following webservice class

Complete with annotations

clip_image004

Modify web.xml

Add the highlighted section

clip_image005

Configure the Local JBoss server in eclipse

Right click on the server you added and choose Add/Remove

clip_image006

Add your deployment

clip_image007

Add your current deployment
clip_image008

Start Application Server

Click on the Play button in the server tab toolbar, you should be automatically switched to the Console pane in Eclipse. Take note that your DynamicTest war file is deployed.

clip_image009

Review the JBoss Admin Console

Specifically the Webservice Endpoints, You should see your webservice deployed here.

clip_image010

You can also browse to the wsdl

clip_image011

Create your client

I used C# with the Mono Develop IDE to create a simple Console Application

clip_image012

Just add a Webservice the way you would in Visual Studio (I went for .net 2.0 WS because the WCF version didn’t create an app.config for me (visual studio you spoil me)).

Run

clip_image013

And that’s it your first JAX-WS! (and not a windows machine in sight.. I feel dirty but I like it :-) )

 

 

=== UPDATE ===

Ok after reading a lot of blogs and a few weeks later i've found a nicer way of doing it.

Instead of editing the xml you can choose to add a new webservice and select your webservice class (note screens below are not for the same project but are functionaly the same

 

 

 

Customization of WebApi

 

If you’ve used Asp MVC Web Api then you are most likely familiar with the notion of content negotiation, this is the process where the content returned in the response is dictated by the accepts header in the request. In sort if you request xml you get xml back, if you request json you get json back.

This is done by what we call Formatters. You can of course add your own formatters, e.g. let’s say you have an application that returns human resource details; you may request back a profile picture by hitting the same route with a different request header.

 

OOB Formatters

Lets take a working example, of what we get out of the box (OOB).

Create a new Web Api project

Add the following class

image

Modify the ValuesController as follows

image

We now should be able to run the project and see the following in the browser

image

So by default we get back an xml formatted response, of course we could request json, but what if we just don’t want xml?

Tweaking the config

 

Add the following line to your Global.asax.cs

image

Now add this new GlobalConfig static class as follows

image

Run your application again

image

Now we get json by default, yah!

 

But wait a second, what if I know that I have some javascript developers that want to use this content, wouldn’t be nicer to offer camel casing to these guys?

image 

Run project again

image

e.g some simple jQuery

image

Eureka moment

 

After all these years, where I’ve modified connections strings etc in the web.config release folder.
I’ve finally realised I can preview the transformation that Visual Studio Does. To be really honest I’m not sure if this is a new feature of VS2012 or if it always existed, but it’s fantastic, give it a go if like me you’ve been living in the dark ages.

 

image

image

Removing sensitive data from git

 

Ok, so in my case it was not so sensitive, I had generated a publish profile for one of my projects, that said I don’t want the world and their aunty to be able to publish their apps to my server so I needed to remove my sensitive data from git.

Here’s how

git filter-branch --index-filter 'git rm --cached --ignore-unmatch mySensitive.data' 
  --prune-empty --tag-name-filter cat -- --all
git commit -m "Add Rakefile to .gitignore"
git push origin master –force

 

The above removes the file from history, you could add it to your .gitignore to ensure it’s not accidently added again.

An image button in iOS

 

So as I wait for my second iPhone application to be approved by the apple store, I start to wonder a few little things. How can I improve my existing apps through functionality and user experience.

Given I’m pretty much a noob with iOS dev still compared to most other languages/platforms i know,  you’ll have to pardon me if I’m giving you a bum steer!

I did consider a few options before proceeding down this route:

  • Subclassing UIImageView and handling the touches once I’d enabled interaction,
  • Subclassing UIImageView and using a gesture recogniser

However I found the following method really simple.

Where we are going

Here we see a picture of the iPhone simulator showing my button with an image, this is what we are going to produce.

Screen Shot 2012-11-28 at 22.49.00

How we got there

I fired up photoshop and created a 32x32 png8 for this image, don’t try to figure out what it’s supposed to be, it’s just random drawing…

I then dragged this testButton.png I created to my XCode project

Screen Shot 2012-11-28 at 22.38.55

 

Next in the XCode project you’re working on, drop a button onto your a view in your storyboard/nib, we’re going for image only, so change type to Custom and remove the default title. If you loose selection you can regain it by selecting the button in the ViewController Scene on the left hand side.

Screen Shot 2012-11-28 at 22.39.39  

 

So next some code, first of all, right click (crtl+click) and drag the button onto the ViewController header file (use the assistant editor to help you, we want to create an IBOutlet so we can reference this button

image

Now we’re nearly there, just one line of code to set the image for the normal state.

Screen Shot 2012-11-28 at 22.41.12

That’s pretty much it… I could subclass all this into an UIImageButton but it’s probably overkill unless I go to the hassle of plugging into the XCode designer for image selection etc… something for another day perhaps..

 

Edit

I did say i was a noob yes? Well I quickly came across a problem with the above method in that designing the application became a little difficult setting the coordingates given I had to run the app to see where my button was, not ideal when i'm slicing in parts of my UX.

There's an easier way to select the image for the button... set the background in the property tab!!!! (highlighted below in red)

The lazy singleton pattern revisited.

 

If you want to get a feel for the singleton pattern in C# one of the best resources I always revisit is on John Skeet’s (@jonskeet) website  http://www.yoda.arachsys.com/csharp/singleton.html

I encourage you to read the above article to appreciate the little intricacies or requiring static constructor, BeforeFieldInit, volatile etc.

However: If you just want the easiest lazy evaluation solution in .net4+, then you’ve come to the right place.

image

Lazy<T> guarantees thread-safe lazy construction.

 

UPDATE:

If I’d followed Jon’s notice, at the top of the page I linked to, I would have seen the post is now located here and moreover, he covers the Lazy<T> approach there.

 

 

That pesky iOS keyboard again

 

In my previous post I showed you how to have the keyboard resign first responder status when Return is pressed.

A little tip: is that you don’t need to set the delegate in code like my previous post, you can use the connections pane and Crtl drag from the textbox delegate to the view controller in the Outlets section.

Screen Shot 2012-10-18 at 12.30.27

Still not good enough

I still had a little niggle about this keyboard covering my view, I really wanted to see what I was doing, so here’s my solution.

I move the view up by y amount of pixels (-120pixels in this sample).

Why negative 120? Well given that your y coordinate starts at 0,0 on the top left (i think I’ve just got a flashback of OS/2 having the origin at the lower left corner… shudder…) we move upwards.

Here is our beautiful UX before we start editing

Screen Shot 2012-10-18 at 12.58.12

When the keyboard presents after the textbox gains first responder status it’s now covered.

So we move the view up

image

When we’re finished we move it back down

image

 

So how did we implement this function?

image

We change the view frame to shift the y position, and we did it in an animation to give it a little jazz.. 0.6 seconds is a way too slow for my liking but it does really show off the animation for demo purposes.

Here is what it ends up looking like:

Screen Shot 2012-10-18 at 12.58.28