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

IPhone: remove the IOS Keyboard on Return

Ok this is another XCode/ Objective-c/ IOS post. Stop reading now if you feel sick MSFT fans Winking smile

So you’ve written an app and you test out that new data entry field only to find out that the keyboard covers you action buttons and you can’t get it to disappear,,, we’ve all been there, now I’ll explain how to stop this happening.

Add a new protocol to your controller

What does this mean? well to people from a c# background think of it as an interface where the methods can be optional. We add this interface to our Controller much the same way syntactically that specify generic types in c#

Screen Shot 2012-09-18 at 13.47.40

TextFieldShouldReturn

Next we implement the method in the protocol that we are interested in. We do two things in this method, first we call a function on the textField to resign the first responder and then we return YES.

Screen Shot 2012-09-18 at 13.53.17

Set the delegate

So we are nearly there, we just need to hook up the textField and the delegate, we do this on the viewDidLoad function.

Screen Shot 2012-09-18 at 13.55.03

That’s pretty much it.

SignalR chat on Azure

 

At lunch today I created a little fun website and it only took about 15 minutes (as you can plainly see from the styling).

Technologies

The technologies involved were

  • Azure (website)

  • SignalR

  • Asp MVC 4

  • .NET 4 (because at the time of writing Azure doesn’t support .net 4.5 not that I need it).

  • Let me explain how I did it, the reason I did it was simple, I was sick to death of seeing all these posts on SignalR without actually having used it. Asp MVC is my choice of web tech these days so that was a foregone conclusion, and Azure has provided 10 free Azure websites for these sort of sites.Here we see the main page with an eductational video
    image

    Here we see a test with two local browsers
    imageStep 1.Create a ASP MVC4 Web internet web application, add a Chat controller. Add a view for the Index method.
image
    Step 2. Import the SignalR package
image
    Step 3. Add the following class to your project.
image

 

Step 4. Add the following javascript to your project

image

 

Step 5. Check it out for yourself, www.manfluanonymous.com

I left it running earlier and these are the messages that people entered over the last few hours.

image

Disclaimer: I copied the SignalR code from someone on the net, if i could remember who I’d give credit.

Kendo Datasource & MVC4 WebApi, you broke my heart

 

So I’ve spend many a sleepless night this week knowing that the webapplication i was working was not doing server side paging…

This morning I decided I needed to remedy that and was I in for an experience Smile

At first I was thinking why oh why had the kendo guys not got the finger out and implemented WebApi support… and I’ve come to the conclusion that they didn’t waste any time on a moving platform…. in fact I'd go as far to say as the platform was actually removed with MVC4 RTM… let me explain….

OData support

 

I’ve previously mentioned that the MS guys are going to provide a more robust OData support, this is a good thing, there’s currently an alpha package for those who date http://www.nuget.org/packages/Microsoft.AspNet.WebApi.OData

However what I failed to notice was that they removed the existing OData support altogether!!
Don’t get me wrong i think this was a good decision not ot have a half implemented solution with a fuller one on the way, it’s just it’s gone and broken many of my WebApis Sad smile

Not to worry, we are where we are and now I need the WebApi to support paging, which previously relied on OData $top $skip $count.

So here is my current solution.

Server

Return:

My return values now have a Total and the Data, I used the following class to help me out here.

image

Parameters

I added some new classes for Pagable parameters, note the Take, Skip,Page,PageSize are sent with kendoui datasource (from fiddler)

image

ApiCall

Here is a sample API call, as previously mentioned I don’t like that I’ve cluttered it up with pagination, (maybe I should consider ModelBinders or MediaFormatters…..)

image

 

Client

Now for the Kendo javascript side:

image

The first important part I had was I had to map the parameters, the reason is that I’m updating the datasource via ajax and I call it like this:

ds.read(s0); I.e. I’m passing some parameters to the query ( i know there is mention of a query object in the kendo api but I failed to get this working),  in the javascript above I’m just setting these parameters again when the paging happens. Note this was where I could set e.g. $top = options.take; if odata was supported…. Sad smile

The next important part is that, I’m getting the result from the .Data field and I’m getting the total form the result.Total field (i also do a bit of mapping for some missing values but that’s application specific).

 

kr, Brian.

ASP MVC4 WebApi Delete 404

 

runAllManagedModulesForAllRequests

To support DELETE verbs in MVC4 the webconfig should have runAllManagedModulesForAllRequests defined

image

If you have an older project (like my project that I started in VS2012 RC) you may need to add this setting or else you’ll get 404 errors.

Here is where I found this info:
http://stackoverflow.com/questions/9692687/webapi-controller-is-not-being-reached-on-delete-command

Note: Make sure to read:
http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

KendoUi Web Grid and ASP MVC Web Api

 

I’ve just been through the mill trying to get kendo grid working with a ASP MVC Web Api Http Post Action.
I think it may help someone if I post my findings.

 

OData

If you use KendoUi you know that the datasource has v.good support of OData, but you’ll most likely also be aware that the WebApi currently is not fully OData compliant (did you notice i said currently!!! I’ve seen some heated discussions regarding OData support with WebApi, and it looks like some headway has been made http://blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net-web-api.aspx?CommentPosted=true). Now while I’m all on for living on the bleeding edge I’ve decided to give the alpha  a miss for now as I need to get this solution into production.

But we are, where we are.

So in the interim I needed to perform the simple task of getting the Kendo grid to

  • Use Http Post verb
  • Refresh when the async operation of loading data has finished.
    • How hard could that be?

    Well looking back, not all that difficult, but it’s easy when you know how.

Getting kendo dataset to use Http Post verb.


Lets first have a look at my MVC Action

image

 

Don’t get hooked up on the implementation or where I’ve put it for now, the important part is to notice the HttPostAttribute aspect. The endpoint url would be something like localhost/MyApp/api/Data/MyId where MyId would be the first parameter, the second parameter SearchOptionsFilters on the other hand are posted; here’s how:

image

Here we see we’re passing the sf object (that the model binder parses into it’s .net counterpart) to the read function of the dataset, AND we are explicitly setting the transport.options.read.type to “POST”.

Now I found a good few posts demonstrating how to do this but they mostly showed javascript object literals with the “POST” set on the transport which wouldn’t work for me, i.e.

image

Getting the grid to refresh once the data becomes available

Look in the screenshot above, I’ve already given this game away! The change callback refreshes the grid once the datasource changes underneath, this it appears is required when going down the ajax route.

Kr,
Brian.

Knockout.js accept terms and conditions checkbox and submit button

 

Here’s a nice way of enabling a button on a form IFF the Accept T&C checkbox has been clicked

Knockout script

image

So we have a simple acceptTerms variable that is observable

Markup

image

In the markup above you can see that the input of id “agree” has bound it’s checked state to the observable, we also see that the submit button has bound it’s enable state.

Pretty simple solution client side solution if you’re already using knockout in your application.

XCode disabling ARC for a single file in a project

 

So I’ll put it out there, I’m a novice Objective-C man, in fact I’m still sitting on the fence on whether I should write my iOS apps in C# (MonoTouch) or Objective-c (xcode), I’m leaning a little more towards the Monotouch approach and to be honest I’m just persevering with objective-c for a few reasons

  • It’s a different language, like a new toy I wanna play with it
  • I need to use XCode for interface designer anyway
  • It helps when reading sample code even if just to translate to c#.

So this morning I was trying to create an iPad app for a RestAPI I’m writing in MVC4 Web Api and I went with Objective-C.
I used AFNetworking to make my Rest calls but unfortunately this library was written before ARC (Automatic reference counting).
Now for some background: I came to iOS development after the fact and so far I have not had to write non-ARC code (that said I love c++ and deterministic destruction so it wouldn’t bother me that much).

So I was a little stumped when I encountered the following problem:

image

image

Basically this is telling me that the ARC doesn’t allow this pre-ARC code!

So how to solve?

Well the solution is somewhat simple, you just need to bring up the project properties Targets -> Build Phases -> Compile Sources and add the -fno-objc-arc compiler flag for those particular files.

image

A magical concoction Asp,WebApi,jQuery,KenodoUi,Knockout.js,WCF,Async,Moq

 

So the heading for this post is a little bit of a mouthful, but I want to tell you a story of how some of these technologies play together, so often in blog posts we are presented with a trivial example (I’m holding my hands up here too) and what we really want to see is that next step, i.e is the tech in question just a nice concept or can it be utilized practically?

Let me tell you what I’ve come up with, the application in question could be written with any web tech and just render some static html and we’re done. But we’re moving into web 3.0 (don’t google that I’ve just coined it!), where our ajax-ey applications are going to the new level.
We’ve all heard the stories of these 2.0 web applications that are many hundred thousand lines of code and hard to maintain, so can it be made easier? Of Course!

There are many new frameworks out these days, and to be hones it’s impossible to keep up with them all, the main thing to know is what they are for so you can investigate their effectiveness if needed; after your investigation you can decide if you want to continue the relationship a little further, in the post I will present some of the technologies I’ve encountered/like/love want to know better. I’ll explain where I used them and how,  hopefully you’ll see that they play quit well together.

WCF

I’m using WCF in the application to talk to some back end Java webservices, these webservices will supply the business objects that my web application is dealing with. I’m not sure I need to explain how I get a service reference but I’ll do so all the same, just right click on project References (or service references if that already exists) and choose the Add Service Reference Option

image

Type in the location the the webservice (a Soap webservice in my case) and press Go.

image

Give your service a meaningful namespace and click OK. That’s pretty much it, In my case I needed to perform addition Kerberos security configuration in the web.config but you’ll have to figure out what configuration you need for your own webservices yourself.

RavenDB or EF Code First (undecided)

Ok I really want to use RavenDB because I’ve used it in other project and I love the document database approach, it’s got some limitations for reporting etc, but it would be a good fit for our application. Also Entity Framework Code Fist is another good approach and we do already have SqlServer licenses so that’s pretty compelling… The great thing is i can pretty much decide later Smile for now I’m just writing my poco (Plain Old CLR ) objects.

WebApi

I love this tech, (btw: Microsoft if you’re listening please don’t break too much with the RTM version! please please). It allows me to offer a nice RESTFull service to my data (coming both from the WCF webservice and my application database), One of the beauties of this API is that it gives some clear direction on how to implement restfull services. MS developers previously we were faced with a decision between WCF and MVC Controllers, while it’s true now we are faced with a decision between Controllers and ApiControllers, for me it’s now clearer; I use my ApiControllers for data access, and I use my standard mvc controllers for rendering the view!

Confused? Look at this diagram

image

  • Here the browser makes a request, it gets routed to the MVC controller, this controller generates the html with with ever context is needed,
  • Once the browser loads the page we make a ajax request to the web api, the web api in turn makes an Async request to the java webservice thereby freeing up the ASP thread pool to service other requests and providing better scalability.
    How? : .net 4.5 async await

    image
  • When the response arrives back to the await the state machine restores the context and a (possibly) new thread picks up from where the first thread left off and returns the data to the browser.

To sum up, the advantages of the above approach are:

  1. A hugely more responsive experience for the end user, as compared with full page refreshes or even partial page refreshes (as in traditional Ajax).
  2. The server-side UI code is extremely simple, as it needs only to transmit an initial block of markup referencing the necessary JavaScript libraries. It doesn’t need to render data.
  3. Using WebAPI services as the basic data endpoint creates the opportunity to use multiple client technologies. For example, you could create a native smartphone application that connects to the same data endpoints without needing any additional server-side code.

 

jQuery

The data returned in in JSON format as we queries data via jQuery $.getJson() that sets the appropriate header (content negotiation is handled via Asp MVC4 for us).

image

Knockout.js

So this is one of the frameworks I knew about but had not used before. Those of you from a Silverlight/Wpf background will be familiar with the MVVM pattern and love the raw powerfull databinding capabilities. Knockout.js is one such javascript framework.

Markup

image

Javascript

image

Above you can see that I’ve got a DataFeedsViewModel, this is the top level view model ($root) that my html is databound to, looking at it with the markup you can see that I’m rendering an unordered list of suppliers IFF there are items in my array. The observable array is used so that the UX/GUI can update should the underlying list of array items change. Each list item has a click handler that is bound to the contentClick function in the $root view model, the beauty of this is the variable ‘e’ is just the single SupplierDetail object that was clicked!! nothing to do with any DOM elements…. nice..

 

KendoUI – by telerik

I’ve used telerik many times, silverlight/wpf/asp ajax etc, I also listen to lots of technical podcasts and had heard some interviews with the authors/designers of KendoUI so I decided to check it out for myself. The first control I used was the grid. Lets have a look at my markup and the associated javascript

Markup

image

Javascript

image

I’m using the revealing module pattern above to initialize my grid, you can see it’s using a kendoDataSource object to talk to the WebApi, the url parameter would be the url of my api,
/DataFeedApi for all records
/DataFeedApi?contentId=XXX for getting a subset of records from the WebApi

 

Moq

As I mentioned above I’m using WCF, WCF is composed of three concerns, the ABCs of WCF, (Address, Binding, Contract) is simple terms the Contract is the wsdl and when we add a service reference that a .net Interface gets generated for same.

The beauty of this is that in my Unit tests I can mock this interface so I don’t need a real connection to the webservice to test my concerns. For those of you that don’t use mocking frameworks, you should, it saves you creating endless dummy classes that implement interfaces just for testing.

 

image

Above you can see I’m mocking the interface DataContentActionsServiceType so that when I call the (It’s java hence the non standard .net naming convention IXxx)

  • getAllDataSupplierInfos method that I return ECB and APX.
  • getDataSupplierForCode(“APX”) returns the Netherland Stuff record.

That about sums up what I wanted to show, hope it encourages someone to start playing with any of the above technologies and see if you can leverage them in your own applications.

Brian.

Recent Tweets

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation

Calendar

<<  May 2017  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Month List