About the author

Brian Keating is a developer addicted to Microsoft Technologies.

Month List

RecentComments

Comment RSS

Deserializing Json

clock April 11, 2012 13:16 by author Brian Keating |

 

With this post I’m back to my lovely OneNote screen clippings, my last few postings were done on Windows8 and I’d no OneNote installed.

So you want to Deserialize Json in .NET! (C#)

How do you go about it?

There are a few approaches, many poeple are familiar with JSon.NET and using it like this

image

or

image

Some people may have done it the hard way

image

But if you add assembly System.Net.Http.Formatting.dll you’ll get a nice little extension ReadAsAsync<T>
http://msdn.microsoft.com/en-us/library/hh836073(v=vs.108).aspx

image

Enjoy!




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)

 




Reading a file in Windows 8 html5 js

clock February 25, 2012 00:38 by author Brian Keating |

 

Hi again, this is my last post were I compare the same WinRT application written in three different ways.

  • C++ / Xaml
  • C# / Xaml
  • JavaScript / html

My previous post covers c++ and c#, this one covers javascript.

JavaScript / html

image

image

I have to admit, this really took me by surprise! It was pretty painless. I had it written off before I even tried it, but this task proved somewhat simplistic. I’d one little obstacle trying to use a CDN, but other than that it was trivial.

So the penny has dropped, the WinRT developer pool is going to be massive! I predict good things.
If Microsoft play their cards correctly it will be a very successful platform (even more so with the promises of WP8 portability).

So what didn’t I like about this particular app? Not much really, other that realising I’ve a lot more talent to content with Winking smile

 

Summary

So I compared the three different approaches, for the task in question c#/xaml or js/html won hands down.
C++ was overkill.

I think each option would have to be considered on an application per application basis.

 

btw: on a non related note: my wife has just switched on the bedroom networked TV and windows 8 on the laptop here in the sitting room started installing stuff

image

I’m sure it’s got to be cool, if only I knew what for Smile




Reading a file in windows 8 CPP vs CSharp

clock February 24, 2012 14:22 by author Brian Keating |

I left my last blog very indecisive, would I use CPP, would I use .NET or would it be html/js.

Again I’m thinking Cpp is really for faster and better performance, and while it might even be the hands down winner on ARM architecture, I don’t expect to see any performance differences in the app I’m going to write.

I’m actually going to write the same application 3 times, and I’ll review my findings as I go along.

I’ll present the c++ and the c# apps here and the html/js will follow in the next blog post.

First up was the cpp. To be honest I did find this painful to write, the syntax is pretty convoluted. At least the markup for cpp is Silverlight so that was a no brainer.

<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
    <Button Content="Open" HorizontalAlignment="Left" 
         Height="4" Margin="84,45,0,0" VerticalAlignment="Top"
         Width="194" Click="Button_Click"/>
    <TextBlock HorizontalAlignment="Left" Height="381" 
        Margin="282,45,0,0" Text="TextBox" VerticalAlignment="Top" 
        Width="1065" x:Name="tb1"/>
</Grid>

I’ll even use the same markup for the C# application.

Now to the code

C++

#include "pch.h"
#include "MainPage.xaml.h"
 
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace Windows::Storage::Streams;
using namespace Windows::Foundation;
using namespace CppApplication17;
 
MainPage::MainPage()
{
    InitializeComponent();
}
 
MainPage::~MainPage()
{
}
 
void CppApplication17::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
 
    auto openPicker = ref new FileOpenPicker();
    openPicker->SuggestedStartLocation = PickerLocationId::Desktop;
    openPicker->FileTypeFilter->Append(".log");
    auto pickOp = openPicker->PickSingleFileAsync();
 
    TextBlock^ content = tb1;
 
    pickOp->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>(
    [content](IAsyncOperation<StorageFile^>^ operation)
    {        
        StorageFile^ file = operation->GetResults();
        if (file)
        {
            //content->Text = file->FileName;
            auto openOp = file->OpenForReadAsync();
            openOp->Completed = ref new AsyncOperationCompletedHandler<IInputStream^>(
            [content, file](IAsyncOperation<IInputStream^>^ readOperation)
            {
                auto stream = readOperation->GetResults();
                auto reader = ref new DataReader(stream);
                auto loadOp = reader->LoadAsync(file->Size);
 
                loadOp->Completed = ref new AsyncOperationCompletedHandler<unsigned int>(
                [content, reader](IAsyncOperation<unsigned int>^ bytesRead)
                {
                    auto contentString = reader->ReadString(bytesRead->GetResults());
                    content->Text = contentString;
                });                
                loadOp->Start();
            });
            openOp->Start();
        }
    });
    pickOp->Start();
}

 

C#

using System;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
 
namespace CSharpApp12
{
    partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        async private void Button_Click(object sender, RoutedEventArgs e)
        {
            var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            openPicker.FileTypeFilter.Add(".log");
            var file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                uint size = (uint)file.Size;
                var inputStream = await file.OpenForReadAsync();
                var dataReader = new DataReader(inputStream);                
                tb1.Text = dataReader.ReadString(await dataReader.LoadAsync(size));                
            }
        }
    }
}

 

 

Now I’m not going to explain every trivial detail, but’s here where I felt I c# won out.

  • C++ 11 lambda syntax is a bit clumbsy, I don’t like having to pass down my closure variables or having to make a local copy first
  • C++ intellisense is vastly inferior, to the point of being just painful. Lets be honest, tooling cannot be under estimated when it comes to productivity. (this is why I when I write Java I find that only since i started using IntelliJ has my speed really ramped up, it’s the right tool for my background.)
  • I’m fast at typing, but using . is a lot faster than –> for pointers.
  • The async await construct is just magical!, now, to those you who I’m sure will complain that I’m comparing apples with oranges, you have a bit of a moot point, in C++ I could have used the parallel patterns library to make it a little neater, but nowhere near as close to C#.

My next post I’ll rewrite the same application in html + js. I predict that the syntax is not that difficult but productivity is where I feel I may fall down… let’s see.. It promises to be interesting.




It’s COM Jim, but not as we know it!

clock February 21, 2012 23:52 by author Brian Keating |

 

Those of you that started out in windows c++ like me are likely familiar with COMPunch, COM+Ghost, DCOM Ninja
If you stayed in unmanaged land then you’ve probably still very familiar with, ATL, HResults etc.
However if on the other hand, like me, you progressed into the managed realm, then those icons above probably sum up your recollections.

For me I once considered myself pretty hot in C++ (shamefully I still do but I’m sure I’d have to spend a week hands on to really tick that box), COM collections on stl (ICollectionOnSTLImpl) were a walk in the park, multiple inheritance was a given and finding you didn’t release a COM reference was the highlight of your day. But, fast forward a few years and then you really scratch your head as to why life had to be so difficult.

Well I’ll answer that question, performance is by far and above one of the biggest factors. With Windows8 fast approaching you may be starting to panic a little, I guess even more so if you started you coding life in a managed kingdom, but fear not, and let me dispel some common misconceptions that are solved with the C++ Component Extensions (C++/CX for short)

  • COM means HRESULTS – No, C++/CX gives yields exceptions from the underlying Fail HResults.
  • COM means no returns – No, C++/CX allows return values
  • COM means reference counting – Kinda, but you don’t have to worry about AddRef and Release, you use the “ref new” keyword and C++/CX does the reference counting for you (not garbage collection!)
  • COM mens CoCreateInstance etc - Again C++/CX ref new takes care of this for you
  • COM means interfaces - C++/CX takes care of IUnknow/IDispatch, if fact IDispatch has been superseded.
  • COM means no inheritance - C++/CX takes care of this for you.

So will I develop my apps in C++/C#/JS+Html (come on don’t expect me to add VB.NET that battle was lost a long time ago Smile.

Well here’s my feelings:

  • C++ maybe, depends on how much pref i need from my machines (sacrificing time to market), if i want to use an existing library,  Parallel patterns library, C++ AMP etc.
  • C# yes, I like this language and it’s a RAD language (albeit i won’t have access to the full Framework)
  • JS+HTML, I’m not sold on this yet, maybe, if i want to produce for the web then I choose js+html+asp not silverlight, would I ever have enough of a code base to reuse on WinRT??… jury is out..