Compsoft Blog

  • Øredev 2010 - Day 3 - Tim Jeanes

    Wednesday, November 10, 2010

    Elk burger

    Elk burger: this is made of win. And elk.

    Session 1 - Keynote - Mission Critical Agility - Jeff Norris

    The definition of mission criticality is when everything is on the line. For Jeff at NASA this may be the fate of a spacecraft; for more run-of-the-mill programmers it may be keeping a customer, preserving the life of the company, or keeping your own job. this makes it no less mission-critical.

    Taking examples from sources as disparate as Alexander Graham Bell to the 1969 moon landings, Jeff outlined key elements of success in agility.

    A key factor of agility is vision: the ability to see what's possible even when it isn't on the well-trodden path. Vision normally involves a lot of risk.

    Though commitment seems a virtue, it can be best to remain as uncommitted as possible for as long as possible. Agile methodologies can allow you to remain flexible until remarkably late in the project lifecycle: by developing only as little as is necessary for each iteration of development, hard commitments to certain technologies or avenues can be postponed until absolutely necessary. Early commitment to a single decision is the antithesis of agility.

    Session 2 - Deep Dive Into HTML5 - Giorgio Sardo

    HTML5 is undoubtedly going to change the way we develop for the web, so although we won't be able to count on all our users having a browser that supports it for quite some time yet, it's critical for us to ensure we're right on top of it from the outset.

    Giorgio's a Microsoft evangelist, and it's encouraging to see Microsoft on board with web standards.

    Even though the HTML5 spec isn't totally complete yet, it's already becoming supported by some browsers - or at least the parts that are stably defined.

    HTML makes for much cleaner markup. The DOCTYPE tag can be stripped right down to just <!DOCTYPE html>. It's no longer necessary even to have separate <head> and <body> elements (though they can still be used if you find it helps with clarity).

    HTML5 adds a bunch of new tags that though they don't render any differently to <div>s, can help with the semantics of the page, which in turn helps with accessibility.

    The new <video> tag makes embedding video a whole lot easier. The only required attribute is src. Defining the video file to display is literally all you need to do to put a video on your page. There are plenty of other attributes though, such as the image to show before playback begins or if it plays automatically. You can alter the playback speed of the video. You can specify numerous <source> child tags to offer various source files in different formats, in case the client's browser doesn't support the codec of your original file. The browser will play the first <source> that it can support. For fallback, you can specify an <object> tag for Flash or Silverlight after the last <source> tag: a browser that doesn't recognise <video> or <source> will ignore those tags but still pick up on the <object> tag (or some static apology that the user can't see the video). Adding an onerror attribute to the last <source> tag ensures that HTML5-enabled browsers will also use the <object> if none of the video sources are supported. Disappointingly there's no fullscreen mode, for security reasons. All attributes are accessible and alterable via javascript, including the position of the video playback. It's also possible in javascript to detect whether or not the browser supports the <video> tag at all, or if it supports certain video codecs (though the HTML5 spec says these functions return such values as "maybe" or "probably").

    The <canvas> tag is another major addition to HTML. This allows you to draw vector graphics on the page. <canvas> support can easily be detected in javascript. The canvas.toDataUrl method can be used to export the content of the canvas to a single static image. It's important to ensure the canvas has loaded before you attempt to draw on it dynamically in javascript: draw instructions made before that will be ignored. For animations you have access to the refresh frame rate of the browser. These vary between browsers and how busy the machine is, so time-based animations are generally the better way to go (though also syncing with the browser refresh makes for smooth animations with less CPU overhead). You can also draw videos on the canvas, and add matrix transformations to how the video is displayed.

    HTML5 supports svg both as inline <svg> tags in the browser, and also as a source file for an image. This means you can use svg graphics for background images, etc., resulting in much lower bandwidth than you would have using a large jpeg image. SVG images can also be created dynamically in javascript and then serialized and used as source to image tags.

    We touched briefly on some new features of CSS3. An interesting one was the ability to define different styles based on the size of a screen - enabling you to swap image when the browser is small, or changing the layout altogether for mobile browsers.

    Session 3 - HTML5 APIs - Robert Nyman

    We recapped some features of video from the previous session. Another nice feature that the BBC are experimenting with is the implementation of subtitles. These can be held in <div>s on the page (and are thus indexable by search engines; then they are shown accordingly in javascript by polling the playback position of the video.

    The Raphael Javascript library is a handy tool that makes building SVG graphics dynamically a whole lot easier.

    There's a tension between using SVG or canvas as on the surface they offer similar functionality. The key difference is that SVG is always vector graphics whilst canvas is always bitmap-based. SVG is often more appropriate for generating dynamic images, whilst canvas is faster and more responsive for animations and games.

    Web storage goes way beyond the capabilities of cookies. Cookies are extremely limited on size (around 4KB), whilst web storage give you 5-10MB, depending on the browser. The two types are sessionstorage that disappears when the browser is closed, and localstorage.that persists between sessions. These work as key-value pairs of strings, but JSON is a handy way of serialising objects.

    There's currently a fight between WebSQL and IndexedDB. WebSQL is backed by Apple, so will probably be in Safari only. IndexedDB will probably be available in all other browsers (and hopefully in Safari too).

    The Worker javascript object allows multithreading. It's initialised with a javascript file and can be communicated with from the main UI thread.

    New javascript property navigation.online is available to check if the browser is currently online, allowing you to alter the behaviour of your web application accordingly.

    There's a drag and drop module in the HTML5 specification, but it looks like it's not going too well. If they can get it sorted out, it could be pretty useful - elements can be marked as draggable or as drop targets by use of attributes. It'll be interesting to see if and how this will be implemented on touch screen devices where  a drag action needs to be distinguished from a scroll - parts of flickr are already unusable on my phone.

    The drag and drop API can be combined with the file API that allows you to drag files from the client file system to the browser, and provide you with metadata about the file as well as access to the byte contents of the file. This can be inspected in javascript, and then the file contents posted to the server asynchronously. Streamed upload, multipart upload and upload progress are all available in HTML5.

    The window.history object allows you to push URLs into the browser history.

    Data push from the server to the browser can now be achieved with the WebSocket object. Connections can be specifically opened and closed in javascript, and events are raised when data is received from the server. web-socket-js and SocketIO allow similar functionality in non-HTML5 browsers, if you need backwards compatibility.

    More at http://robertnyman.com/html5

    Session 4 - Clarity Means Completion: The Psychology of Kanban - Jim Benson

    Existential overhead - the things that stress your team out: all the things that take up brain space and prevent you from working. We find we get this when there's a lot of work backed up that needs doing, or that is work is progress. Being able to push things to a place called "done" frees up space in your brain to focus on the things you should be working on now. Typically developers love to start new things and often don't finish them and flush them from their minds. Kanban keeps the loop tight, ensuring you're only thinking about the things that matter right now.

    Flow- being able to see the whole flow of work in the project. Though you know what you have to be caring about right now, all other tasks are visible, making it easy to push back on panic rush jobs: though you can still take them on, the fact that another task (that up till now was the most important task on the board) will be pushed down to lower priority.

    Depersonalisation - The goal of everyone in kanban is to get a task off the right hand side of the board; not just to move it out of your column. It encourages co-operation between developers and testers, as developers can see when the test work queue is backing up. The fault probably isn't with the tester: with dev help they can most likely catch up with their workload. The whole team is focused on removing blockages.

    Pattern recognition - Human brains (especially those in the IT industry) just love pattern matching. Kanban makes spotting problems and issues with your workflow a case of pattern matching: the visibility of the workflow leaves problems with nowhere to hide.

    Learning styles - People with different learning styles tend to work in different ways: in the extreme, some will flit from the exciting part of one task to the exciting part of another; others will focus intently on one task until it's beyond perfect. Kanban keeps the balance: the goal is always to move tasks to "done" and never see them again.

    Subjective well-being - It can be useful to flag tasks as being tasks you like and tasks you hate. In retrospectives, discussing what it is that makes tasks suck can lead you to realise what's causing pain in your overall processes and thus what it is you can do about it.

    Session 5 - The Counterintuitive Web - Ian Robinson

    This session wasn't quite what I expected: it turned out to be part of a series on RESTful practices that I wasn't all that interested in. Ah well, a few things were slightly interesting.

    In a traditional web application or service oriented architecture, the server would keep track of the state of the interaction with the client - for example the position in the state machine that a customer has reached (requested order, ordered goods, paid, cancelled, etc).

    In a RESTful application, we break the process into resources (quote, order, item) with verbs (GET, PUT, POST, DELETE), then specify operations (CreateQuote, SearchOrders, ReserveItem, etc) that are executed on the server in response to these verbs. Each resource then maintains its own mini state machine.

    For an application to be able to evolve, we need at least one degree of freedom in our architecture: either we can continually add new verbs (as we would in an SOA), or new resources (as we would in a RESTful application.

    Session 6 - Introduction to Core Animation - Marcus Zarra

    Core Animation is one of the core technologies for iPhone and iPad development. It allows for animating 2D planes (or layers) in 3D space. It almost (but not quite) achieves the same as OpenGL. For most animation requirements, however, it performs slightly better than you could manage using raw OpenGL yourself.

    It supports basic animation (to change a value from A to B, and keyframe animation to allow for many points which are animated between

    The following can be animated: opacity, colour (including alpha), size and position. You can also animate matrix transforms. The API allows easier access to matrix transforms by exposing methods to animate rotation, translation and scaling on any axis.

    Animation is best used to indicate user interaction, to give feedback to the user (for example to let them know something can be interacted with). It's also handy for simpler games. It's also very useful for highlighting alerts.

    Several animations are provided for free, such as flipping the screen around on the y-axis, sliding on screen on top of another, etc. Custom animations can be created as well.

    Unless you specify otherwise, the built-in animations take 250ms - long enough for the user to notice, but without them feeling like they're being held up at all.

    Animations can be expensive, particularly if you're animating complex structures, or if you have layers with alpha transparency. The key is to measure performance with instrumentation rather than judging it by eye. Sometimes when you have bad performance you just have to experiment by removing features one by one to see what's actually causing the performance hit. Rounded corners, for example, are surprisingly heavy-duty.

    Core Animation does most of its hard work (preparing the animation and working through the maths) on a background thread - only the actual drawing takes place on the UI thread. In later versions of iOS, even some of the drawing takes place on the background thread.

    Session 7 - CSS3: Now and the Future - Jonathan Snook

    The CSS3 spec is at the Candidate Recommendation stage, where it's unlikely to change much but isn't actually finalised yet. However, many browsers already support many of the features - often even features that aren't at the CR stage yet.

    Some of the hotter new features are the new selectors (such as :nth-child), multiple backgrounds, border-radius, gradients, shadows, rgba colour definitions (allowing alpha on different part of an element such as the border and background), 2D and 3D transforms, transitions, multi-column support, and animations.

    Safari, Firefox, Opera and IE9 support most of these features.

    Multiple backgrounds look awesome and we've needed them for a long time. You get to specify as many as you like and they get layered one on top of each other. The unfortunate drawback is that there's no way to override just a single layer (for example in the rollover class for a button).

    Many of the features now becoming available in CSS3 have been available for some time in various forms in older browsers. It makes the CSS pretty messy, having to include the correct CSS3 definition, along with the definitions for Mozilla, webkit and IE's proprietary legacy implementations.

    http://caniuse.com is a handy resource to check which features are currently supported in various browsers.

    http://www.modernizr.com detects browser support for various features and substitutes workarounds where they're not available.

  • Øredev 2010 - Day 2 - Tristan Smith

    Tuesday, November 09, 2010

    Koana, Katas, oh my!
    (Corey Foy)
    Corey started with a discussion of the differences between professional Software Development and other professional careers, pointing out that other critical jobs such as Doctors and Firemen don't do their learning on the job.
    His point, while acknowledging that not all software is life critical, but certainly the cost to a developer of major failure with a new technology implementation on a project for example could be the loss of their job, a pretty critical issue for them.
    The differences between Koans (a focussed learning exercise) and Katas (honing skills to problems with known solutions) were expounded with illustrations from martial arts. Shu Ha Ri learning was also talked about where Shu is learning by example, following steps thoughtlessly to learn a new thing. Ha learning is where analysis of the subject, why am I doing this, what if I do it an alternate way and Ri learning where the subject is instinctive. In martial arts, this would be where you know the katas and karate moves so innately that you could automatically defend yourself for example.
    Other than the knowledge drop, the majority of the time was spent working on some katas where we in pairs solved solutions such as Fizzbuzz and Conway's Game of Life using Test Driven Development. Deleting our code after each iteration and starting again from scratch each time.
    Interesting too was that the room had maybe 15 people in it from all language backgrounds and yet everyone managed to work together and storm through the problems.
    A practical introduction to Kanban
    Kanban is a Japanese methodology for process improvement and control.
    It originated in the Toyota Manufacturing Factories after research into the Supermarket model of demand controlling the rate of production.
    Kanban has some key principles:
    • Limit the work in progress.
    • Stop starting (new work), start finishing. (Using a queue where only one task is taken when the previous task is done.
    • Visualise the flow of work so that bottlenecks and other issues are easy to see.
    After a brief overview, came the guys initiated a dot game where 8 people were divided up by job role. A post it note on the table had a dot based design and different coloured dots were given to the different roles. Business Analyst, Designer, Developers, Tester, Project manager and Customer.
    http://www.netobjectives.com/the-dot-game
    In the first iteration the process was defined, each person would do a batch of 6 instances of their job (putting their coloured dot on the post it) before passing the batch to the next person.
    What quickly became clear was that there were bottle necks and dependencies that led to undue pressure felt by people, some people were kicking their heels while others were slaving away. When the first batch was complete, the customer rejected all the work.
    None of the team ever asked for feedback from the customer, everyone had their own interpretation of the spec and the feedback loop was too long as there was no feedback until the entire batch was complete.
    Two more iterations of the exercise allowed changes to be discussed which brought customer feedback into the process and more individual informed involvement.'
    It was a good way of highlighting some of the key strengths of Kanban, the problems experienced in the first instance where caused by too many items being processed, inefficiencies due to lack of visibility and slow response to those inefficiencies.
    Some of the other points made along the way:
    Context switching (limited by the 1 item at a time flow) tends to result in about a 20% loss in time per item, this has a major impact if you're repeatedly having to context switch. Some research they pointed at showed that context switching equates to a 10 point drop in IQ.
    Work in progress also includes items that are complete but have not been released yet, or not been taken up by the next department (Dev > Testing > Customer Acceptance).
    The higher visibility of problems means that bugs for example have a number of extra costs, there's the delay downstream for the time Testing takes, then the context switching tax of going back to a previous problem domain (and possibly project).
    Catching issues earlier leads to a lower cost to change in requirements, making it easier for customer change requests to be processed.
    Shorter lead times mean greater motivation, the higher perceived (and actual) productivity leading to a positive feedback loop.
    Moving on to the Kanban board, tasks are added and prioritised with colours showing the task type or scope (bug, feature, maintenance).
    Avatars appended to the bugs as the tasks move across the board through departments make it obvious who is working on each task. Tasks are pulled from the list, and pushed to the done / next stage by that person.
    As each task gets moved, date entered can be added to make it easier to see the lag times between work coming in and being done. Deadlines can be added as well as extra data such as TFS Item Ids.
    Each department has a specific Work in Progress max task number so that teams are limited to their capacity.
    http://www.kanban101.com
    Image from mountain goat software
    Some really useful information given, the slides of which we'll put up when we get them. We'll certainly be looking to implement a lot of the key features of Kanban in our current Scrum methodology, it fixes some of the issues we sometimes find where inflexibility of times / tasks can be an issue.
  • Øredev 2010 - Day 2 - Tim Jeanes

    Tuesday, November 09, 2010

    Ribersborg Kallbadhus

    Here's the post-sauna sea pool at Ribersborg Kallbadhus last night. This somehow seemed a good idea despite an air temperature of only 3°C. Exhilarating, but we all shrieked like girls. We also noticed that scarcely any locals were joining in...

    Session 1 - Koans and Katas, oh my! - Cory Foy

    This was a largely hands-on session where we spent most of the time writing actually code, so there's not too much to blog about beyond the basic principles of katas and koans.

    Both are exercises whereby you hone your coding skills outside of the normal flow of day-to-day work.

    Katas are essentially simpler exercises where you already know the solution: we worked on the FizzBuzz problem and Conway's Game of Life. The point of the exercise is either to experiment with different ways of reaching the solution (such as implementing TDD or BDD, or using a novel coding pattern), rather than focusing on working out the solution to the problem itself.

    Koans, on the other hand, are longer exercises that are more clearly defined by an instructor. These focus on guiding you through the principles of a language or a coding practise, leading you to pick up the concepts by writing simple pieces of code.

    Katas are something you'd expect to do many times over to hone your skills in various areas, whereas a koan is something you'd work through once in order to pick up particular knowledge.

    Session 2 - A Practical Introduction to Kanban - Joakim Sundén, Marcus Hammarberg

    I selected this session as I thought it could be particularly relevant to us at the moment. Kanban is a practice we've been considering taking up at Compsoft, if suitably modified to fit our particular needs.

    We started with a hands-on exercise where people simulated the various departments of software development. In this task we were just sticking different coloured dots onto post-it notes, and the point was to experiment with different ways of working to ensure there aren't bottlenecks, that people aren't idle, that the customer is happy with the final result, and that no one feels too pressured.

    The two main principles of kanban are to work to an agreed capacity, and only to pull work from the queue when it is required.

    Limiting work in progress minimises risk: the shorter your lead times between starting work and getting feedback, the less unconfirmed work there is in the system. The more unchecked work there is, the more potential there is for that work to be wrong - either buggy or just not what the customer requires any more. Work in progress should be limited to the capacity of the team. Working with smaller units of work can help to keep the process time streamlined. Where possible, having a cross-functional team can minimise bottlenecks.

    The amount of WIP in a software context is difficult to track as it's not visible: there are no stacks of half-built physical goods sitting around. Thus visualisation is critical. Post-it notes of the wall to track the volume of tasks and where they are in the system helps everyone to see where the work's building up, where the bottlenecks are and hence where the waste is.

    Though SCRUM incorporates many kanban principles, it allows for more flexibility than strict SCRUM. Often it can be impractical to set a fixed sprint time-box for a portion of work, especially where (as we often find) we're juggling many different customers simultaneously.

    A general principle (though not a hard rule) is to focus on finishing work rather than starting new work. Even though it all has to be done sooner or later, it's generally beneficial to help get items that are already started finished, rather than bringing more unstarted items into WIP. The customer appreciates this as it means the higher priority tasks get delivered sooner, rather than there being more lower priority tasks in the pipeline.

    Moving post-it notes representing tasks between columns identifies bottlenecks early and can prompt appropriate reaction. Different coloured notes can represent whatever you want - be it different priorities, different customers, bugs versus features versus change requests, etc.

    Joakim Sundén with example kanban board

    Each department's columns has a WIP limit. Those these can occasionally be broken, this should always at least prompt a conversation about what the underlying problem actually is. It's also worth including the customer's acceptance as a column, so they can be prompted to keep up with their involvement in the task.

  • Øredev 2010 - Day 1 - Tristan Smith

    Monday, November 08, 2010

    Silverlight Bootcamp
    Originally due to be given by Shawn Wildermuth (Silverlight MVP) and then by Tim Heuer (Silverlight Program Manager), it ended up being given by Einar Ingebrigtsen Norwegian Silverlight MVP and developer of the Baldur 3D Silverlight engine. He gave a decent comprehensive overview and exploration of Silverlight.
    The talk itself was interspersed with loud exclamations from the REST talk next door 'BOOM, BOOM, BOOM HEADSHOT!' and 'What the **** is this application' were heard by the clearly passionate Thoughtworks guys next door.
    Starting with a comprehensive overview of what Silverlight is, Einar talked us through the breakdown of the plugin, how the CLR, DLR and rendering engine fit into it.
    He covered topics such as Dependency Properties, RoutedEvents, Storyboards, ContentControls, Animations, DataBinding and a lot more. The aim of the talk was to get a 99% coverage of Silverlight so I'll just cover some details, I thought might be of interest, in this post.
    RoutedEvents follow a similar path to html DOM events except for some key differences
    - Bubbling only goes up the tree (focus, lostfocus)
    - EventArgs Handled property can be set to true to handle the event (this doesn't exist for all events)
    Storyboards
    - Anything can be animated (made to change over time, not just visual properties)

    ContentControl
    - Custom controls you can attribute up which property to use as the Content property
    He gave us a Xaml centric walk around Blend covering:
    Animations
    - Animate colors, values, over time, with easing etc.
    Triggers
    - EventTrigger is the only option, which has a single RoutedEvent (Loaded) with a single action, BeginStoryboard
    Sample data
    - Lets you create sample data that's easily bound in Blend, makes it easier to design when you can visualise the final result.
    - Basic types only
    - Creates sample data schema, xaml etc in the project and an associated resource file with the items in it
    Dependency Properties
    Used to add bindable properties.
    Resources
    All UIElements can have an associated resource, these resources apply to the whole hierarchy of that UIElement.
    Resources are stored as dictionaries so they have a key to get access to them and can store anything (a Class instance for example).
    MergedResourceDictionary allows you to pull in dictionaries from elsewhere
    Styles
    Styling doesn't mean just visual styles, you specify TargetType but can change any property at all.
    Styles are inheritable making base styles with overridable style parts possible.
    VisualStateManager
    Controls can have states and transition between them, Focused, MouseOver etc.
    Validation
    Binding has Validation hooks - ValidatesOnException, ValidatesOnNotifyDataErrors if the object being bound implements IDataErrorInfo + INotifyDataErrorInfo
    Control value default
    On controls you can set properties of TargetNullValue='None' and FallbackValue='Data Context not set' so that you can have default values for when nothing is specified and when data has not been bound.
    TypeConverters
    Exposed properties on your object model can declare the TypeConverter to use (To allow scenarios such as converting a selected product code into a product instance).
    You point to a TypeConverter by attaching an attribute
    Templates
    Blend makes it easy to edit templates based on existing controls, this is often a handy starting point. In order to get your bound property content to appear, you need to ensure you add a ContentPresenter control
    Timers
    You get access to two, DispatchTimer and the CompositionTarget Rendering event (which is fired as many times as you have MaxFramesPerSecond configured).
    The DispatchTimer runs on its own thread.
    To work against the UI, you need to go via the Dispatcher
    LocalConnection API
    - Used to communicate between SL instances on a page��
    Fonts
    Silverlight uses its own font engine, you get 9 fonts by default but you can embed your own fonts.
    WriteableBitmap
    Introduced in Silverlight 3, it's surprising fast, Einar's 3D engine project makes a lot of use of it.
    Localization
    Tooling is a bit rubbish at the moment, you have to manually change the access modifier in the Resource file but then because the tooling doesn't modify the constructor to be public, you have to derive the resource class to add a public constructor.
    Serialization
    - DataContractSerializer and JsonSerializer only
    - References are maintained (circular references sorted for you)
    - IgnoreDataMember to skip serialization of properties
    Printing
    Is still lame, no paging support, pixel not DPI based. If your image is bigger than the available print area, it won't intelligently continue, it'll lose the excess.
    - The cool feature, is that you can pass specific UIElements to be printed.
    WCF
    - Add service reference handy proxy generation
    - Validation for databinding is a pain because you lose IDataErrorInfo in transit.
    MVVM
    ViewModel contains State and Behaviour
    Built in Commands mechanism - requires a new class for each one.
    MVVM Light give you some time saving Behavioural additions.
    You create your commands as methods on your ViewModel and call delegates passing your method.
    Event aggregation - a contract (message type) that view models can subscribe to / publish. MVVM Light has this called Messager.
    Einar showed us a convention he uses where he creates a directory per feature, in this case it was a Customer folder with a View, ViewModel and CustomerDataSource.
    The ViewModel encapsulates the state and behaviour. It uses a generic DelegateCommand to wire up to a local method (Load for example) rather than implement the full ICommand.
    MVVM Light has an implementation of the delegate calling code.
    Jeff Wilcox pointed us at the SilverlightToolkit
    Is a library on CodePlex (silverlight.codeplex.com) that has a bunch of handy controls such as DockPanel, ViewBox and BusyIndicator.
    Also has a comprehensive samples app which lists the controls included but includes examples of styling, templating, selection, events, databinding etc for each control. Pretty handy!
    Jeff showed us a really nice styled, templated app called Bugaholic he wrote that looks a lot like the Zune client.
    http://www.jeff.wilcox.name/2010/05/my-childwindow-design/
    Einar covered some unit testing, Jeff wrote the Silverlight Unit Testing framework so we saw a bit of that to end with.
  • Øredev 2010 - Day 1 - Tim Jeanes

    Monday, November 08, 2010

    Øredev - not the plushest conference venue

    Øredev - the only conference I've known to be held in a converted slaughterhouse.

    A bootcamp in Silverlight - Jeff Wilcox, Tim Heuer Einar Ingebrigtsen

    I've tinkered a little with Silverlight at a basic level in the past, but not really used it in anger. This intensive session took us from the very basics through to cover around 99% of Silverlight within a single day, so I've only blogged the points that stood our for me.

    RoutedEvents - events that a parent can also receive (Focus, LostFocus, etc.) - these bubble all the way to the root of the VisualTree. Can set the Handled property of EventArgs to stop bubbling, though this isn't available on all such events.. OriginalSource holds information about the source of the event.

    ContentControl - the base class for classes that have content (e.g. Button, TextBlock).

    ItemsControl - the base class for controls that have items (just as lists, etc.)

    HierarchicalDataTemplate - the base class for hierarchical structures such as TreeView.

    Animation - all done through storyboards. Any property can be animated - not just visual things (e.g. you can animate the value of a string). In all animations you specify keyframes and Silverlight interpolates between them using the specified easing. nimation storyboards can be started in code, or via triggers in the xaml.

    Sample Data - This is a powerful feature of Blend. You can easily specify a data structure (Customer has FirstName, LastName, Photo, etc.) and mock data will be generated for you - lots of lorem ipsum-like text and arbitrary images in our case. This makes it really easy to get started with a data-driven app that you can even show to a customer right away.

    DependencyObject and DependencyProperty - When making your own controls, can define DependencyProperties. This enables properties to be animated; it also provides two-way dependency, so the view is updated with changes made in code as well as the code being notified of changes made to the value via changes made in the view.. This points to the actual property whose value is to be changed. You can also specify metadata such as the default value and a callback method that will be called whenever the value is changed by some action in the view.

    This makes for quite a bit of extra typing and non-refactorable code (the actual property name is specified as a string in the DependencyProperty definition, for example). It's worth using a generic wrapper that will register the DependencyProperty for you. Einar's set up some sample code of how to do this, available here: [.]

    Resources - As well and application-wide resources, all UIElements can have resources available for their scope. Though resources are usually used for styling, resources can be any objects. Only static resources are available in Silverlight - WPF's dynamic resources can't be used here.

    Styling - this goes way beyond the powers of CSS: any property can be styled - including ones that aren't visual. Styles can be inherited from one another using the BasedOn keyword.

    Visual States - Controls can have different states (e.g. MouseOver, Focused, etc.). Using the VisualStateManager you can set styles for different states and the animations between them.

    Markup extensions - These allow you to use pseudo-values for properties, such as {Binding}, {StaticResource}, etc.

    DataContext - All UIElements have a DataContext, which is inherited from its parent by default.

    Binding data - Different modes are available: OneWay (the default, which only takes data from the object to the view), TwoWay (which sends data back), OneTime (which reads the data once at start-up and never updates).

    IValueConverter can convert string values in the model to a different value that is used on the view. This can also work both ways.

    String formats, null and fallback values can also be defined.

    Attached Dependency Properties - these allow you add your own properties to the existing properties on a DependencyObject. You can see these in action in the Grid control: it adds the Grid.Row and Grid.Column properties to child elements that appear within the Grid.

    Element-to-element binding - One element can bind to the properties of another element. This can be useful, for example, in list/ detail binding.

    Silverlight promotes using an asynchronous model, so INotifyPropertyChanging and INotifyPropertyChanged interfaces are used to mark the beginning and end of the async operation.

    TypeConverter - Everything in xaml is a string, so these are used to convert between objects and strings between the view and the model. They are defined through attributes on types or on DependencyProperties.

    Offline support - Isolated storage is available for storing data locally. Silverlight can also be run out-of-browser. The API provides methods to detect network availability and events are raised when the network availability changes.

    ChildWindow - an easy way to create modal controls. Watch out though - it's easy to tab from this control back to the parent. It's a bit tricky to work around this bug.

    DispatchTimer - a timer for running code at a predefined point in time. This runs on its own thread so you need to use the Dispatcher to execute operations on the UI thread.

    Local file access - you can't access any old file on the hard drive; however OpenFileDialog and SaveFileDialog are available to ask the user to access files.

    Local Connection API - enables you to communicate between multiple Silverlight instances on a single HTML page.

    Fonts - Silverlight has its own font engine to break the dependency on the OS, thus ensuring it will render the same everywhere. Nine fonts are included in the runtime, but you can embed your own or access certain ones that you can (hopefully) assume exist in the OS. TrueType fonts are supported.

    WriteableBitmap - this enables you to create your own bitmaps dynamically at runtime. It's surprisingly performant.

    Printing - Any UIElement can be sent to the printer. However, it's pretty limited. It doesn't always look great as it's pixel-based. There's no paging support - anything you print will come out on a single page.

    WCF Services - Adding a Silverlight-enabled web service to your server application really adds a regular WCF service - but it also sets everything up for Silverlight consumption in the web.config.

    MVVM - the Model - View - View Model model works really well with Silverlight. The View Model is where you spend most of your development time in Silverlight. It should contain business logic relevant to the frontend, but not view-aware. It typically connects to the server through services. In terms of state, it contains as much model-like information that the view needs, with the application logic state.

    Though MVVM costs a bit in terms of the initial learning curve and early development time (though it's less uncomfortable if you're already used to ASP.NET MVC), it's worth it for the separation of concerns and code testability and maintainability. It also makes it a lot easier to make drastic changes to the UI without breaking the application.

    Silverlight toolkit - Available at silverlight.codeplex.com, this is an open source library of useful Silverlight components that may one day make their way into the core Silverlight library. It includes tools for WP7 development.

  • iPad, Glorious iPad

    Thursday, April 08, 2010

    Shipped from the USA, our iPad has been in the office for 27 hours or so... well, nearly. The MD took it to a meeting yesterday afternoon and then home and played in to the small hours with it. And now it has gone to another meeting. Interestingly, the meeting yesterday was about the development of an Android phone app, but that quickly got forgotten as the iPad stole the limelight.

    I had the pleasure of spending some time with it this morning, looking over it with colleagues and have received a variety of opinions:

    The Sales Team: they loved it. It is a tactile thing that wants to be used, to be touched, to be seen. They can see that putting it in front of customers with their iPhone / iPad app on will blow them away. I guess the telling sign is that all bar none have expressed their desire to get hold of an iPad.

    The Support Team: the only comment required is that as I left the Head of Support was on the phone to his wife, currently on business in the USA, asking her to get to an Apple Store! (Update: she is on a waiting list!) (Update #2: Wife was able to pick up 64GB iPad; Head of Support uncontrollably happy!).

    Design Team: in spite of expressed concerns our Senior Designer 'loves it'. The slickness of the interface has impressed him, and he too sees how clients will love seeing their imagery in a fresh crisp view. He was exploring how he could justify to his wife the purchase!

    Development Team: it shouldn't surprise that their view focused on its gaming potential - the additional control that the larger surface offers over the much smaller iPhone was evident as a Senior Developer demolished a tower in 'Angry Birds'. When questioned, the dev team confirmed that they would rather build for iPhone / iPad (iPad using a similar development framework to iPhone) than for other mobile platforms.

    The client: I took the liberty of introducing a long-standing client to the iPad; his reaction used colourful language to illustrate his surprise at its ease of use and its capabilities.

    The girls next door: It's a gadget, a boy thing... really? They were the first to want to touch the screen and flick through pages on the book reader. Mind you the guys from next door were impressed with the comic book reader.

    My considered opinion:

    This is a great gadget. For viewing websites, ebooks, documents, videos (the on board speaker is pretty good, not great but adequate) and photographs, it is revolutionary. It doesn't have a Flash player, which means media on the BBC website is not viewable (yet?), but the experience of viewing the news pages is great. Really great. In educational situations, I think this may well transform revision - one app that looks at the Periodic Table is phenominal. It is a delight to look at and to use!

    Do I see this becoming a business tool? Absolutely. We previously built an iPhone app that presents a host of videos; our dev team converted this for use on the iPad and, wow, it is very impressive. OK, so this app is an instructional tool for a golf tutor, however, the stunning presentation can be applied for use by sales teams, project management ... anyone! For example, in my marketing capacity I can see already how easy potential customers will be able to view a range of documents and supporting videos.

    We have an internal app that has an interface on the iPhone. We currently can edit info from the iPhone, however, the touch screen keyboard is not a practical size, comments added, therefore, consist of only a few words. With the iPad and its more capable screen size, it is much easier to type meaning that greater amounts of information will be included. Actually, the word processing app works well; it enables one to add text naturally unlike with the iPhone, and certainly unlike other smartphone devices.

    It is because of the combination of these that I think it will become a valuable business tool; it works as a presentation medium, as a document viewer and as a means to capture textual information. And it is fun.
    So, perhaps the caveat is that the iPad is going to work well for businesses, provided the right apps exist.

    My challenge is now to convince the wife that it is a good idea of hers for us to get one...

  • Using Team Foundation Server (TFS) with Xcode on a Mac

    Friday, March 05, 2010

    We live and breathe TFS here as I genuinely feel its the best source control product on the market. The Visual Studio integration is spot on. The web access add on give nice access for all none developers to create / edit bugs etc.

    We recently have been ramping up our iPhone development and as you may be aware its Mac only using Xcode. Currently there are no TFS plugins for Xcode as it as limited (no?) support for source control plugins.

    After some googling, I stumbled upon SvnBridge. This is a small module you pop on to your application tier and BOOM, you have SVN access to your existing TFS library. No mods, no hassle, just works.

    Getting used to Xcode and svn can be hard work. The intergration isn't the smoothest in the world. So watch out for issues adding / removing items or moving existing items around.

    Overall we are pleased with the support SvnBridge provides, day to day use works well, just a few Xcode / Svn / SvnBridge /TFS fringe issues.

  • MySQL and the warm blankets of Replace and On Duplicate

    Thursday, February 25, 2010

    Two very useful features MySQL has that MSSQL doesn't are the 'REPLACE' and the 'ON DUPLICATE'.

    I've found these are most helpful when updating existing records, although it is best to understand how they differ and how best to combine them with 'INSERT' statements.

    Just for reference a normal 'INSERT' might look like this:

      1: INSERT INTO TABLENAME (productName, productCost, productId)
      2:   VALUES ('new product name', 'new product cost', 'new product id')
    And an 'UPDATE' statement might look like this:
      1: UPDATE TABLENAME SET
      2:   productName = 'new product name',
      3:   productCost = 'new product cost'
      4:   WHERE productId = 'existing product id'
    'REPLACE' is great if you want to insert new records or update records that have matching unique keys. This is because if a record is not found that has a matching key, the record is just inserted. However, if an existing record is found, the record is first deleted, and then inserted.

    An equivalent 'REPLACE' statement looks like this:

      1: REPLACE INTO TABLENAME SET
      2:   productName = 'new product name',
      3:   productCost = 'new product cost',
      4:   productId = 'new or existing product id'

    This makes 'REPLACE' handy as you don't need to worry about finding or deleting records when there is data that just needs to be added or renewed, and you can do it all in one statement that takes care of it for you.

    Caution is needed with 'REPLACE' because it DELETES RECORDS if they exist, before inserting them. So if you have data that has information in that you don't want to loose then you need..

    'ON DUPLICATE'!

    Combining an 'INSERT' statement with 'ON DUPLICATE' functions similarly to 'REPLACE' except that it doesn't delete existing records, but gives you the power to decide what fields are replaced with what values.

    An 'INSERT' with 'ON DUPLICATE' statement looks like this:

      1: INSERT INTO TABLENAME SET
      2:   productName = 'new product name',
      3:   productCost = 'new product cost',
      4:   productId = 'existing or new product id'
      5:   ON DUPLICATE KEY UPDATE
      6:   productName = Values(productName),
      7:   productCost = Values(productCost)

    Notice how the new value for the updated field is chosen from the 'Values' collection passed into the 'INSERT' statement. The new field value can be updated to any value that SQL can accept for the field type being update, and you don't have to update them all.

    It can also be used with clauses that you would use with a plain 'INSERT' statement.

    To find out more, hop on over to http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

  • Using javascript to put the cursor at the end of a textbox

    Wednesday, January 27, 2010

    All too often with software development it's the feature that seems the simplest that takes the most time to implement.

    We had a <textarea> on a page that typically contained a lot of text. The customer wanted that textarea to have the focus when they arrived at the page, with the cursor at the end of the text ready for them to type some more. If there's enough text in the box for the vertical scrollbar to appear, we'd need that to be scrolled to the bottom too.

    "Sure, no problem!" I said, thinking this would take about five minutes to implement. It was more like two hours of research and wrestling with browser compatibility.

    Let me save you two hours. Skip to the end and use my code, or stick around and share my pain.

    The nicest way to position a cursor within a text input or textarea is to use the setSelectionRange function. This can also be used to select portions of text:

    document.getElementById('myTextBox')
        .setSelectionRange(startPos, endPos);

    Setting startPos and endPos to be the length of the text puts the cursor at the end. So far so good. Unfortunately, this is a non-standard javascript function, and some browsers doesn't support it - most notably IE.


    Another method to put the cursor at the end is to replace the contents of the textbox with itself. Easy peasy with jQuery:

    $(this).val($(this).val());

    Unfortunately this doesn't work so well in Google Chrome: though it scrolls the textarea to the bottom, it leaves the cursor at the beginning of the text.


    OK, so we use a combination of the two - use setSelectionRange if it's available, replace the text if not.


    Now, though, we find that Firefox and Google Chrome won't have scrolled the textbox. That's OK - we can set the scrollTop property to a large value (a little dirty, but hey - it works):

    this.scrollTop = 999999;

    Phew! Job done, right?


    Well no - there's still one little "unique browser feature" we have to account for, and not one you'd ever know about until you met it doing this sort of thing.


    This bit of code should just work in all browsers that support setSelectionRange:

    var len = $(this).val().length;
    this.setSelectionRange(len, len);

    If you're already saying "Ha! That'll never work in Opera!" then you're clearly too much of a cross-browser javascript-character-encoding genius to be reading this blog.


    This will work fine if the textarea contains no carriage returns.


    It turns out that when Opera measures strings (using .length), carriage returns count as one character. However, when it comes to setSelectionRange, they count as two.


    This means that in Opera, the cursor will be positioned near the end, just not quite at the end - it'll be back by as many letters as there are carriage returns in total.


    Ironically, Opera's perfectly capable of handling unicode characters just fine. You can mix Roman, Greek and Chinese characters in your textbox to your heart's content and Opera will count them consistently, no matter how many bytes each one takes to be stored. Press Enter though and all is lost.


    This cross-culture check was an important one to make. If Opera had been counting characters for .length and counting bytes for setSelectionRange, things would have got a little complicated - you never know quite how many bytes will be needed to encode the most exotic character a user might one day need. As it's only carriage returns that mess us up, we know we can only ever be out by at most a factor of two. Thus we can just say this:

    var len = $(this).val().length * 2;
    this.setSelectionRange(len, len);

    That will handle the worst case where the textbox contains only carriage returns.


    A quick check to ensure that no browser minds us trying to go beyond the end of the string like this, and we really, truly, are all done now.


    My only remaining moral obligation was to ensure that no one else had to reproduce this effort. I've bundled this all up into the PutCursorAtEnd jQuery plugin. The code for release 1.0 is as follows - tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00, and probably safe in pretty much everything else too:

    // jQuery plugin: PutCursorAtEnd 1.0
    // http://plugins.jquery.com/project/PutCursorAtEnd
    // by teedyay
    //
    // Puts the cursor at the end of a textbox/ textarea
    // codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
    (function($)
    {
        jQuery.fn.putCursorAtEnd = function()
        {
            return this.each(function()
            {
                $(this).focus()
                // If this function exists...
                if (this.setSelectionRange)
                {
                    // ... then use it
                    // (Doesn't work in IE)
                    // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
                    var len = $(this).val().length * 2;
                    this.setSelectionRange(len, len);
                }
                else
                {
                    // ... otherwise replace the contents with itself
                    // (Doesn't work in Google Chrome)
                    $(this).val($(this).val());
                }
                // Scroll to the bottom, in case we're in a tall textarea
                // (Necessary for Firefox and Google Chrome)
                this.scrollTop = 999999;
            });
        };
    })(jQuery);
  • ASP.NET 4.0 now 50% more SEO friendly

    Monday, January 11, 2010

    Okay, so I made that statistic up, but this post will cover some of the extra SEO related goodness Microsoft is including in the .NET framework.

    I previously mentioned the Microsoft SEO Toolkit which helps find SEO issues with your site here.

    Why is Microsoft including SEO features anyway?

    For public facing web sites and web applications, visitors are the lifeblood that keeps their businesses flowing. Every visitor is a potential customer, and who doesn't love customers?

    For most web sites, a high proportion of new traffic comes from search engines, so improving the relevancy of your site will lead to higher rankings in search results. This in turn leads to greater visibility and higher traffic.

    SEO can be the difference between success and failure, and that importance is reflected in the changes made in ASP.NET 4.0.

    So what's new?

    1. Page.Keywords and Page.Description.

    The Keywords and Description meta tags have traditionally been the first place to optimise your pages, in keywords you can offer a list of words relevant to the current page. Description is used as a short description of the page, search engines often show this as part of the listing in the results, so it's very important.

    Whereas before you had to manually inject keywords and description into a page, you can now manipulate these directly via the Page class.

    2. Permanent Redirects

    Renaming links and removing old content that have previously been indexed can lead to an accumulation of stale links. Nothing turns visitors off like a big error page when they click one of your broken links.

    One way to handle these broken URLs is to do a Response.Redirect to a working URL, this means the visitor gets a page which is good, but results in the search engine believing the link is still fine, which it isn't. The best way to deal with this is to use a permanent redirect so search engines know the page has permanently moved, this means it will index the new URL and remove any dead links.

    .NET 4.0 introduces a nicer way with:

     1: Response.RedirectPermanent"("PathOfWin.aspx")

    You can do this manually by returning the 301 status code yourself, but this is certainly a win for speed.

    It also introduces the MVC method of:

     1: Response.RedirectToRoutePermanent("SomeRoute");

    I'm sure there'll be lots more info on .NET 4.0 improvements to come in future posts.

  • Dodging the browser's autocomplete when capturing the user pressing Enter

    Monday, December 21, 2009

    You often need your web page to catch when the user presses Enter, and most of the time you want to click a button or a link when they do this.

    This is nice and easy in javascript, but the browser's autocomplete feature can get in the way a bit: often the user will start typing, see the autocomplete suggestions, tap the down arrow a couple of times to pick one, then press enter to pick it.

    If your javascript kicks in at this point, that's probably not what your user meant to happen: they just wanted to select that item from the autocomplete suggestions - they didn't want to click the "Next" link just yet.

    I posted a question on stackoverflow to see if anyone else had found a solution to this that was better than saying "press tab, not enter!" to your users.

    No one had an out-of-the-box solution, but one user suggested tracking the user pressing the up and down arrow keys - they'd have to press these to get into the autocomplete suggestions.

    Much as this seems like a solution made out of string and sellotape, it totally works! We need a few more tweaks (catching page up/ page down too; not doing anything in Opera because it already does it itself).

    I've implemented this in jQuery and made it available on jQuery.com as the SafeEnter plugin.

    You can use it like this, to click an element when the user presses enter:

    $('#myTextbox').clickOnEnter(myElement);

    . or you can handle the event yourself like this:

    $('#myTextbox')
        .listenForEnter()
        .bind('pressedEnter', function()
        {
            // Do stuff
        });

    To save you going hunting for it, the full code of the plugin's here:

    //codesnippet:2e23681e-c3a9-46ce-be93-48cc3aba2c73
    (function($)
    {
        $.fn.listenForEnter = function()
        {
            return this.each(function()
            {
                $(this).focus(function()
                {
                    $(this).data('safeEnter_InAutocomplete', false);
                });
                $(this).keypress(function(e)
                {
                    var key = (e.keyCode ? e.keyCode : e.which);
                    switch (key)
                    {
                        case 13:
                            // Fire the event if:
                            //   - we're not currently in the browser's Autocomplete, or
                            //   - this isn't a textbox, or
                            //   - this is Opera (which provides its own protection)
                            if (!$(this).data('safeEnter_InAutocomplete') || !$(this).is('input[type=text]') || $.browser.opera)
                            {
                                $(this).trigger('pressedEnter', e);
                            }
                            $(this).data('safeEnter_InAutocomplete', false);
                            break;
                        case 40:
                        case 38:
                        case 34:
                        case 33:
                            // down=40,up=38,pgdn=34,pgup=33
                            $(this).data('safeEnter_InAutocomplete', true);
                            break;
                        default:
                            $(this).data('safeEnter_InAutocomplete', false);
                            break;
                    }
                });
            });
        };
        $.fn.clickOnEnter = function(target)
        {
            return this.each(function()
            {
                $(this)
                    .listenForEnter()
                    .bind('pressedEnter', function()
                    {
                        $(target).click();
                    });
            });
        };
    })(jQuery);

  • Using MSDeploy as a build task in TFS

    Monday, December 07, 2009

    MSDeploy is a new tool out by Microsoft that allows easy synching of files between servers. This can be used from inside IIS or just run from command line.

    You can read more on MSDeploy here. Read MSDeploy's team blog. Nice article on using the msdeploy command line.

    I thought I would share an actual use of the MSDeploy in our TFS build scripts. It also uses the XmlUpdate task from the MSBuild Community Tasks Project.

    <Target Name="AfterDropBuild">

    <!--
    Update web.config to be in release mode -->
    <XmlUpdate XPath="/configuration/system.web/compilation/@debug"
    XmlFileName="$(DropLocation)\$(BuildNumber)\Release\_Published
    Websites\Site\web.config
    " Value="false" />

    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
    BuildUri="$(BuildUri)"
    Message="Deploying Website"
    Condition="'$(IsDesktopBuild)'!='true'" >
    <
    Output TaskParameter="Id" PropertyName="InstallerStepId" />
    </
    BuildStep>

    <
    Exec
    Command='"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
    -verb:sync
    -source:contentpath="$(DropLocation)\$(BuildNumber)\
    Release\_PublishedWebsites\Site"
    -dest:contentpath=\\SERVER\Websites\Site
    '
    ContinueOnError="false" />

    <
    BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
    BuildUri="$(BuildUri)"
    Id="$(InstallerStepId)"
    Status="Succeeded"
    Condition="'$(IsDesktopBuild)'!='true'" />

    <
    OnError ExecuteTargets="DeploymentFailed" />

    </
    Target>

    <
    Target Name="DeploymentFailed">
    <!--
    Called if deployment of the web site fails -->
    <
    BuildStep
    TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
    BuildUri="$(BuildUri)"
    Id="$(InstallerStepId)"
    Status="Failed"
    Condition="'$(IsDesktopBuild)'!='true'" />
    </
    Target>

  • Inline Block not quite Inline-blocking in IE8

    Monday, November 30, 2009

    So we have been working on a site that has a good amount of buttons on it, but input buttons aren't that easy to make look nice.

    So i've been round the site fitting snazzy buttons built out of anchors and spans with backgrounds to complete the look.

    We've made use of the 'Inline-block' setting of the display css style. It looks proper nice in Firefox, Safari, Chrome, and Internet Explorer 7.

    But.

    Internet Explorer 8 makes a right meal out of it!

    image

    All buttons that are next to each other appear stacked on top. IE8 seems to have a problem coping with 'Inline-block' elements.

    However, there is a quick fix it would seem, to this stacking issue. All that is needed to get Internet Explorer 8 to honour the 'Inline-block' style is add a 'margin-right' of some value, like so:

    image

    and now all the browsers render the buttons nicely:

    image

  • Tim Jeanes - TechEd 2009 - Day 5

    Friday, November 13, 2009

    WIA308 - The Biggest Little-Known Features in Microsoft Silverlight

    (All samples from this session are available at http://www.wintellect.com/downloads/techedeurope2009.zip)

    Typically Silverlight uses the browser's connectivity for all network access. However, Silverlight 3 introduces the "client stack", that uses the operation system's networking APIs. This makes it a lot more stable and reliable - for example you now get full access to headers, and when you hit a SOAP error you'll now get the full error details back, instead of the munged version that the browser returns (the browser stack will only ever return a 200 or a 404). This also gives you access to http PUTs and DELETEs, rather than just GET and POST as supported by the browser stack.

    On the other hand, the client stack will never give you cached results; also you're limited to two concurrent connections.

    You just have to call this:

    HttpWebRequest.RegisterPrefix("http://[whatever]",
    WebRequestCreator.ClientHttp);

    ... and then access connections as usual.

    An event called CompositionTarget.Rendering is fired about 60 times per second on the UI thread, and can be used for custom animations. It's mostly used for games, but can be useful elsewhere, for example to work through a long-running queue of changes that need to be made to the UI - running on another thread would be inappropriate as that thread wouldn't be able to update the UI.

    There's an enhanced frame-rate counter that monitors the amount of memory used by the GPU.. This is shown when EnableFrameRateCounter and EnableGPUAcceleration are both set to true.

    BitmapCache.RenderAtScale can be used to scale up controls using the GPU, without pixelation.

    A new class called Analytics allows you to monitor CPU load (both by this process and by all processes), as well as information about any GPUs that might be present.

    The AssemblyPart class represents an assembly that's part of a Silverlight application. AssemblyPart.Load enables you to load assemblies at runtime, minimising the initial download time of the application. (NB. this can only be called on the UI thread.) By changing the CopyLocal property of a reference to false, you still get full intellisense when developing the application, but it's not sent down in the initial xap file. So long as you dynamically load the associated dll before you try to use it, your application will still work.

    Be careful though! The JIT compiler compiles methods the first time it sees them: if this happens before you've loaded the assembly, you'll get a runtime exception. Also, the JIT compiler may choose to in-line some methods, so you don't know for sure when a method will be compiled. The safest way to avoid this (and retain strong-typing) is to use the [MethodImpl(MethodImplOptions.NoInlining)] attribute on the method that uses the dynamically-loaded reference.

    Application Extension Services are services that have the same lifetime as the Silverlight application - they start just before the app, and end just after it ends. Implement IApplicationService (and optionally IApplicationLifetimeAware) on a class to make it such a service. We saw a sample where dynamic assembly loading was handled on-demand by such a service. It's a little complex, so check out the sample code.

    The VisualTreeHelper class gives you access to the xaml that's been generated by templates in data-bound controls. This can be handy for programmatically styling items in a list, for example.

    Silverlight 3 now has support for xaml-styled modal dialogs, using Child Windows.

    VirtualizingStackPanel acts like a StackPanel that handles large numbers of items much better, by deferring templating the items until they scroll into view. ListBox now uses it by default, though ComboBox still doesn't.

    RelativeSource can be used to bind a property of an element to the property of a nearby control (such as its parent).

    AutomationPeer is usually used for accessibility issues, but can also be used to simulate button clicks.

    NetworkInterface.GetIsNetworkAvailable() tells you whether or not a network is available. NetworkChange.NetworkAddressChanged is an event that will let you know when the network drops out or comes back.

    DEV312 - Using and Extending Microsoft Visual Studio 2010 Architecture and Modelling Tools

    A lot of this was typing code, so I won't reproduce it here, but there were a few key points.

    Visual Studio uses MEF (Managed Extension Framework) as its extensibility mechanism, so it's now included in VS2010. It gives you extensions for commands, gestures (such as drag-and-drop) and model validators. This does most of the hard work for you, giving you easy points to plug into VS events, so you can just concentrate on the things you want to do.

    Model validators can be set to run whenever the model is saved or opened, or run manually from a menu.

    VSIX is a packaging technology that uses Office's xml model to package up your extensions and makes them much easier to install.

    Whilst developing an extension, pressing F5 launches a new instance of Visual Studio, installs the extension, and enables debugging in the first instance. This instance is entirely separate from a normal one, down to using its own set of registry settings. This is so much easier than it used to be!

    There's a whole now (and much, much easier) model for inspecting and altering existing code. This was a third-party library he found, but I'll see if I can dig it out - our code generation tools are a little painful to work with sometimes.

    This session focused entirely on extending the class diagram and the UML model diagram, but I believe similar extensions are available for other actions and items in Visual Studio.

    DEV301 - Microsoft Visual Studio Tips and Tricks

    I was going to try to keep up, writing them here as they were explained, but there were too many coming too fast, and in any case there'll all here: scottcate.com/tricks. Thanks Scott!

    (Most of these work in VS2008 as well - you don't have to wait for VS2010.)

  • Tech Ed 2009 - Friday - Neil Bostrom

    Friday, November 13, 2009

    Can you keep a secret? The biggest little-known features in Microsoft Silverlight

    The default networking calls in Silverlight are all made through the browser. This has limitations to do with when web service return server faults. The browser can not interrupt it correctly.

    There are now two networking stacks in Silverlight 3. Browser stack and client stack. The client stack goes direct to the OS network stack. This stack works correctly for web service faults. The browser stack only support 200 and 404 return codes. This is the root of the problem with web service server fault limitation. A limitation with the client stack is that it does not get the content caching built in to the browser.

    To start using the client stack, you call HttpWebRequest.RegisterPrefix("http://", WebRequesterCreater.ClientHttp) and all calls after that will be on the client stack.

    You can check any request object by checking the CreaterContext.

    Silverlight 3 has an updated frame rate counter. To enable that, add ENableFrameRateCounter and EnableGPUAcceleration.

    RenderToScale is part of the BitmapCache that allows you to control the size of the bitmap that gets handed off to the GPU by Silverlight.

    Analytics class allows logging of CPU load and GPU usage.

    AssemblyPart.Load allows you to load up assemblies on the fly. This means you can keep your xap file small and just pulled down the extra parks as and when you need them. To lighten up your xap file, you can change your references to be copy local = false. This means it won't be shipped in your xap. For the dll to be easily downloaded, put a manual copy inside the ClientBin folder.

    This technique does have a big flaw. The CLR will die trying to find that reference. The CLR scans the method before it's run for all its types. MethodImpl(MethodImplOPtions.NoInlining) forces the JIT compiler not to scan that method for types it does not know.

    Application Extension Services is a service model for building services that run with your applications. All you need to do is implement IApplicationService, StartService, StopService. Silverlight will create the service as it starts and close it just before exiting.

    SynchrosationContext.Current has access to the UI dispatcher

    VisualTreeHelper is a handy class to grab controls inside Composite controls.

    RelativeSource allows two way template binding! Awesome!

    AutomationPeer class allows you to click buttons etc.

     

    Architecting Silverlight Applications with MVVM

    MVVM is only a solution for large scale applications. It's not really ideal for small projects as it can be very bloated with layers etc.

    MVVM is Model, View, ViewModel. As you start using this concept it is very similar to MVC. You create a Model which is your entity with data access. View is your control XAML on the page and then you create a model for your view that has everything you can bind to. The advantage with this is that ObservableCollection does not need to exist in your model, you can just expose that in your VIewModel. This keeps your model very clean from UI dependant references.

    A cute way to reduce the dependency on the view calling the model in code is to use behaviours that you can just attach to elements in the view. One handy behaviour out of the box is CallDataMethod which can be wired up to to your method on the model.

     

    Code Contracts and Pex: Power Charge your assertions and Unit Tests

    CodeContracts does validation on your code and comes up with warnings for certain coding errors.  Code Contracts allows you to make code method call intentions on your methods and code contracts will generate the correct code to run that intention.

    Pex allows you to do unit testings on firing cases of your code that you might not have considered.

    The Code Contracts does make for very bloated code. For interfaces you need to make two more classes to just say something doesn't need to be null.

    Code Contracts has a runtime checker, static checker and documentation output. So that single intention gets used in a bunch of places.

  • Tim Jeanes - TechEd 2009 - Day 4

    Thursday, November 12, 2009

    WIA304 - Building Line-of-Business Applications Fast With Microsoft Silverlight and Microsoft .NET RIS Services

    Given a data model, RIA services quickly generates the domain service classes for your web layer. The generated classes include skeleton methods to get, insert, update and delete the entities. Business rules (such as required fields) are automatically passed through so that the UI can respond to them.

    The uriMApper xaml element provides a way of routing URL patterns to xaml controls, making your Silverlight application more website-like, and preserving the functionality of the back button. It uses URLs in the pattern mysite.com#/Customers - the # ensures you're really staying on the same page, so the Silverlight control doesn't have to be reloaded.

    A goal of RIA Services is to take away some of the pain of handling asynchronous events, giving you cleaner, more readable code.

    RIA Services provides you with some additional Silverlight controls. One we looked at was the DataPagerControl, that attaches to a datagrid and returns pages of data, all with writing virtually no code.

    The DataControlToolkit adds a few new Silverlight controls to get you going more quickly with editing data. For example, the DataForm control will provide appropriate input controls for each field on your object.

    The ActivityControl can be wrapped round your input form. When its IsBusy property is set to true, it masks itself and shows a Please Wait animation. This property can be bound to your domain service class (that wraps the async calls), thus making it dead easy to give your users a synchronous experience.

    To enforce security, the [RequiresAuthentication] and [RequireRole] can be added to methods, preventing them from running if the user doesn't have sufficient credentials.

    WIA303 - Microsoft ASP.NET AJAX: Taking AJAX to the Next Level

    I've never been a big user of Microsoft's AJAX offering - I felt their control toolkit wasn't particularly good-looking and wasn't flexible enough if you didn't want exactly what it did out of the box, and I found jQuery could do at least as much as I wanted - so I was interested to find out what improvements they've made to "take things to the next level".

    First up, Microsoft have launched a Content Delivery Network, hosting many common javascript files, such as jQuery, the Microsoft AJAX.NET javascript library, and the jQuery Validation library (which I really must look into). jQuery.UI's not on there yet, but they're thinking about it.

    In .NET 4.0 webforms, you can say <asp:ScriptManager EnableCdn="true" />, and it will automatically get all its script files from the CDN.

    The MS Ajax Minifier is a new offering that's available as a command line tool or an MSBuild task that works in two modes: normal minification (that strips whitespace, etc.) or hypercrunching (that goes a lot further - shrinking variable names and removing unreachable code). I think hypercrunching is probably the coolest name Microsoft's come up with for any of its products for quite some time.

    The minifier can also analyse your code and warn you of any problems it can recognise.

    (As an aside, a nice way to edit your project file in Visual Studio is to right-click it and select Unload, then right-click and select Edit. I never knew that - I've always been opening it in a separate text editor.)

    The new AJAX library isn't being shipped with VS2010 or .NET 4.0 - instead it's available as an open source project.

    It's written as a pure js library, so it will work equally well in webforms, MVC, or plain html. It integrates seamlessly with jQuery, and all its controls are exposed as jQuery plugins.

    start.js contains a script loader that will pull in any other scripts you need, and defined by the Sys.require() function. This makes it easy to ensure you get the all libraries you need, exactly once each. It also supports lazy loading, so you can load libraries at the point that you need them.

    Items can be added to the page using Sys.create.dataView. This looks for elements with a class="sys-template", which are treated as templates. The contents of the template are repeated for each item in your data source, and data fields within the template are demarked using {{field-name}}. An itemRendered event is fired for each item to allow you to perform your own custom tasks.

    Sys.bind() gives a really easy way to bind an item list with a detail view. You specify an event that fires when an item in the list is clicked, which you then use to populate your detail view. Using templates for both means you have to write almost no code.

    A major new feature is the client-side datacontext. This works much like the DataContext in LINQ2SQL in that it tracks changes to records in the browser,which can then be batched up into a single AJAX post when the save button is clicked. This also supports two-way binding, so you can have the text in html elements be automatically updated in response to the user changing the text in a textbox.

    WIA401 - Enhancing the Design-Time Experience for Microsoft Silverlight 3

    When developing controls to be used in Silverlight, bearing in mind how the designers will experience them in Blend can make a big difference to how ready they are to slap you.

    A new feature in Blend is the ability to add sample data. This makes it much clearer what the control will look like at runtime, without having to access any live data.

    Attributes can improve how the control appears both in Blend and at runtime. For example, giving a property Category and Description attributes puts the property into its own group in the designer, with tooltip text to indicate what its function is. Further attributes can change how the value is entered, how it is validated, where it appears in the list, etc.

    All the design-time code is wasted once you come to deliver your final product, so it makes sense to separate your design-time code into a separate assembly, but putting it into separate projects in Visual Studio. To do this, you must follow a naming convention for the project (and thus dll) names, and put classes in each project with the same names. This will then be respected by the design environment. Your projects should be named  *.Design, *.VisualStudio, *.Design.Editors, *.Expression.Design.

    Behaviours are a powerful tool that allow you to specify a lot of functionality without any code. Some are available out of the box, such as making an item draggable, but you can also make your own, configurable by properties in the property box in Blend.

    WIA307 - Cool Graphics, Hot Code: Visual Effects in Silverlight

    (All samples from this session are available at http://www.wintellect.com/downloads/techedeurope2009.zip)

    A class called PageTurn.cs is a class that encapsulates the Page-Turn framework. Given pairs of canvases (for the left- and right-hand pages), this provides a clean page-turning animation.

    The WriteableBitmap, new in Silverlight 3, is the root of all sorts of visual goodness. This lets you generate images on the fly, as well as taking a snapshot of controls in the running application. This can be used for anything from drawing Mandelbrot Sets, to capturing frames from a video, producing a draggable magnifying glass or the much over-used Shiny Wet Black Floor effect.

    [Aside: If your xaml contains a large picture, but you're scaling it down, then if you make a WriteableBitmap from this, telling it to scale up, Silverlight is clever enough to use the original large bitmap, rather than the smaller scaled one, thus avoiding pixelated blockiness.]

    We saw a little more of HLSL for building custom pixel shaders too. It was developed by Microsoft and is used by DirectX, so is very high-performance. It's based on C and looks a little crazy, but it's maybe not as scary as I'd thought. We saw how this can also be used to generate the Wet Floor effect. This has the big advantage that it's real time, so if your original xaml changes, so does the reflection.

    However, it's worth noting that (for now) Silverlight only uses the CPU to execute the pixel shaders; if it ever uses the GPU, we can expect much better performance.

    DEV316 - Model-Based Testing Made Easy with Spec Explorer 2010 for Visual Studio

    Spec Explorer explores your C# code and draws a state machine graph of the possible routes through it. This gives a different view of the model that can be (possibly) more easily compared with the original requirements. From this, it generates unit tests that will trace each route though the code.

    It's a little bit crazy and I don't think I'll ever use it, and that's all I've got to say about that.

  • Tech Ed 2009 - Thursday - Neil Bostrom

    Thursday, November 12, 2009

    Building Line-of-Business Applications Fast with Microsoft Silverlight and Microsoft .NET RIA Services

    RIA services provides a pattern to write application logic that runs on the mid-tier that is projected on the client side. Making producing 3 tier application simpler. It's not just restricted to Silverlight.

    Tim started off by showing the new Silverlight Business application template that comes with Visual Studio 2010 out of the box. This template seems pretty complete with loads of functionality like forms transitions, login, register, navigation, resources and styling. Very sexy, well worth looking through this template.

    Domain service class is the guts of RIA services. When adding that class it prompts to point at your model. It then generates an API using your model, insert, update, delete, etc, methods for all your entities.

    RIA services does its querying with two methods, one is the model collection name (Employees), you would bind to that. After that you would populate that collection using the Load method on the context.

    RIA services also includes some out of the box helper controls. One of them being the data pager control. As this control works on IQueryable in your model, it does true server side paging.

    RIA services takes advantage of the Data annotation syntax, similar to AJAX and MVC. This is a general direction in Microsoft which is great. We can implement this once in our common code and get validation for free on almost any client type.

    RequestAuthenication and RequiresRoles is a nice way to control method calls using forms authentication on your server side.

     

    Successfully Administering and Running Microsoft Visual Studio Team System Team Foundation Server 2008/2010

    Turns out the install success rate for TFS 2008 was quite low. Looks like we were lucky on that front. You can never rename a team project, that's why Microsoft uses codenames for projects!

    TFS performance comes from hard disk speed. Disk read / writes in SQL is where the real hit in TFS is. Try to split the databases out.

    It's recommended that you only use a single team project for your company. Use iterations and areas to break down projects. Microsoft has a single team project for "Office" and all the projects (Word, Excel etc) are all in that project. The main reasons behind this is Work items can't be moved between team projects, the out of box reports work on a single team project.

    Microsoft suggests to run TFS in a virtual environment. Benefits come from snapshot and disaster recovery.

    When splitting the tiers up, it is suggested to have sql and SSRS and web tier on the other.

    Read the online notes, LOADS AND LOADS of tips on performance. Legend!

    TFS 2010 installation has been massively simplified. Project collections now allow moving of everything to different to servers. All the new features in TFS 2010 are only available in VS 2010.

     

    Enhancing the design-time experience for Microsoft Silverlight 3

    This session is talking about creating controls that are blend friendly. That appear in Blend and are easy to design. When creating controls that would call data or webservices, check if in design time and return sample data in place of live data.

    Overide ArrangeOverride and MeasureOverride to run code on resize or move in design time. Use Dependecy Properties to make control properties available in Blend. Standard meta attribute like Description, Category, DisplayName, PropertyOrder, NumberRange, NumberIncrement, NumberFormat, EditorBrowsable will get used by Blend to breakdown the placement of the property.

    With all this extra design time code, you can get a large code base. It is suggested you break out the design time code into a new dll. If you name that DLL *.Design.dll, VS and Blend will go looking for it and use them on the fly. If you name it *.Expression.Design.dll only blend will use it. If you name it *.VisualStudio.Design.dll, visual studio will automatically pick it up. In this new dll, add reference to Microsoft.Windows.Design to get access to the extension support.

    Next topic was Behaviours. Blend has a bunch of behaviours out of the box and there is an option in blend to pull down more. Behaviours is a very easy way to wrap up a small set of functionality you would want to apply to any control.

    To build your own behaviour, inherit from Behaviour in System.Windows.Interactivity. If you want to limit it to a type, then pop that in the generic type. AssicatedObject stores what object the behaviour is being attached to.

     

    Debugging Microsoft ASP.NET and Other Microsoft .NET Production Issues with WinDbg and Microsoft Visual Studio .NET 2010

    This session is a favourite of mine, been to it for a few years and has always been very informative. This year it has been updated to take advantage of the VS 2010 feature that allows easy opening and diagnosing memory dump files. In Visual Studio 2010 the Parallel Stacks window shows a diagram of where every thread is and its stack in a lovely chart, giving you loads of insight into what's going on with your website.

    As always Tess got down and dirty with some WinDb.exe action. WinDb.exe is a low level debugging tool that is not aware of .NET. So to give it some knowledge of .NET you need to first load sos.dll. You do this by running the following command:

    .loadby sos mscorwks

    Once you have done this you can walk through some of the CLR using an array of commands. Some of the interesting things you can do is say:

    !dumpheap -stat

    This will list all of the objects on the heap. From here you can drill into the objects for more information by using

    !do (memoryaddress)

    Once you find something that you believe should have been GC'ed, you can run the following command:

    !gcroot (memoryaddress)

    To give you a tree of what the GC is holding on to! This is so immense!

    If you forget what the commands are, you can easily load up a command file that gives a handy context menu on the right using:

    .cmdtree c:\debuggers\cmdtree.txt

    You can get the cmdtree.txt from Tess's website.

    Debug Diag Tool can capture memory dumps on the fly or look for requests holding. Its produced by the IIS team and can be easily downloaded and installed.

    Tinyget is another handy little tool to stress test websites. Means you can prep your website before taking a memory dump.

     

    All You Needed to Know about Microsoft SQL Server 2008 Failover Clustering

    I know nothing about failover clustering so this was going to be a sure win! Interestingly clustering only helps with machine fail over, not database failure.When a node does fail over, any application will fail to connect while the next node comes online. So you need to put retry code in to keep your application running.

    SQL server 2008 clustering works better with Windows Server 2008 R2 clustering. So the first thing you would do is setup Windows Server Clustering. Once you have done that you can then install the SQL Server clustering installation on your primary machine. You would then add all the other machines using the Add Node option in the setup wizard.

    Sexy feature of clustering is that you can rollout patches and service packs without any downtime by applying the patches to each node, one at a time. This gives you good uptime as there is no need to take your application offline. You can even do full version upgrades, so moving from SQL 2005 to SQL 2008 with only a min or two's worth of downtime which is just the database script upgrading to SQL 2008.

  • Tim Jeanes - TechEd 2009 - Day 3

    Wednesday, November 11, 2009

    DEV310 - Software Testing with Microsoft Visual Studio Team System 2010: Part2, Making It Real

    TFS can be configured to fine degree to specify how much data is captured whilst the tester is executing manual tests (event log, intellitrace, system information, test impact, video recorder, etc. can be turned on and off, and various settings tweaked for each of them). This could be very useful in avoiding massive bloat. Worth noting is that if you're not careful you'll capture all activity in all applications - not just the application being tested.

    I'm so looking forward to Intellitrace - the ability to wind forwards and back through the code whilst debugging is going to change everything. TFS also allows you to enable this whilst the testers are testing, so the developers can replay the code execution later.

    (When using Intellitrace, it's important to access websites by machine name, rather than localhost, otherwise the recording won't work correctly.)

    TFS has a new feature called Test Impact Analysis. This records which lines of code are executed by each test case. This means that when you start testing against a new build, it will highlight which tests should be rerun. If you change something that isn't managed code (such as html), you can manually record which tests this impacts.

    You can specify configuration information for manual tests - for example you can list the browsers that the test should be run against. The tester will see this as multiple tests - one for each configuration.

    TFS has hierarchical work items - you can break tests down into test cases, and link the tests to work items that are user stories, for example.

    You can specify test steps for a test case: you can be as granular as you like with this (either "create an account" or "click on account, click register, type your name", etc.). Granular steps are a pain to write, but mean you can track more accurately where the test fails.

    You can put parameters in the test steps by prefixing with an @ (e.g. "type @FullName"). You can then specify lists of values for these parameters that will then appear as multiple iterations of the same test. The test script tool that the tester will send these values to the application being tested with a single button click, avoiding typos.

    Test steps can be marked as verification steps. You can specify the expected result, and this will oblige the tester to mark whether this step succeeded or failed.

    When running tests, the tester has the option to record their actions. These can be played back later (in whole or in part) to speed things up when they redo the test later. This works across different iterations of the same test.

    These action recordings can then be converted into Coded UI Tests. The code it generates is nice and clean - each granular step becomes a separate method in the generated code. It's impressive stuff - if a step involves clicking a link on a webpage, and you later change that link's id, the test will still try pretty hard to find the right link, by name or by inner text, etc.

    The Coded UI Tests can (and in most cases should) be tweaked by the developer to add assertions that match the verification steps in the original manual test. There's a tool that allows you to pick DOM elements directly from the browser, and add assertions as to what properties those elements should have in order for your test to pass.

    When specifying build processes in TFS, you can have it deploy your application onto a virtual environment of a number of virtual machines in a virtual environment - one VM to host the application and another to host the database, for example. All automated tests (including the the Coded UI Tests) can then be run automatically against these. As the Coded UI Tests actually open a browser to run them, these can also be run on VMs in the virtual environment, testing various browsers on various OSes.

    Damn, this is good!

    DEV304 - Extend Your Web Server - What's New in IIS and the Microsoft Web Platform

    The Web Platform Installer is a smart new tool that makes it very easy to get a web server up and running very quickly. It can install anything you choose from a massive range of products: all you need from Microsoft (.NET, IIS, etc.), plus a whole bunch of third party items (DasBlog, DotNetNuke, Wordpress, etc.). It can be used again later to fetch new tools and add-ons.

    Server Core is a cut-down version of Windows that has a minimal GUI (just a command line interface) - almost all configuration has to be done remotely. (You have to explicitly turn on remote configuration for IIS though, as you'd expect.) .NET is now available on this platform. They've removed some components (WPF, of course) to keep the overall size of Server Core minimal, but ASP.NET is there.

    IIS 7.5 supports secure FTP! At last!

    IIS has a URL rewriter that can transform nice-looking URLs (example.com/user/foo) to the ones your application requires (example.com/user.aspx?username=foo). This gives you a nice way to smarten up the URLs of an existing application without having to change the source code of the application. The tool to set this up is pretty cute: you only have to give an example URL and it will figure out the regex to use to create the transformation.

    WIA202 - Microsoft Silverlight 3 - What's in it for Developers?

    Now that more devices that access websites are using H.264/AAC encoding, it's good to see that Silverlight now supports this too, though DRM isn't currently supported (which is either a good or a bad thing, depending who you are.).

    GPU acceleration is supported now (though you have to opt-in for your application: it's not turned on by default). This doesn't include 3D support just yet, though it should be out in a later version. The setting EnableCacheVisualisation will highlight the parts of your Silverlight app that will benefit from GPU acceleration.

    However, you can simulate 3D using Silverlight's perspective 3D function. This uses plane projection transforms to give the 3D effect.

    On animation, they've built in a bunch of easing functions - the ones available will look very familiar if you use jQuery's easing plug-in.

    Pixel shaders can add effects to the visual display. There are two out-of-the-box ones: a drop shadow and a blur. You can write your own if you're not afraid of HLSL. As an easier alternative, you can use the ones made for WPF, available at wpffx.codeplex.com. Only one effect can be applied at a time, so if you want a drop shadow and a blur, you have to fudge it by containing your control in a canvas, then applying one effect to the canvas and one to the control itself.

    You can take a snapshot of Silverlight controls as bitmaps. This can be handy to show reflection effects, a ghosted item whilst dragging and dropping, or for more reliable printing.

    Silverlight now has a messaging system that allows multiple instances of Silverlight to communicate with one another. They don't have to be in the same browser window, nor even the same browser: an instance of IE can communicate with an instance of Firefox.

    DEV304 - Deep Dive Into Developing Line-of-Business Applications Running in the Cloud

    Windows Azure is great at supporting massively scalable applications, but there are a number of concerns that will need to be addressed for most such line-of-business applications.

    The first is Multi-Tenancy. If your application is to branded by multiple companies, it's important that tenant A cannot access tenant B's data. If you're using Azure tables for your data storage, you can easily create a new table for each tenant. Access to these are very fast, and having separate tables ensures each tenant's data is held entirely separately.

    If you're using SQL Azure you could create a new database for each tenant. Though this would be a maintenance nightmare for the DBA in traditional computing, Azure takes away this overhead: creating a new database is quick and hassle-free.

    Another issue is customisation and extensibility: each customer might want to skin the UI according to their brand; they may also need to alter the business logic within their slice of the application. This lends itself well to Azure tables: as the table can hold entirely heterogeneous data, adding additional properties to rows is no problem. The developer only has to remember to handle to case where the value is missing on older records.

    DEV207 - How Microsoft Does It: Internal Use of TFS and Team System for Software Development

    Microsoft have made extensive use of their own tools to develop their software, so they've learnt a lot along the way.

    One interesting point they raised was that by deferring fixing bugs, they never got round to it. Though it's more fun to be developing new code, the bugs mount up like the debt you don't want to think of. They found a much better way was always to fix all known bugs before moving on to the next implementation task. (A nice new feature of TFS is that you can set it up so that it will reject a check-in that doesn't compile or pass all unit tests.)

    Obviously Microsoft is a far bigger company than we are, so the scale of their development doesn't compare that well with us. However, it was interesting to note that they prefer to form Feature Crews: a team of no more than five developers and five testers, dedicated to producing a single feature over 6-10 weeks. This size compares well with the sort of development team that we find works as well.

    They've dropped their policy of 70% code coverage for unit tests, as they found that having too many led them to spending too much time maintaining unit tests and not enough time developing features. Instead, they try to target the most common usage path of the application. Interesting: we're currently wrestling with the balance of test coverage versus maintenance overhead.

  • Tech Ed 2009 - Wednesday - Neil Bostrom

    Wednesday, November 11, 2009

    Get Virtualised with Microsoft System Centre Essentials

    This is the first interactive session I've been to this year. As we are currently running Virtual Server at work, I thought this would be a good session to find out where Microsoft are going with virtualisation. I was very impressed with System Essentials.It has all the management of your network in one place. Very powerful support for virtualisation right out of the box.

    The best feature they showed is a three step wizard for virtualising a physical machine to a virtual machine. It will take across everything from the physical machine using bit copy. This will save us loads of hassle when moving existing boxes into Virtual Server. The manager is pretty clever when it comes to knowing which vm's will run on which host based on hard disk, memory etc.

     

    Extend Your Web Server: What's New in Internet Information Server (IIS) and the Microsoft Web Platform

    David Lowe is running this session covering the new features in IIS 7.5 that comes with Windows Server 2008 R2. He started out by covering the web platform installer. It allows you to setup your server quickly and easily. It has third party products built into it allowing you to install everything you need to run on your web server. These third party tool are like WordPress and Umbraco.

    The new MMC interface now works over HTTP allowing you to easily mange your server from anywhere. Nice!

    With Windows Server 2008 R2 now support ASP.NET on Server Core. This means you can have your web server with only command line to reduce your attack surface. The server core commands look scary as! 

    Something shocking he mentioned while chatting about this is that Window Server R2 is only 64bit!!!!

    IIS extensions are now fully supported in managed applications in Microsoft.Web.Administration.

    They have a whole bunch of extensions out of the box, giving you loads of feautes like FTP, Media Server, Routing, Advanced Logging and even database explorer.

    Secure FTP now comes out of the box in R2. You can assign SSL certificates on your FTP site to make sure all passwords are encrypted.

    IIS Application request routing module is a very nice tool for setting up web farms just using IIS. It can also be used for for forwarding sites to different boxes.

    Must remember to use the Search Engine optimization tool more. Very sexy!

    Never seen Best Practices analysis before and looks like a good tool to get security tips on your websites.

     

    Microsoft Visual Studio Team Foundation Server 2010: Becoming productive in 30 minutes

    This session is showing how to install TFS 2010 in 30 minutes. Microsoft have done some good work to make the install / configuration much easier. There is now 64x version of TFS, meaning it can make full use of uber servers.

    TFS now comes with a lovely administration console to tweak settings for TFS.

    In the new version of TFS they have introduced a concept of ProjectCollection. This means that projects are grouped into collections. These collections can be moved from server to server.

    This session did a really nice demo of TFS with VS 2010. See all the little changes on day to day work.

     

    Microsoft Silverlight 3: What's in it for developers

    Silverlight 3 introduced GPU acceleration support. This feature is opt in meaning that you have to say that your silverlight project will use GPU acceleration. It only works in full screen mode on the mac due to a restriction on the mac OS. LIttle tip bit that came out was that stretching pixels in hard cpu work. GPU acceleration really helps with that. To enable GPU acceleration, you pop EnableGPUAcceleration in the html object tag. You also have to enable any elements in your xaml that you want to be accelerated by adding CacheMode="BitmapCache". They have a debug tag called EnableCacheVisualisation which will show you what parts of your silverlight application can be improved by GPU Acceleration.

    Silverlight 3 also got video streaming improvements and more easing functions. IIS Smooth streaming is now out of the box supported.

    Another nice feature that came in Silverlight 3 is local messaging support. This means we can send messages from multiple Silverlight controls. It does it via a shared memory concept. This communication can work across tabs and browsers.

    A quick demo was shown using the new navigation APIs. This includes support for links to jump to parts of your Silverlight application. Using this enables the use of the back and forward button. Very nice!

    The power behind the navigation support comes from the frame controls. You can also control the Uri that gets produced using UriMappers on the frame control.

    They have a nice system to break out any referenced assemblies in to smaller packages meaning the client is more likely to cache common references. This reduced your xap files.

    Sexy feature when using out of browser support in Silverlight 3 is CheckAndDownloadUpdateAsync(). This method will check the version of the local app and allow you to get the latest version before running the normal application.

     

    Securing Microsoft Silverlight: Knowing the Enemy

    As we are producing Silverlight applications, I thought I should get on top of this issue. The first topic was an easy one which is packet sniffing. Simple solution, use SSL!

    To protect data, keep it on the server and send down only the XAML. Isolated storage is not secured. Its just sitting around on the disk, open to the user.

     

    How Microsoft Does It: Internal Use of Team Foundation Server and Microsoft Visual Studio

    This session was done last year but has been updated with new stats. All the advice in this session is from Microsoft experience internally. One of the big problems they suffered with Visual Studio development was putting off bugs. Doing all the work upfront and fixing the bugs at the end. This caused a big problem as they took longer to fix later.

    The speaker showed a nice end to end storyboard of the visual studio 2010, 3 years ago. Very interesting to see where they went with it and how they associated them with work items.

  • Tim Jeanes - TechEd 2009 - Day 2

    Tuesday, November 10, 2009

    Coincidentally in Berlin for the 20th anniversary of the fall of the Berlin wall.

    20 years ago today a bunch of us got away without doing our German homework because our teacher was in such a good mood.

    WIA203 - Streaming With IIS and Windows Media Services

    IIS and WMS are two quite separate products, and which you use depends largely on your specific requirements and your available architecture.

    WMS2008 sits best on its own server, separate from the server holding the original content. It then does all its own smart caching, automatically dumping the less-viewed content from the cache, and preserving the media that is more on demand. A raft of recent improvements mean it can handle more than twice as many simultaneous connections as could WMS2003.

    On the other hand, if you're just delivering media from a web server, IIS Media Services may well be enough. It's a freely-available downloadable add-on to IIS that gives a bunch of features to improve media delivery.

    It has some nice settings to give more efficient usage of the available bandwidth. Typically users only watch 20% of the video media that they actually download, so the other 80% is wasted bandwidth that the media provider still has to pay for. You can configure IIS to treat media and other data files differently dependent on their file type. Typically you'd set it to download as fast as possible for the first 5-20 seconds, then drop to a proportion of the required bit rate for the rest of the video. This gives a quick spike on bandwidth initially followed by a constant rate of just enough to ensure the user doesn't experience any delays in the media they're viewing.

    If you need to control how and what the end user watches (for example, they may need to be forced to watch an advert before they can see the main content), you can control how they can stream and download the content. In the playlist you define on the server you can enable or disable the user's ability to skip videos or to seek within them. The URLs of the actual videos being sent are automatically obfuscated to ensure that the URL of the main content isn't guessable by the end user.

    Smooth streaming is now supported. This monitors the user's bandwidth and adapts the stream quality in almost-real time. This is achieved by splitting the original media into many 2-4 second long chunks and encoding each at several different qualities. IIS then delivers each chunk in succession, switching between qualities as the bandwidth allows. As it's monitored continuously, if the user experiences a temporary glitch, their video returns to its better quality within a few moments.

    Encoding at many bitrates is very CPU intensive, so doing this live is much harder work. Currently Microsoft has no offering that can manage this in real-time, so you'd need some third party hardware to do the hard work.

    DEV317 - Agile Patterns: Agile Estimation

    I suck at estimating timescales, and Getting Better At It has been on my list of tasks for the next period on every performance review I've had for the past 11 years. I'm glad to hear that I'm not alone - this was a very well-attended session where we commiserated together about how estimates (which are by definition based on incomplete information) becomes a hard deadline.

    A key concept is the Cone Of Uncertainty. This measures how inaccurate your estimates are as time goes by.

    ConeOfUncertainty

    A couple of points to note are that initial project estimates, based on the loosest information, are often out by a factor of 4 - either too long or too short; even when you have a clear idea of what the customer wants, estimates are still out by a factor of 2. Also notably, we can't guess with 100% accuracy when the software will be delivered until it's totally complete. Asked for a show of hands, the vast majority of the room said they've woken in the morning expecting to release a product today, end then haven't: even on the last day, we can't guess how long we've got left.

    As we can't avoid this, it's better to be honest about it and work with it.

    User stories

    The customer specifies a list of stories - items that must be in the product.

    Planning poker

    From user stories, we make estimates of difficulty. This is to do with priorities - not time estimation. The estimates should be based on difficulty. Planning poker cards represent order of magnitude compared with baseline. Each person places their estimates simultaneously. Disagreements lead to discussions.

    Take a baseline: a task you know well (such as a login page), then compare the complexity of each other item with this (this is twice as hard as that, etc.).

    Story points

    Break down stories into smaller pieces (that will later become your individual work items). Give each a number of story points: a number of units of relative size - multiples of say a notional hour or day, depending on the scale of the project. These aren't still really your time estimates as you don't really know yet how quickly you're going to work through them.

    Play planning poker again to decide the number of story points for each item.

    Product backlog

    The list of work items becomes your backlog, each with an estimate attached to it. At this point you meet with the customer to prioritise the items in the backlog.

    Velocity

    Developers commit to a number of story points for the first sprint. At the end of the first sprint, the number of completed story points is your velocity.

    TFS has some plugins that help to monitor and calculate this.

    Re-estimation

    After each sprint, the customer may add more stories to the backlog, and can re-prioritise the backlog. The developers may also add bugs to the backlog.

    Each sprint gives you increasingly accurate predictions of future delivery.

    DEV303 - Source Code Management with Microsoft Visual Studio 2010

    Branching has been improved: it's now a more first-class part of TFS. Branches have permissions associated with them to allow or prevent certain users from creating or merging branches. It's a faster process now as no files have to be checked out (or even copied to your local machine) to create a branch in TFS.

    You can create private branches by branching code and setting permissions on the new branch. Also, there's a graphical tool that shows how branches have been created and how they relate to one another. This is interactive, so branches can be created or merged from here.

    When viewing the history of a file or project, changesets that were branches can be drilled into to show the changes that happened in the main branch, prior to it being branched into your project.

    Changesets can be tracked visually through branches and merges - you can show where a change has been migrated between branches - either on the hierarchical diagram of changesets or on a timeline.

    It was always a pain to merge changes where there are conflicting file renames. Fortunately this has been significantly cleaned up. The conflict is now correctly detected and you're told the original name of the file as well as the two conflicting new names.

    Similar fixes have been implemented for the problem areas of moving files, making edits within renamed files, renaming folders, etc.

    These version model changes make it a whole lot clearer what's going on if you view the history for a file that's been renamed - even if it's renamed to the same name as a file that was previously deleted. If you're using VS2005/2008 with TFS2010, you'll need a patch to ensure this works.

    Rollbacks are now a proper feature - you don't have to resort to the command line power tool to do these. Also they now properly rollback merges (previously it would forget that the merge now hadn't taken place, so re-merging would be very difficult).

    A single TFS server can now have multiple Team Project Collections. These are sets of projects with their own permissions, meaning that different teams can use the same TFS installation without access to one another's projects.

    WIA403 - Tips and Tricks for Building High Performance Web Applications and Sites

    This was a fast-paced session with lots of quick examples. I've not listed them all, but a few of them are here:

    Simplifying the CSS can improve the performance of the browser. Basically speaking, the simpler the CSS rule, the more performant it will be. Also, using "ul > li" to specify immediate children is much more efficient than catching all descendents with "ul li".

    Javascript performance can be improved by making sure you use variables that are as local as possible. Similarly, the more local the property on an object (i.e. on the object itself or on its prototype), the quicker it can be accessed.

    A powerful feature of javascript is that it can evaluate and execute code in strings at runtime. However, this can be very slow. It's often used to run code with setTimeout - it's much better to use an anonymous function instead.

    Getters and setters for properties are generally good programming practice. However, as javascript isn't compiled, the slight overhead of traversing the setter/ getter method can double the time taken to access the property.

    The length property on a string or array is not fast: it has to count all the items in it. Thus saying for (var i = 0; i < myArray.length; i++) is very inefficient. Caching the length in a variable makes it faster. Or if you're iterating over DOM elements, you can use the firstChild and nextSibling properties instead: for (var el = this.firstChild; el != null; el = el.nextSibling)

    Having a lot of cases in a switch statement is also slow: each case has to be checked in turn. A sneaky trick that can be employed is to build an array of functions instead, and just call the appropriate one. Obviously this doesn't apply in every situation.

    Rather than having many small images on your page, it's better to have one large image and specify offsets for each one you want to show. SpriteMe is a handy tool that will make this mosaic for you: it scans your page for images and then glues them all together.

    Doloto is a tool that monitors your javascript and tracks which functions are called. It can then generate javascript library files that are dynamically loaded in the page as they are needed. It ensures that the most common functions are available immediately and others are loaded later. A quick demo on Google maps showed that it could reduce its bandwidth spent on retrieving javascript files by 89%. Impressive stuff!

    Microsoft Expression SuperPreview can render a page as it would appear in different versions of different browsers (Firefox, IE6, 7, and 8). It will show the results side-by-side (or even superimposed on one another) and even spot the differences for you (and highlight them).

    WIA305 - What's New in ASP.NET MVC

    A new feature is to be able to compose a view out of multiple calls to actions. This appears as <% Html.RenderAction() %>. This is a little smarter than Html.RenderPartial as you can perform any necessary business logic where it belongs in the correct controller instead of having to shoe-horn it in elsewhere.

    Areas allow you to group parts of your application into logical groups. It behaves like a folder in your project, with subfolders for models, views and controllers. There's also an AreaRegistration class that registers routes for the Area. Global.asax has to call AreaRegistration.RegisterAllAreas to activate these. By default, the area appears at the top level of its views' URLs.

    An exception is thrown at runtime if Areas contain controllers with the same name. This can be circumvented by specifying which namespace should be used for the controller, when you register the route.

    Working with ASP.NET MVC 1, I've felt frustrated with the validation. A new model allows you to specify your validation once and have it applied to each layer. Your validation rules can be specified by using Data Annotation attributes, or in an XML file, or elsewhere if you write your own provider. To enable client-side validation you only need to include a couple of Microsoft javascript libraries and add the helper method <% Html.EnableClientValidation(); %> to your page. If you invent your own validation rules, you'll also have to write your own javascript version of that validation logic - the built in framework passes the rules as JSON that you can intercept on the client.

    There are some new helper methods - Html.Display, Html.DisplayFor, Html.DisplayForModel, HtmlEditor, Html.EditorFor and Html.EditorForModel. Given a model, these display read-only or input field versions of all the fields on the model. You can define your own templates for these - either by type (to implement your own date picker, for example), or by giving a name of a partial view that renders an editor for the whole model. This respects inheritance too: if no template has been defined for Employee, it will fall back to the template defined for Person.

    A nice little tweak is that by default, JsonResult now won't allow HTTP GETs. This dodges a cross-site scripting vulnerability, though you can override it if you really want.

Find out more about by contacting us