2013-05-10

Building Web Sites with ASP.net MVC4

This is another brain dump from another session at PrairieDev Con. This session is by the really excellent and hilarious James Chambers.

  • ASP.net MVC is built using the idea of convention over configuration.
  • MVC is model view controller
  • MVC and the tooling for it is now released out of band with Visual Studio
  • MVC is built on top of ASP.net so the role providers from a WebFormsapplicationcan be plugged right in
  • MVC is built on a bunch of nuget packages. If you have them already on your machine then there is no need to retrieve packages over the net
  • There are a bunch of templates to choose from when you start a new asp.net mvc site - empty project is totally empty and almost always a bad idea
  • basic at least adds some of the app_start stuff and is a good starting point
  • Internet and intranet add authentication
  • Authentication is now set up via the AuthConfig which is in App_Start. There is now out of the box support for OAuth
  • Bundling reduces the number of requests to the server by smushing CSS and javascript together
  • Routing allow for you to map urls to pages
  • When creating a new controller it is possible to use scaffolding to create controllers which have some functionality built in
  • The default built in data access stuff with the controller templates are built using EF
  • You should refactor almost right away as the generated code has hard dependencies.
  • The model binder, which can be overwritten, pulls information out of the request and binds it to a given model. It works on best effort so it is possible it won’t be able to bind some fields. In that case it just skips the field.
2013-05-09

Entity Framework Code First

This is another dump of my notes from a talk at Prairie Dev Con. This is David Paquette’s Entity Framework Code First talk which is, oddly, subtitled Magic Unicorn. Very odd.

David is also a beautiful unicorn David is also a beautiful unicorn

- EF shipped with VS 2008 and was junk

  • ORM is tough, please don’t write your own
  • There are 3 flavours of EF model first, database first and code first.
  • Model first using a visual designer to build up a model of the data. Kind of like LINQ
  • Database first will generate you a model from an existing database
  • Code first you create POCOs first and use conventions to figure out things like the key and foreign key references
  • Conventions - virtual IList or IColleciton creates a foreign key to the collection of Somethings.
  • virtual Something creates a one to one mapping from the current object to a Something
  • any property called Id becomes a primary key
  • EF will create a database using the name of the DbContext if there is no configured database
  • Good idea to initialize collections in the constructor. Using a HashSet is more efficient than using a List because hash set optimizes for having no duplicates.
  • A DbContext provides a mapping from the objects to the database. Each entity is just set up as an IDbSet in the DbContext.
  • The LINQ queries return IQueryables which are a built up collection of lambads which are applied in a delayed or lazy fashion
  • It is important to convert the IQuerable to an array or list before passing the data to the view as the DbContext may be out of scope before the view is rendered
  • You should dispose your DbContext as that returns the connection to the pool. This is best done using a handy, dandy injection framework. In this case Ninject.
  • To return a single object you might call _dbContext.Somethings.Find(id) you can also use Single or First which have slightly different failure criteria.
  • To add an entity use an Add on the context and then call SaveChanges to synchronize the DbContext with the database
  • Tidbit: There are no performance implications to using varchar(max) except that varchar(max) cannot be indexed so it can’t be easily searched.
  • When editing an entity you need to mark the state as modified _dbContext.Somethings(entity).State = EntityState.Modified.
  • You can specify a database initializer where you can have it delete and recreate a database or add default data
  • You can profile your applications using MiniProfiler.MVC which is a lightweight profiler from Stackoverflow. To hook in EF include MiniProfiler.EF
  • You can to eager loading by specifying .Include(“Something.Comments”) this would load the comments collection for Something
  • Projections can be used to trim down what is returned form the database
  • Paging is implemented using Skip and Take

Thoughts:

EF is a lot of magic but it seems like pretty well thought out and easily overridable magic.

2013-05-08

YUI

I’m told that YUI is pronounced Y U I and not yoooii, which I feel is a realdisappointment. This post contains information gathered fromJeff Pihach’s YUI talk at Prairie Dev Con. It is basically going to be a stream ofconsciousness with little ordering. Sorry.

  • YUI has quite a bit of support from various companies. Yahoo is, obviously, a big user. That yahoo uses a technology is not really a selling feature for me. They don’t even let people work from home.
  • YUI loader does server sideconcatenationof modules to allow you to load dependencies into your YUI application. It is dependency aware so it will properly order your includes. There is support for minification and even for doing debug statement removal.
  • Has support for a CSS selector based DOM selection and manipulation engine.

Y.one(‘.foo .bar’); //selects just one element which is returned as a Y.Node Y.all(‘.bazzs’);//returns a node list which is an array with some extra prototypes on it

  • Y.Node supports such methods as

setStyle() addClass() hide() show() …

  • There is binding for events which support binding before (using on), after (after) and instead of (delegate) events. Kind of handy.
  • You can specify the context under which an event handler will run. Probably a bad idea.
  • YUI is heavily modular so if you don’t need gesture support or simulate DOM events just don’t load those modules. Modules can be rolled up into “rollups”
  • YUI has some ability to create modules and classes for you. They have an augment function which is about the same as the jQuery .extend method. The classes look to have the ability to bind to change events on properties. So basically every object is an observable.
  • There is a plugin model which implements the mixin pattern. Is mixin a pattern? Maybe it is a language feature.
  • YUI base provides a simple basic object and pretty much everything extends that
  • Y.Widget createsreusableGUI objects
  • Y.Array.each is a handy foreach thing for arrays.
  • There appears to be an extension method which allows for overriding 3rd party controls through monkey patching
  • Y.App is a rollup which provides for an MVC style framework. Has built in support for routing.
  • ModelSyncRest is a framework which allows for making changes to a bunch of data using REST. It is very quick to set up CRUD sort of pages using a REST backend

Thoughts:

I’m not in love with having different selectors for a list of elements and a single node. That is one of the great selling features of JQuery. Having twothree different object extensibility methods is a bit complicated. I’ve never been convinced by mixins so I’m a bit one sided on that.

Why is enumerating an array so complicated, huh JavaScript? Old JavaScript engines are the bane of the Internet.

I think that YUI has some potential but that the bar to entry is pretty high. I’m not fully convinced that the advantages are so big that they cover the cost of dealing with the cost. I find myself still asking Y.Why? (I spent half the talk thinking up that joke)

2013-05-07

HTML 5 Data Visualizations PrDC Notes

I did a talk today on HTML5 Data Visualizations. The code is already available athttps://github.com/stimms/HTML5Visualizations. For specific information you can refer to my collection of HTML 5 data visualization blog posts

2013-05-06

Next Generation JavaScript

I’m talking today on next generation JavaScript which is really a misnomer. This is more like different approaches to JavaScript. The talk covers TypeScript, CoffeeScript and Dart. I have some demo code which is available and is up on github. The slides are pretty minimalist but if you really want them then drop me a line and you can have them.The topic of the presentation as I sent it to the conference organizer is

It has been said that JavaScript is the assembly language of the web. If that’s true then what tools are available to us for writing next generation JavaScript? In this talk we’ll take a look at three technologies which may make writing JavaScript more of a pleasure: TypeScript, CoffeeScript and Dart.

2013-05-05

Bookmarklet for Prairie Dev Con

Well here I am again at Prairie Dev Con and everybody has gone to bed early. Responsible speakers, or something. I went to figure out what sessions to attend but it is kind of tough to remember. So I built a bookmarklet to let me highlight sessions. Just copy and paste this

into a new bookmark in your bookmark bar.Click on it when you’re on the session page to let you highlight sessions with a click onhttp://prairiedevcon.com/Schedule.

2013-05-03

Strictly JavaScript

ECMAScript or JavaScript as it is more commonly known has gone through a number of large iterations over the years. The version currently under development is known as ECMAScript 6 or Harmony, which is an awesome code name. However most JavaScript we see around is actually ECMAScript 3. ECMAScript 4 was a failedendeavour but ECMAScript 5 brings a great new feature which we, as developers, should be exploiting: Strict Mode.

Back in the day Visual Basic had a feature called Option Explicit which was recommended. It required that you actually declare all your variables. Adding a simple command to your JavaScript enables strict mode for the whole file

“use strict”;

What does this strict mode do? A bunch of great things. The first is that it does the same thing as Option Explicit in VB: it requires that all your variables be explicitly defined using var. Without strict code such as

monkey = “salmon”

will attach a monkey property to the global object, in most cases window. This is a dangerous behaviour as it allows information to leak from one function to another. Strict will catch that and throw an error. Instead you need to do

var monkey = “salmon”

This alone should be enough reason to use strict mode. But there is more! Way more.

Duplicate property assignment is detected and prevented so you will know right away if you do

var shoe = { size: 7, size: 9}

you’re also prevented from putting in duplicate parameters into a function declaration

function climbTree(treeName, height, treeName) { }

Finally strict mode restricts the use of the eval key-word. You can no longer use it as a parameter or as the name of a function or even as a variable. It also prevents variable assignment from inside an eval context so you can no longer do

eval(“importantOuterVariable = ‘delete everything’;”);

Although I found that variable assignment from eval was still permitted in chrome.

Adding strict to any JavaScript is likely to catch errors before they become bugs in the real world. I think it is highly advisable and so easy to do. So why don’t you get a little stricter with your JavaScript?

2013-05-02

What I learned from Azure Bootcamp

Over the weekend I helped run a day long Azure camp. We had about 40 people come out and learn a bunch of stuff about Azure. The day was set up as a code camp with us having presentations every hour or so and then working time during which we circulated and attempted to help people out. Based on the feedback and my own observations I wanted to jot down some suggestions for the next time we put on such an event.

  1. Name tags. It would be great to give people name tags so that when I’m walking around I don’t keep having to ask what their names are and they don’t have to keep asking about mine.

  2. Electronic method of asking questions during the presentation. We were in a big room and it would have been good for people to be able to tweet questions instead of raising hands and the such. Frequently people are worried aboutinterruptingthe flow of thepresentationso this side channel would be great.

  3. Less complete demo. We built a fully functional azure driven website and let people download it to play with it. Next time we should branch the website just before we give people the download link and remove key parts of the functionality. They would still be available in a branch should people get stuck but they wouldn’t be obvious. As it stood people went to implement things and found them already to be in place and nothing for them to do.

  4. Challenge problems. One of the most popular comments was that things were going too slow. At the same time there were some people who were struggling to keep up. I can totally understand that. The camp catered for people at all sorts of skill levels so there were bound to be differences in how long it took people to get a task done. We should have put instretch goals or challenge problems for the faster moving. It would also give people something to work on when they get home, should they wish.

  5. Status board. With 30+ people plugging away at stuff it is hard to say who is ready to move on and who is still working. We could have set up a site on which users could check off their progress so we could see if we were ready to move on. This would allow us to be more dynamic with when sessions start and finish.

  6. Microphones and better projectors. Our room was huge, too big as it turns out. People at the back had trouble hearing and seeing the projector. The obvious solution is to move forward but we should have been proactive at the same time and moved people or invested in some microphones.

  7. Something for people who don’t have the tools. As always people end up at the camp without the right tools installed. From time to time they can’t install the tools because they’re using their company’s laptop. All the tools for this camp were free so we could easily have set up some VMs on the cloud to let people do development with remote desktop. There would have been a cost but for 10 users for 8 hours on a large instance at Azure the cost would have been $26. I think we could have stretched to that, the only question is “would our bandwidth have stretched?”

I think the whole camp went really well and I’m excited about doing another one at some point in the future.

2013-05-01

Dart Part 4 - DOM Changes

It is tough when looking at Dart to remember that compiling Dart to JavaScript isn’t the end game of Dart. This is a much bigger project than CoffeeScript or TypeScript which just aim to make writing JavaScript less painful. Dart is on a quest tocompletelychange how web browser scripting is done. So when I compare dart:html to Sizzle it is a false analogy. Sizzle is written in JavaScript and talk to the browser through a set of APIs which have grown up over the last decade or so.

dart

The assertion of the Dart folks over at Google is that the API which has grown organically is inconsistent and unmaintainable. Based on some of their examples I can’t really disagree. Let’s take a look at a couple of them.

Say you want to query for some information out of the DOM. There is a rich JavaScript API for that. Why you just need to pick one of these methods

getElementsById() getElementsByTagName() getElementsByName() getElementsByClassName() querySelector() querySelectorAll() document.links document.images document.forms document.scripts formElement.elements selectElement.options

That’s pretty clear. In Dart your choices are

query() queryAll()

That’s it. All the power of selecting items is still there but it now hidden in the parameters passed to these two functions. The parameters are written in the same DSL as CSS so it is something that web developers already know. Vendor prefixes are another big issue in modern development. When browser vendors create newfunctionalitythey hide it behind a vendor prefix until it is ready for general consumption. It’s not a big deal if you’re on a rapidly updating browser like FireFox or Chrome but if you’re on IE with yearly release cycles the it is tedious to deal with.

If you want to get access to the camera from a browser in JavaScript you’re going to do

navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

Dart abstracts away all those silly vendor prefixes and give you

window.navigator.getUserMedia(audio:true, video: true)

Way nicer! You can still have all the nice syntactic sugar of jQuery but now jQuery itself can be much smaller and easier to maintain because it doesn’t have to smooth out the weirdbehaviorsbetween browsers.

We need this. I don’t know if Dart is the solution but we need a clean break from maintaining the garbage which is the interface between JavaScript and the browser DOM. I’m glad that somebody is at least making an effort.

2013-04-30

Dart Part 3 - Libraries

Unlike CoffeeScript and TypeScript Dart is not really meant to be compiled to JavaScript. You certainly can compile it to JavaScript but the long term goal of the language is to replace JavaScript. That’s a goal which is at least a decade out. Truth be told I don’t see Dart ever replacing JavaScript wholesale. Selling Dart to Microsoft and to Mozilla is going to be quite a thing when there is already such acceptance of JavaScript. JavaScript hangs around rank 9-11 in the language ranking while Dart is not even in the top 50. That’s not to say that Dart isn’t a fantastic language it is just new and facing a pretty entrenched competitor.

So being a full replacement for JavaScript Dart must also fulfill the role of many of the fantastic libraries which have become commonplace in the land of JavaScript. Dart includes a number of libraries for manipulating html, performing asynchronous actions, running mathematical operations and even fir file I/O. These library create a sort of base class library the same as what you get with Java and .net. Obviously they are too large to cover in a single post. I thought I might talk a bit about dart:html which is the library designed for manipulating and queryingHTML.

The first thing in the html library is a sizzle like selector engine which works on CSS3 selectors. It is easily usable via the query and queryAll functions. Query returns an Element and queryAll returns a list of elements. These elements can be manipulated just as you would in JavaScript. For instance this code will add a colour a couple of divs

On the trivial html test page I put together the result was

Coloured boxes thanks to dartColoured boxes thanks to dart

Exciting!

If you look back at part 1 of this series I mentioned that there was some concert over the amount of crud which was created by Dart during a normal compile. To make these boxes dart2js generated 1891 lines of code. Humm”¦ that seems excessive. But it isn’t really a fair comparison is it? I included dart:html which is likely huge as it contains a bunch of the functionality of jQuery. If you read the Dart documentation it suggests that Dart will actually trim out functions which are not used. There is also a ““minify flag which can be passed to the dart2js compiler. Using the minify option the library is shrunk way down and the results are in line with other selector libraries.

LibrarySize when Minified
Sizzle17KB
jQuery32KB
dart:html25KB
It is difficult to say if comparing dart:html to Sizzle or jQuery is more accurate. There is more that just a selector engine in there but there is also less that full blown jQuery. There is some interesting stuff built into dart:html and its companion libraries. With dart:uri and dart:async we pick up support for web sockets as well as Ajax. I don’t feel like the syntax is all there yet but it does have the advantage of being built into the language. Well built into the base libraries. Most times developers are more likely to use the built in libraries instead of finding third-party libraries so there is probably more consistency moving from one Dart project to another than moving from one JavaScript project to another. The libraries aren’t terrible but they aren’t fantastic either.

“Not terrible but not fantastic” pretty much sums up my feelings about Dart in general.