Monday, June 23, 2014

Salesforce Log Categories and Events by Level

The following table shows the Apex logging events that occur at each logging level by logging category. Logging events from higher levels also appear in all the lower levels.

The data is similar to that available through the Salesforce page that sets the debug log filters. That page shows the events dynamically based on the selected level in each category. Here I've currently gone for a static approach to make it more searchable.

The table is currently really wide and will probably be hard to read on lower resolution screens. I'll play around with it over time to see if the layout can be improved.

Logging Level / Category System Visualforce Apex Profiling Apex Code Callout Validation Workflow Database
  • USER_DEBUG[LoggingLevel.Error]
  • USER_DEBUG[LoggingLevel.Warn]
  • USER_DEBUG[LoggingLevel.Info]
  • USER_DEBUG[LoggingLevel.Debug - Default]
  • USER_DEBUG[LoggingLevel.Fine]
  • USER_DEBUG[LoggingLevel.Finer]
  • USER_DEBUG[LoggingLevel.Finest]

Special Cases:


See also:

Monday, April 14, 2014

Web Deployment Made Easy: If You're Using Web.config transformations, You're Doing it Wrong

With all due respect to Scott Hanselman and his Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong post, using Config Transforms can represent a significant amount of work over just copying a separate file with the complete config for each deployment environment.

There is something to be said for having a file that contains the entire config file as it will be deployed to the server. For one, it is easy to run through a Diff tool and see how the server configuration differs from a local build without first having to do a Preview Transform command.

To be fair, the following is certainly the wrong way to be approaching XML transforms. It is however quick and easy to do. Especially when migrating an existing large project. I didn't need to go through the configs line be line to diff between the local build, the shared dev environment, the staging/QA environments, and the production environments. I just copied each complete config into its separate build configuration based config file and carried on with my life.

Overtime I'll probably revisit each configuration and work towards defining the numerous differences between each environment.

<?xml version="1.0" encoding="utf-8"?>

<!-- For more information on using web.config transformation visit -->

<configuration xmlns:xdt="" xdt:Transform="Replace">
    <!-- Dump the entire contents of the configuration element from the other .config file here -->
        <!-- ... -->
        <!-- ... -->
        <!-- ... -->
        <!-- ... -->
    <!-- and so on... -->

Monday, March 24, 2014

An alternative to Salesforces Wsdl2Apex for calling SOAP web services in Apex

Salesforce provides a tool called Wsdl2Apex that allows you to generate Apex classes from a WSDL. These Apex classes act as a proxy for invoking the web service methods.

While functional, Wsdl2Apex has a number of limitations. Including:

  1. The generated Apex classes require code coverage, which needs to be created manually.
  2. You need to import the entire WSDL. In many cases you may only require a subset of the web methods. Reducing the number of methods cuts down the lines of Apex (a limited resource) that are generated and subsequently the number of lines requiring code coverage.
  3. Support for complex types that extend a base type. <xsd:extension base="foo:Bar">.
  4. Support for importing another WSDL. <xsd:import>
  5. Support for attributes. <xsd:attribute>
  6. The ordering of the generated methods appears to be arbitrary (maybe hash based ordering internally?). At the very least, a small change in the input WSDL can produce Apex that doesn't diff very well. This can be a pain with source control and tracking the history of changes.
  7. Conflicts between named WSDL elements and reserved keywords in Apex. E.g. long
  8. WSDls that contain multiple wsdl:binding elements

I've been working with an intern student here at FuseIT to create a replacement tool as part of the FuseIT SFDC Explorer under the new WSDL tab in the release. The current release is aimed at having reasonable feature parity with the existing Salesforce Wsdl2Apex implmentation.

Current functionality:

  • Import a WSDL from URL or local file.
  • User definable class names for each WSDL namespace
  • Detection of existing Apex Classes that match those being generated
  • The ability to select just the Apex methods that should be generated (including a description of the input and output parameters)
  • Publish the Apex classes directly into a Salesforce Org via the Tooling API.

Work in progress and possible future extensions:

  • Generate test Apex methods and mocks that give 100% code coverage for the generated callout code.
  • Generate HttpRequest web service calls as an alternative/backup to the WebServiceCallout.invoke calls.
  • Generate a WebServiceMock class with expanded request/response objects and doInvoke implementation.
  • Generate a wrapper Apex class that will revert to the mock implementation with running in a test case context. This could also expose the end point and timeout settings as properties.

See also:

Wednesday, March 19, 2014

Checking Salesforce ApexClass code coverage using the Tooling API

The FuseIT SFDC Explorer has been extended to provide Code Coverage reports for Apex classes.


It used to be that you could easily bring up the Code coverage for a class from the Setup > Develop > Apex Classes page. There was a column that showed the percentage per class. Clicking this column would open a page that showed the coverage status per line. This was great as you could sort by this column to find classes that with lacking in coverage. Either by percentage or based on the "Size Without Comments" of the apex class. Also, the page that came up could easily be linked to and refreshed with an F5 in the browser. The URL had the format:

Then, in the Winter 14 release they stripped this functionality out and proposed using the Developer Console instead.

Sadly, the current response from Product Management is that this useful column and page aren't coming back any time soon:

Josh Kaplan

We are slowly moving all functionality in the various setup pages into the Developer Console. Starting with the Winter '14 release, you will be able to see your code coverage metrics, at a glance, in the Developer Console tool only. This information will no longer be available in the class and trigger list views as it has been in the past.

Moving forward, the Developer Console will be the supported tool for browser-based development on the platform. It is costly to support multiple tools that perform the same function, so we are migrating everything to a single application. Over the next few releases, we will be retiring the old setup pages entirely.

You can still check the code coverage using the developer console, but I find this doesn't work well with my development. Finding the correct class and refreshing test results is ackward. Maybe it's just me and I'm missing some shortcuts with the Developer Console.

Code Coverage with the FuseIT SFDC Explorer

Happily, the Tooling API can now pull most of the required data for code coverage. So, rather than complain about lost functionality, I've started to build my own tool.

The Code Coverage tab in the SFDC Explorer is fairly minimal at this stage. You can search your Apex classes and then open up a code coverage view.

The code coverage results here rely on the results of running asynchronous test cases. You won't see any results from the synchronous test runs.

Given an Apex Class name or Salesforce Id (01p key prefix) you can quickly search for the code coverage results.

There are buttons to link to the Test History in the Salesforce Web UI or clear the current code coverage results.

Monday, December 2, 2013

Chrome v30 blocking HTTP Salesforce Web Tab

As of Chrome v30 if you have an http page configured as the URL in a Salesforce Web Tab you will be greated with a blank page.

Checking the developer console shows that the content has been blocked.

[blocked] The page at ran insecure content from http://localhost:60000/site/SalesforceLanding.aspx?SessionId=00D70000000000….

The best solution is to switch the iframe page to use SSL (HTTPS) and you won't have any further issues.

If the iframe is only for development purposes you can temporarily bypass this security check using a small shield that appears on the right of the address bar and selecting "load unsafe script"

Friday, October 18, 2013

Importing the Salesforce Winter 13 Metadata API to .NET

After updating the Metadata API to v29.0 from v28.0 I started getting the following SGEN compilation errors:

  1. Error 25 Unable to generate a temporary class (result=1). D:\...\SGEN
  2. Error 26 Cannot convert type 'XYZ.SalesforceMetadata.QuickActionLayoutItem[]' to 'XYZ.SalesforceMetadata.QuickActionLayoutItem' D:\...\SGEN
  3. Error 27 Cannot convert type 'XYZ.SalesforceMetadata.QuickActionLayoutItem[]' to 'XYZ.SalesforceMetadata.QuickActionLayoutItem' D:\...\SGEN

The QuickActionLayoutItem complexType from the v29.0 wsdl:

   <xsd:complexType name="QuickActionLayout">
     <xsd:element name="layoutSectionStyle" type="tns:LayoutSectionStyle"/>
     <xsd:element name="quickActionLayoutColumns" minOccurs="0" maxOccurs="unbounded" type="tns:QuickActionLayoutColumn"/>
   <xsd:complexType name="QuickActionLayoutColumn">
     <xsd:element name="quickActionLayoutItems" minOccurs="0" maxOccurs="unbounded" type="tns:QuickActionLayoutItem"/>
   <xsd:complexType name="QuickActionLayoutItem">
     <xsd:element name="emptySpace" minOccurs="0" type="xsd:boolean"/>
     <xsd:element name="field" minOccurs="0" type="xsd:string"/>
     <xsd:element name="uiBehavior" minOccurs="0" type="tns:UiBehavior"/>

The problem appears in the generated Reference.cs with the quickActionLayoutColumns multidimensional array return type.

              typeof(QuickActionLayoutItem), IsNullable=false)]
        public QuickActionLayoutItem[][] quickActionLayoutColumns {
            get {
                return this.quickActionLayoutColumnsField;
            set {
                this.quickActionLayoutColumnsField = value;

The XmlArrayItemAttribute typeof(QuickActionLayoutItem) should be typeof(QuickActionLayoutItem[]). After changing this manually the web reference compiled again.

              typeof(QuickActionLayoutItem[]), IsNullable=false)]
        public QuickActionLayoutItem[][] quickActionLayoutColumns {
            get {
                return this.quickActionLayoutColumnsField;
            set {
                this.quickActionLayoutColumnsField = value;

See also:

Saturday, September 14, 2013

TechEd 2013 Round Up / Summary

I've summarised some of the most interesting/important parts of my TechEd 2013 NZ notes here.

AZR301 Building Real World Cloud Apps with Windows Azure - Part 1
  • Automate Everything (Everything that can be done in the Azure portal can be automated. Rest API. + Powershell commands. Azure script site with templates)
  • VS2013 has built in support for Git.
  • Continuous Integration and Delivery -
  • Web DEV Best Practices
    • Scale out our web tier using stateless web servers. Dynamically scale our web tier based on actual usage load.
    • Multiple load balancers (Layer 7) can split requests to multiple VMs running IIS. Can handle server failure and start up a replacement VM. Lots of redundancy to handle failures.
    • Auto scaling rules based on time of day. Schedule times. Day or night for timezone. Logging shows scaling history.
    • 2 Core 4GB VM is a good starting point.
    • Instance count range and CPU load scaling.
    • Avoid using session state if possible. Prefer the cache provider if possible. Use CDN to edge cache static file assets. Use .NET 4.5 async to avoid blocking calls.
  • Single Sign on. - Windows Azure Active Directory (AD). Can be linked to on premise AD. Can be integrated with Salesforce. Wizard to setup sync all the users to the cloud.
  • Data Storage
    • SQL Database (Relational)
    • Table Storage (NoSQL Key/Value Store)- Advantage to store peta-bytes of data.
    • Blob Storage (unstructured files) – More like a standard file system.
    • Virtual Machines to host other options.
    • Slide – Data Storage Questions to Ask. Pros and Cons slide.
  • Data Scale and Persistence
    • Volume – MB/GB/TB/PB
    • Velocity – How quickly will it grow. Twitter – Fast data creation but only interested in most recent data.
    • Variety – Relational, images, key-value pairs, social graphs.
    • Scale out your data by portioning it.
    • Vertical Portioning. Split image data out of relational database into blobs.
    • Horizontal Portioning (Sharding). Split rows between databases based on some key (e.g. User last name).

ARC303 Hack-Ed: Wheedling and cajoling your way to success

Andy Prow and Kirk Jackson

  • Backtracking in RegEx can cause significantly increasing CPU workload. Reg Ex being used can be exposed client side with client side validation.
  • XmlDocument .Load expanding entities in the doc type. Can cause full CPU and rapidly expanding memory usage.
  • Cookies leaking out due to transitions via HTTP and HTTPS.
  • Wireshark. Exposes Client cookies sent over WIFI network.
  • File Upload Cheat Sheet -
  • Highlighted Dapper SQL Injection Risks
Information Disclosure

Entity expansion is not limited to string literals though. It could very well refer to external data like the example below.

<!DOCTYPE doc [     
    <!ENTITY win SYSTEM “c:\windows\win.ini"> 

If this document is somehow reflected back to the client it would result in disclosing information on the server that a client wouldn't have access to.

App202 Zero to Hundred - EventFinda comes to the Windows 8 store

Donnel Cyril and Mohit Singh

  • UI hidden is UI that doesn't exist. Primary controls on screen for search.
  • Incremental data loading. Lazy loading via ISupportIncremantalLoading to keep delays under 3 to 4 seconds.

DEV302 DevOps at LightSpeed, lessons we learned from building a Raygun

Jeremy Boyd and John-Daniel Trask

  • Octopus Deploy - Automated deployment to staging the production environments
  • Git - create a topic branch for any new task
  • ElasticSearch - for scaled search. Plus REST .NET API for interacting with it.
  • Redis - Out of process cache that can handle Key value pairs, queue data structures, hash structures

ARC305 Hack-Ed: Develop your Security Spidey-Sense

Andy Prow and Kirk Jackson

Indicators of potential security flaws in a website

  • Unlocked Vault
    • Dropping out of https to http - certain cookies should be marked to only send over https. Add Strict Transport Security header
      Strict-Transport-Security: max-age.
      Sesion abandoning on login. Especially from http to https
    • Password field with length and/or character limit - May indicate that it isn't being hashed and salted on storage.
    • Files that expose secret content (robots.txt, sitemap.xml)
    • Cached search engine results.
  • Too Trusting
    • Too many invalid password attempts. Use the brute force detection built into ASP.NET Membership Provider (max invalid password attempts, password attempt window)
    • Change password without entering existing password
    • Characters give errors, or display incorrectly: < ' " ; UTF smiley face.
    • Client only validation of user input.
    • User content displays directly on screen unescaped. <
    • No random tokens in the form data. CSRF
    • URLs are in the query string
    • SQL statements in the query string
  • Spilling your secrets - Information is being leaked out of the system.
    • Signup or password reset contains an existing password - should use one time URL for resetting password.
    • Site lists characters that are banned in text fields
    • Customer id (or similar object reference) in the URL
    • A number in the URL that increases by one (or in an obvious format)
    • You can tell the underlying technology
  • Back door is open - Front-door security is good but someone's left alternative avenues into the system.
    • Sensitive data is unencrypted
    • Authorisation - by URL or menu
    • Admin site available to the world - god mode. Separate God mode app.
    • Production data in a test environment. Dev laptop has production data / credit card details but no security of production.
  • D.I.Y Security
    • Doesn't use out of the box forms authentication
    • Custom single-sign-on
    • Home-built encryption
  • Dodgy Foundations - There is a poor underlying architecture or technology.
    • Mix of technologies (PHP and ASP.NET)
    • Cross-domain javascript / CSS
    • Rich Client components
    • Old OS, server, ASP.NET version
    • Built using Webforms
    • Writing directly to disk
  • Risky Business - Features requiring strong security have not been done
    • Application accepts file uploads
    • Parsing XML, HTML or other file formats
    • Credit card payments
    • Mobile app talking to API.

DEV304 C# on a diet with scriptcs

Glenn Block

  • Node.js - No IDE or project required. Minimal install
  • Microsoft Roslyn CTP - Compiler as a service
  • scriptcs - No IDE, project, class, namespace, Using statements
  • .csx is the Roslyn file extension.
  • #load to pull in seperate .csx
  • #r "System.Data"; // Get DLL out of GAC
  • using System.Data;
  • Visual Studio load in exe. Add - debug. Can be used to hit breakpoint.
  • Can be run standalone. REPL.
  • ScriptArgs[0] - access command line arguments. Anything after --
    Can be used to create full line command line tools.
  • scriptcs - install mongodb
    packages.config to pull dependancies
    Removes need for #r from GAC.
  • Script Packs - Require(); // Will discover from Packages folder. Skips need for using.
  • Hosting - Host scripts within an existing app.

Day Two

DEV305 Level up your API with Hypermedia

Amy Palamountain

Reduce the overhead of updates. Client can adjust to changes dynamically. No need to support older version of the API. Self navigation of API. Primary Concern. - Accessible - Consistent - Descriptive - Flexible - shield from breaking changes.


DEV306 10 F# Features Every C# Developer Should Crave

Ivan Towlson

  • F# match expression. No side affects to set the variable
  • immutability - Given by default in F#. Lots of extra effort in C# to hide behind Get only properties and equality overloading.
  • Discriminated Unions - Creating a parser. F# is more concise and isn't open to extension like the c# abstact base class.
  • non-nullable types
    f# types can't have null values (unless interop with other languages)
  • infix notation - Can only overload existing operators in C#. F# can define new ones.
  • Partial application
  • Pattern matching
  • Units of measure

APP308 Working with devices; integrating into peripherals for Windows 8 and Windows Phone.
  • 3D printing.
  • Location awareness
  • Fingerprint scanning. Biometrics instead of passwords.
  • Scan barcodes and read magnetic stripes. POS scanners.
  • Use geofence enter/exit to trigger app actions.
  • Manage virtual smart cards for remote.
  • Scan documents and images with scanners.
  • Bluetooth and low level USB. Native USB rather than relying on third party libraries.
  • Security - WinRT apps must declare deviceCapability. HID - humaninterfacedevice (emulates a keyboard for cammands). Does not require drivers. USB takes a more complicated payload.
  • New generic USB devices.
  • Bluetooth 4.0 GAP

APP309 Taking advantage of Windows 8.1
  • Use the canvas for the primary application buttons
  • AppBar hints similar to Windows Phone
  • Provide a great search experience inside the app. New dedicated control SearchBox
  • Snap view replaced by varible widths.
  • Moving past single screen and touch.
  • Kiosk mode
  • SpeechSynthesizer
  • Second screen support. ApplicationViewSwitcher.

XAML Dev differences

  • Flyouts.
  • SettingsFlyout
  • Input Controls Header control
  • DatePicker
  • PlacholderText
  • AppBarButton, toggle
  • CommandBar
  • PDFDocument. Get individual pages.
  • MediaElement. Includes playback controls. Embed YouTube.

DEV309 ASP.Net WebApi – Whats New

Open Web Interface for .NET (OWIN)

Attribute Routing

  • Removes need for configuring the routing in the config. Instead use the Route attribute. RoutePrefix to apply at the class level.
  • Special case routing with RegEx matching.
  • Routes stay with the code.
  • config.MapAttributeRoutes().
  • Helps avoid routing issues.


  • Cross Orgin Resource Sharing
  • Generally will only work with the newer browsers. IE 9+
  • Access-Control-Allow-Origin: *


  • Edm Model != Entity Framework Model.
  • Discover
  • $select to pull specific columns. Can be useful to exclude image data columns.
  • ODataConventionModelBuilder
  • Makes Services Easier.

DEV310 Not MacGyver's JavaScript - Better Client Side Architectures.
  • jQuery - DOM abstraction library - Gets complicated really quickly. Should be used as a single tool rather than a soltuion to everything. Focus on the object model.
  • Frameworks - generally prescriptive, sometimes restrictive. Hollywood principl.
  • Library - generally focused and to the point.
  • Backbone.js Library
    • Models - data and associated functions
    • Views - UI backed by a model
    • Events - Bind and trigger custom events
    • Router - Provide linkable URLs
  • Problems with backbone:
    • Complexity isues with scaling.
    • Headaches with Routing Insanity.
    • Events can become really complex.
    • Memory Leaks (Zombie Views) View Events didn't unbind.
    • Most of the pain happens in the Router and the View.
  • "The secret to building large apps is never build large apps. Break your...
  • Modula/ Component Application.
    Modules are decoupled from each other. Removing one does not affect the other.
  • Application Orcastration as a first class concern. Responsible or the orchstration of the modules.
  • Marionette.js - helps build composite apps with backbone.
    Backbone extensions to remove boilerplate code. (ItemView, CollectionView)
    Avoids ZombieViews by unbinding.

INO301 Building Apps with the Kinect for Windows SDK
  • v1.5 More Sensor data, IR, Accelerometer, Camera Settings.
  • 1.7 Kinect Fusion. 3D scanning.
  • Kinect will consume about 60% of a single physical USB port.
  • Stride, # of bytes per single line

Day Three

DEV312 Pick your poison; pick your target - multi-platform development with .NET


C# with the .NET rather than the JVM

  • It is not write once use everywhere. UI created differently for each platform. Would otherwise give you lowest common denominator.
  • iOS will run ARM Binary to run natively. Ahead of time compilation. Certain things like reflection and generics won't work.
  • Android can run IL+JIT
  • Can run Windows, Android and iOS emulators.
  • "On the Mac, when it's time to upgrade, you just pick it up, throw it away, and buy a new one."
  • Ensure Windows VM uses two cores. One for its internal VM. Enable HyperV
  • Project Linking

APP213 Game On - Cross Platformer
  • DoDo gogo using - HTML5, impact.js, Canvas. Three.js
    HTML Drawbacks.
    • Draw Call Efficiency. Particle Effects. High Asset Count
    • Audio Management (good), but not fine grained.
    • Tooling - not storing tools for HTML games development.
  • Unity IDE for games
  • Example games using Unity - Jelly Run. Template Run
  • Advantages:
    • Pipeling - import photoshop file.
    • Tooling - All the tools to manage and manipulate a game.
    • Performance Tuning
    • Asset Store - get assets.
    • 3D
    • 2D (Unity 4.2 built in)
    • Multi-Platform deployment.
  • Code Typically written in C#. Runs on mono and targets .NET 3.5
  • Can pull .NET 3.5 Libriaries into the Unity Assets/Plugins folder.
  • Basic support for async/await. But doesn't extend to Task return types.
  • Use common assembly name between Unity .NET and Windows 8 Library to work with both.
  • Unity can process each asset on import and adjust to suit the platform. E.g. down sample for Windos phone.
  • Build config on Phone Solution to "Master" (rather than debug and release) have debug support.
  • Shaders run on the graphic card. Shader runs on Materials.
  • Cross Platform Considerations.
    • - Store approval requirements
    • - Automated certification tests
    • - Start packaging early
  • -
  • Know Your Devices
    • - High memory
    • - Low memory
    • - Resolution
    • - Graphics capabilities
    • - Aspect rations
    • - Device Capabilities
  • Implement anaylitcs. The most popular level may be the hardest level. Nuget import for anaylics in Windows phone.
  • Unity Answers

DEV414 Taming Time: A Deep Dive into the Reactive Extensions
  • The async await pattern does not compose very well.
  • IObservable. Nothing in .NET 4 implements this interface.
  • Reactive Extensions - where to get the IObservable and how to work with them.
  • IObservable.Subscribe - OnCompleted, OnError, OnNext
  • RE - Subscribe takes a delegate/callback.
  • Dispatchers . Invoke. Instead use .ObserveOn() so it runs on the dispatcher thread.
  • .Timestamp()
  • .DistinctUntilChanged()
  • IQbservable - passes query off to the remote datasource and will only the filtered results.
  • Applies the filters much earlier.

DEV316 Getting started with Git: A .NET developer's guide

Ian Randall

  • Record changes to file(s)
  • Restore
  • Who made the changes
  • Centralised VCS.
    • - Collaborate in teams
    • - Server contains history
    • - Client contains working copy.
  • Issues:
    • - Heavy network usage / slow
    • - Single point of failure
    • - Typically poor offline experience
  • Distributed VCS
    • - Repositories
    • - Fully offline
    • - Mostly local commands - fast
  • Basic commands
    • $ git init MyProject
    • $ git add
    • $ git status Changes
  • Files must be added to the staging area.
  • Commit - Commit changes to the repo. Working directory clean
  • $ git commit -m "Added Readme"
  • Unstaging - reversing add
  • $ git reset HEAD
  • Unmodify changes
  • $ git checkout --
  • Branching - Git's killer feature
  • snapshots - Git doesn't store deltas. It stores the whole file. Uses compression in storage.
  • Metadata
  • Pointers
  • A commit contains:
  • pointer to the sanpshot...
  • Labels for HEAD and master.
  • $git branch
  • $git checkout
  • Moves HEAD to the feature branch.
  • Merge or Rebase.Rebase can make it easier to read the history, but alters the previous SHAs. Rebase best when only done locally to code that isn't pushed to others.
  • Distributed
  • Git on the Server - Subtly different to client/server
  • Git clone <path>
  • $ git remote - verbose
  • $ git remote add alias <foo>
  • Remote branch
  • Pull the latest versions from the server.
    $git fetch origin
  • $git fetch
  • $git merge
  • $git pull
  • Push to remote
  • $ git push origin master
  • Pull Requests - Asking someone else to get your changes into their repository.
  • Git support in Visual Studio
    • - Select 'Git' as Source Control type in VS2013
    • - Integrated experience
    • - Brand new, but maturing
  • Git Extensions very good on windows.

DEV415 The conjurer's masterpiece - hiding complexity with async

  • "Asynchronous programming involves the coordination of multiple concurrent processes"
  • Blocking can be dangerous:
    • Scarce resources (threads): UI threads (this is only one), Javascript, I/O
    • Expensive resources: .NET ~1MB per thread memory usage. Threads are only added to the ThreadPool slowly.
    • Too many processes to coordinate. 'Duplex' connnections - long running process per user
  • Callbacks split implementation up. Intention is out of sequence.
  • Promises - Ordering correct, but exception handling is hard. Plus a large amount of ceremony code.
  • async/await - resembles the blocking code flow structure to make following the process easier. Exception handling matches the standard synchronous technique.
  • Async is a "MethodBuilder iterating over tasks and awaiting on the results"
    • Tasks - The results or promise of a result from asynchronous methods
    • Awaiters - Holds a collection of continuations, TaskAdapter acts as adapter for a Task
    • MethodBuilder - Coordinates the running of an async method. How does it iterate over the Tasks.
    • Continuations - What do I run when the task is finished?
    • Schedulers - How do I run the continuation
  • Practical async in C# - 6 things to know
    • Use TaskCompletionSource to create your own Tasks -
    • Make sure all Tasks are observed. If it returns Task make sure you await it. Important for exception handling.
    • Be careful with async void - can't await for the results and can't catch exceptions. Rule of thumb - "async void is only for event handlers at the top of the stack."
    • Use .ConfigureAwait(false) when possible - help avoid multi-threading issues. Don't come back on the same thread if the returning thread isn't important. Useful for library code.
    • Async void can still be unit tested -
      await TaskTrackingSynchronizationContext.WaitForAsync();
    • Visual Studio 2013 - Simplified debugging - Windows > Tasks - Shows all tasks that are currently active and improved stack trace.

Other interesting talks: