Thursday, December 16, 2010

Sending a Sitecore MediaStream through a HttpResponse

The following code can be used to stream Sitecore media back to the client without using the configured MediaRequestHandler.

 public class MediaDownload
  public static void ProcessRequest(Page page, Media media)
   Assert.ArgumentNotNull(page, "page");
   Assert.ArgumentNotNull(media, "media");
   if (!DoProcessRequest(page, media))
    page.Response.StatusCode = 404;
    page.Response.ContentType = "text/html";

  private static bool DoProcessRequest(Page page, Media media)
   Assert.ArgumentNotNull(page, "page");
   Assert.ArgumentNotNull(media, "media");
   if (media != null)
    return DoProcessRequestToStream(page, media);

   return false;

  private static bool DoProcessRequestToStream(Page page, Sitecore.Resources.Media.Media media)
   Assert.ArgumentNotNull(page, "context");
   Assert.ArgumentNotNull(media, "media");
   if (Modified(page, media) == Tristate.False)
    SendMediaHeaders(media, page);
    page.Response.StatusCode = 304;
    return true;
   MediaStream stream = media.GetStream();
   if (stream == null)
    return false;
   SendMediaHeaders(media, page);
   SendStreamHeaders(stream, page);
   DownloadHeaders.AddDownloadResponseHeader(page.Response, media.MediaData.MediaItem.Name, media.MimeType, media.Extension);
   using (stream)
    WebUtil.TransmitStream(stream.Stream, page.Response, Settings.Media.StreamBufferSize);
   return true;

  private static Tristate Modified(Page page, Sitecore.Resources.Media.Media media)
   DateTime time;
   string ifNoneMatch = page.Request.Headers["If-None-Match"];
   if (!string.IsNullOrEmpty(ifNoneMatch))
    return Tristate.True;
   string ifModifiedSince = page.Request.Headers["If-Modified-Since"];
   if (!string.IsNullOrEmpty(ifModifiedSince) && DateTime.TryParse(ifModifiedSince, out time))
    return MainUtil.GetTristate(time != media.MediaData.Updated);
   return Tristate.Undefined;


  private static void SendMediaHeaders(Sitecore.Resources.Media.Media media, Page page)
   DateTime updated = media.MediaData.Updated;
   if (updated > DateTime.Now)
    updated = DateTime.Now;
   HttpCachePolicy cache = page.Response.Cache;
   TimeSpan maxAge = Settings.MediaResponse.MaxAge;
   if (maxAge > TimeSpan.Zero)
    if (maxAge > TimeSpan.FromDays(365.0))
     maxAge = TimeSpan.FromDays(365.0);
    cache.SetExpires(DateTime.Now + maxAge);
   Tristate slidingExpiration = Settings.MediaResponse.SlidingExpiration;
   if (slidingExpiration != Tristate.Undefined)
    cache.SetSlidingExpiration(slidingExpiration == Tristate.True);
   string cacheExtensions = Settings.MediaResponse.CacheExtensions;
   if (cacheExtensions.Length > 0)

  private static void SendStreamHeaders(MediaStream stream, Page page)


Wednesday, December 1, 2010

Using a DllImport referenced DLL indirectly from a TestTools.UnitTesting.TestClass

Project A uses DllImport to invoke code in a third party DLL. Project B uses Microsoft.VisualStudio.TestTools.UnitTesting to run some test cases on Project A.

The automated tests in project B were failing as the DLL required by project A wasn't being copied into the TestResults directory used by the tests.

Adding the DeploymentItem attribute to the test classes in Project B with the path to the DLL revolved the issue.

Friday, November 19, 2010

Invoking a public Salesforce Web Service Method from a site

Typically when dealing with a Salesforce hosted web service you need to first authenticate to the login site to get a sessionId and Url of the server that will process the requests.

It turns out that it is possible to invoke a web service without this authentication step provided it is configured in a certain way.

Step 1

Mark the class as global and the web service as public. E.g.

 * Test to see if the web service can be connected to and used 
 * without having to log in as there is no api sObject use here.
global class HelloWorld
    WebService public static String GetMessage()
        return 'Hello world';

Step 2

In Salesforce, it is important to give public access to the class (Adding the class under Settings > Develop > Sites > Public Access Settings)

Step 3

Download and import the WSDL from the Apex class.

Step 4

Once you have imported the WSDL you will need to use the public URL of the web service rather than the standard version which requires a session to be established first.

E.g. The domain will change to use the a pattern like:


Step n+1

One of the key aspects when calling it from C# is setting ServicePointManager.Expect100Continue before creating the web service proxy. E.g.

System.Net.ServicePointManager.Expect100Continue = false;


Friday, October 22, 2010

IIS terminated web server process during debugging - Application poll ping settings in IIS

When debugging a web application from Visual Studio I've started getting the following error when I take too long to step through a process:

"The web server process that was being debugged has been terminated by Internet Information Services (IIS). This can be avoided by configuring Application Pool ping setting in IIS. See help for further details."

Try increasing the "Ping Maximum Response Time (seconds)" or turning off "Ping Enabled" entirely.

See also:

Wednesday, October 6, 2010

Sitecore CMS 6.2 - Accessing parameters in Sublayouts

<Rant>I often seem to have no end of grief when searching for Sitecore documentation straight from Google. It seems most of the useful information is buried in cookbooks and component references which are in PDF format rather than HTML and require a login to the Sitecore Developer Network. I just find it frustrating that they have lots of good documentation but it is difficult to search. I'm almost tempted to bring all their docs down to a public facing web server and letting it get indexed.</Rant>

As a case and point, I wanted an administrator editing the layout details for a content items control to be able to specify a value that would be mapped into a public property on a user control. The Additional Parameters seemed like a good candidate but didn't lead anywhere with the standard Sitecore install.

Turning to Google I found Anders Dreyers post on Accessing parameters in Sublayouts with Sitecore 5.3.1. At least with that version of Sitecore it looked like parameters weren't easily available in a sublayout.

That post did lead me to Sitecore.Web.UI.SublayoutRenderingType, which is referenced in the web.config as the rendering control for sublayouts. Using Reflector on it shows that the parameters collection could be used to automatically set properties using reflection.

After searching through the Presentation Component Reference I went to the Presentation Component Cookbook PDF via a footnote reference and then onto the SublayoutParameterHelper via another footnote.

4.5.3 How to Pass Rendering Parameters to a Control
To pass parameters to a control using the Control Properties dialog:
  • In the Control Properties dialog, enter control properties.
To pass parameters to a control using the rendering properties dialog:
  • In the rendering properties dialog, click the Parameters tab, and then enter named parameters.12
12 To access the parameters passed to a sublayout, see

Googling for SublayoutParameterHelper lead me back to Cascade the Data Source of a Sublayout down to Nested Controls PDF, which seems to explain how to use the SublayoutParameterHelper.

This looks like just what I was after. By inheriting from Sitecore.Sharedsource.Web.UI.Sublayouts.SublayoutBase rather than System.Web.UI.UserControl the parameters will be automatically mapped to the corresponding properties in the sublayout if they exist. Just remember to call base.OnInit() if you override it (as per the documentation).

Friday, October 1, 2010

ASP.NET Control.SetRenderMethodDelegate()

I was looking for a way to inject a WebControl as the next sibling of another HtmlControl where they may not be in a control tree yet. The post Adding Rendering with SetRenderMethodDelegate() - aeh, sort of seemed like a possibility but didn't eventuate as certain controls (Panels) would render their outer content before passing off the the rendering delegate.

Thursday, September 30, 2010

Using jQuery with Sitecore and avoiding conflicts with Prototype

When using jQuery with Sitecore you need to take additional steps so that the jQuery $ function doesn't interfere with the Prototype $ function that Sitecore uses for the Sitecore Ribbon.

Example from

(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
// other code using $ as an alias to the other library

See Also:

Friday, September 24, 2010

System.Web.MembershipProvider and RoleProvider references not found in unit tests after VS2010 upgrade

After updating a solution from VS2008 to VS2010 the unit tests for our custom web security providers started failing the builds with messages like:

Error    15    The type or namespace name 'MembershipProvider' could not be found (are you missing a using 
directive or an assembly reference?)    D:\Development\[snip].UnitTests\ProviderHelper.cs
Error    16    The type or namespace name 'RoleProvider' could not be found (are you missing a using 
directive or an assembly reference?)    D:\Development\[snip].UnitTests\ProviderHelper.cs
Error    4    The type name 'RoleProvider' could not be found. This type has been forwarded to assembly 
'System.Web.ApplicationServices, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. 
Consider adding a reference to that assembly.    D:\Development\[snip].UnitTests\ProviderHelper.cs

The last exception here reveals the issue. The project now needs a reference to System.Web.ApplicationServices

Saturday, September 18, 2010

Writing cleaner WebControl HtmlTextWriter output with a fluent interface

Producing HTML output from a ASP.NET WebControl is fairly verbose in terms of the amount of markup required. This isn't ideal for readability or maintenance.

When I find a workable solution I'll post it here. Right now I'm thinking it will be some form of Fluent interface.

See Also:

Wednesday, September 15, 2010

IE8 Trusted sites not displaying PDFs in a popup window with Adobe Reader 9

First, some background on the development environment:

  • Windows Server 2008 - 64 bit
  • Internet Explorer 8.0.6001.18943 (using the 32 bit exe)
  • The website is running under SSL
  • The site has been added to the Trusted sites security zone with Protected Mode off
  • The functionality works fine in Firefox and Chrome.
  • Adobe Reader 9.3.4
  • Internet Explorer add-on: Adobe PDF Link Helper

Steps to reproduce:

  • Login to the SSL site
  • Click on the javascript link that opens a new window with the URL to return the PDF.
  • The popup window opens (in my case as a tab) and is marked as being in the trusted sites zone.
  • The page appears to be completely blank with no content or HTML loaded.


It appears the issue could be related to IE8 opening the new tab in a separate process and not correctly passing the session cookies in with the new request. See Stack Overflow IE8 losing session cookies in pop-up windows.

Happened again

This definitely appears to be related to the site being in the trusted zone. In another similar case a pop up window would spawn in a new window without the session cookies when triggered from a trusted zone. When the site was taken out of the trusted zone the pop up would open in a new tab with the session cookies.

Trusted Zones and iframes

Update 23/01/2012 - Encountered another variant of this issue when the website trying to open the popup window was in the trusted security zone and an iframe of a parent site. The parent website that contained the iframe wasn't in the trusted website zone and IE was showing mixed zone security messages. When the popup window appeared it was in the trusted zone but had lost the session cookies.

Friday, September 10, 2010

The referenced assembly "log4net" could not be resolved because it has a dependency on System.Web

Here is a riddle, what is wrong with this brand new .NET 4.0 console application that only references the log4net dll?

error CS0246: The type or namespace name 'log4net' could not be found (are you missing a using directive or an assembly reference?)
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1360,9): warning MSB3253: The referenced assembly "log4net" could not be resolved because it has a dependency on "System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.


The projects target framework is set to the client profile version of the .NET framework, which excludes (typically) server side assemblies such as System.Web.

Changing the Target framework under the Application project properties resolves the issue.

See Also:

Thursday, September 2, 2010

Getting the latest version of the Adobe Flash Player when the Download Center fails


  • (IE)
  • (Firefox

Notes from Tech.Ed 2010 Presentations

Wednesday, September 1, 2010

DEV203 Implementing TFS 2010 – A Real World Perspective

Speaker(s): Gavin Lees

Tech.Ed Online

- Process Management
- Version Control
- Work Item Tracking
- Build Automation
- Reporting

Tight VS2010 integration

Advanced source Controls
- Branching/merging
- Changesets
- Shelving
- Check-in policies (add comment, work item association)

Automated builds
Lab manager
SharePoint integration
VS2010 Ultimate freatures

Team Project Collections:
- independent storage in separate SQL databases
- Logical organisation units
- improve scalability
- Can grant security access to just the collection
- Cannot link work items across collections
- cannot branch or merge code across collections
- cannot create queries across collections

Created via Team Foundation Server Administration Console.

Modifying Process Templates
- Install TFS power tools for editing templates
- Edit process templates locally.
- Accessed (Upload/Download) from the top level of team explorer. (Process Template Manager)
- ProcessTemplate.xml
- Global Lists - uploaded to TFS via the command line
- Edit .wit files but upload .xml files back to TFS.

witadmin - command line tool for working with work items. Includes functionality that isn't supported by TFS.

Reverting a changeset
- Get by changeset gets all previous changes.

Run command prompt from directory
> tfpt getcs /changeset:14


Application Tier configuration for email alerts.

DEV301 A Whirlwind Tour of the Microsoft .NET Framework 4.0

Speaker(s): Owen Evans

Tech.Ed Online

- Client Templating

Web Forms
- ClientIDMode & ClientIDRowSuffix - ClientIds less nested
- Routing - Now part of the core framework - 
 clrver -all

Visual Studio 2010 Training Kit

WEB311 The Scaling IQ Test: When Development and IT Pros Collide

Speaker(s): Richard Campbell

Tech.Ed Online

The IT/Dev Meeting
Need senior staff from both IT and dev to make app related decisions.

Email < IM < Phone < Meeting < Lunch/Food

- Accuracy (Generally first)
- Reliability (Generally second)
- Performance
- Scalability
Put them in order, every site has different priorities

Give the CTO an account call "Administrator" that is actually a guest user.

- None
- Windows (Active Directory, Basic)
- Forms Based

- Connection strings
- Ensure they are used or remove them.


- In-process vs. out-of-process
- load balancing

Load Balancing
- How to make SQL server fail over cleanly.

Performance Bottlenecks
- Scheduled tasks
- Key points that could take the application down.

Things Dev Need to Know

Network Diagram
Production Logs
- Truth about what is happening with the application
- Analysis to create test data (web trends). What are the users actually doing.
Disaster Recovery
- coding support requirements. How much data can be lost?

After the IT/DEV meeting
- Get business buy in

- Meet with IT/Dev early
- repeat

DEV306 Taming SOA Deployments using Windows Server AppFabric

Speaker(s): Peter Goodman, Stefan Sewell

Tech.Ed Online

SOA Challenges
- Monitoring

- Service hosting and Scale-out

- Deployment
  co-ordinate across multiple hosts and technologies
  support repairing, patching, updating, removing

Windows Server AppFabric ("Dublin")
- WCF & WF Service Monitoring
- Workflow Service Hosting and Scale-out
- PowerShell API and IIS Manager Extensions
- Distributed Cache ("Velocity")

- Centralised monitoring store in SQL Server
- Configurable with support for custom events.
- Not suitable for auditing as messages may be dropped under high load.

AppFabric Event Collection Service -> AppFabric Monitoring. Data passes through staging table.
Config screen for WCF Message logging.

Workflow Service Hosting and scale-out
- workflows can be restored to any server provided they have the definition.
- InstanceLock to control access to Workflows (timeout and polling for crashed workflows)
- Out of the box support for persisting to SQL Server 2008.

Automating deployments using PowerShell
- PowerShell v2
  Remote shells and remote command invocation
  In Win 7 and Server 2008
  Fully interoperable with .NET and COM components
  Call from managed code via System.Management.Automation
  Uses verb-noun pairs.

PS C:\> import-module Webadministration

Windows PowerShell ISE - Development environment

Declarative deployment
- Environment Definition
  - List of servers
  - Mapping of roles to servers
- Role Definition
- Deployment Engine

DEV401 LINQ Confidential: A Deep Dive Into How LINQ Works

Speaker(s): Ivan Towlson

Consumers versus interface implementers

- Extension methods
- Lambda expressions
- var - let the compiler figure out the type (type inference)

How the compiler compiles LINQ queries.

- Translation by compiler is naive/straight forward.
- Allows normal method resolution after first pass translation.
- Would pull all data from datasource and then filter

LINQ is very sensitive to the compile time type as to which methods get resolved to.

- Returns sequence in the same way as IEnumerable but defers to IQueryProvider that runs the actual query.

Lambda is not exactly the same as a delegate. Could be determined as an expression depending on the target(how they are used). Prefers Expressions over delegates when possible.

Lambda expression can't compile to var as it must explicitly go to Func or Expression.

Turing an expression tree into an acutal query.


Tuesday, August 31, 2010

DEV305 Parallelize Your Microsoft .NET Framework-Based Applications with Parallel Extensions

Speaker: Ivan Towlson

Tech.Ed Online

Take advantage or newer processor architecture.

.NET Framework 4 has inbuilt functionality for using this new functionality.

Like LINQ, but faster.

Querying a large dataset.

Traditional approach requires large number of considerations for treading.


Works for anu IEnumerable
- Optimizations for other tyoes(T[], IList)

Writing a PLINQ query
- .AsParallel()
- ParallelEnumerable (Does the actual work)

- Operators are replicated across partitions for (ideally) complete isolation

Operator Fusion
- Avoids excessive merging and partitioning steps

Partitioning Algorithms
- Chunk - potential for a lot of locking when doing small tasks
  Progressively hands out more work out to each thread to separate both small and large jobs.
- Range - For IList equally divide work among threads
- Stripe - For IList
  Elements handed out round-robin to each other
  Less wasted effort in the case of exception
- Hash - For IEnumerable
  Elements assined to partition based on hash code.
- Custom - Partitioner

- Pipelined: Each result becomes available as they are completed.
- Stop-and-go: For OrderBy, ToArray, ToList, etc...
  Higher latency and more memory usage.
- Inverted: no merging needed
  ForAll extension method - no buffering required.

Parallelism Blockers
- Ordering not guaranteed (consider OrderBy)
- Exceptions (Stop other threads?) - System.AggregateException
- Thread affinity - Web form controls
- Operations with < 1.0 speedup - Overhead can make the entire operation slower.
- Side effects and mutability are serious issues
  Avoid shared state, side effects  

Task Parallel Library (TPL)
- Parallel.For(o, N, i => { work(i);});
- Parallel.ForEach

- Parallel.Invoke();

Task Concepts
- FromAync

Coordination Data Structures
- Thread-safe scalable collections
- Task and data management
- Synchronisation types
    SpinLock and SpinWait for very quick waiting periods.

DEV202 Pimp My App

Speaker: Shane Morris @shanemo

- lack of whitespace causes clutter - very flat
- colour balance across the page drawing the eye to one location.
- promote symmetry.
- where is the logical starting point in the page. Queues.
- What do we want people to see and in what order?
- Uppercase is harder to read due to outline versus mixed case text.
- What is lower down on the page?
- Avoid spilt navigation

1. Graphics come last, not first.
2. Set goals
- User, business, usability, experience.
3. "You are not your user
4. test early and often
5. Go with the flow 
Start with navigation and flow of the tasks

Layout steps
1. Map out the workflow
- What would a first time user do.
2. List your content
- Widgets
- Pattern Library
3. Layout the elements in order
- left-right, top-bottom.
4. Check natural grouings
- Keep releated concepts together.

1. Remove every unnecessary element.
2. Minimise Variation
- Err on the side of consistency.
3. Colours 
"Red and green should not be seen without a colour in between."
"Angry fruit salad."
Rate 1 to 5 for visual design skills and use that many colours.
Neutral background colours are safest. (white, grey, black, navy blue,)

Pull colours from a suitable photo.

About 10% of males have some form of colour blindness.

How many diffent type faces shoul I use?

3. Line stuff up.
- Beware unintended relationships

4. Space and Size things evenly

5. Indicate Grouping
- Group boxes
- Similirity
- Proximity
- Alignment
- Empty Space

 Visual Hierarchy

6. Adjust Visual weight
Hot colours,
Irregular Shapes

DEV208 Getting Started with Workflow in .NET 4

Speakers: Stefan Sewell, Peter Goodman

What is a workflow?
- Visual sequence of connected steps. (Flowchart or state machine)
- Declarative (what we want, not how to achieve it) - SQL, HTML
- Runtime schedules execution of the steps.
- activities linked together with data that flows though and is executed by the runtume.

Why would I use a workflow?
- Business processes that can naturally map to a workflow
- Very good at handling async work. Runtime to handle the scheduling.
- Long running logical processes that are episodic in nature. Persist/Restore. Human based workflow in minutes/hours/days.
- intuitive customisation model as part of your solution. Visual DSL.

How do I create a workflow?
-  Use the System.Activities namespace rather than the older System.Activities namespace.
public InArgument Question {get; set;}
InArgument ties the properties to the runtime instance of the workflow.

"That would be an ecumenical matter."

Can write unit tests for Workflow activities.

Workflow Basics

Further reading
Total Noobs' 

How do I execute a workflow?

Workflow Service

A WCF service whose implementation is a workflow.

Service logic easily modelled as a workflow.

COS304 Azure Storage Deep Dive

Speaker: Chris Auld

Scalable - You will run out of money before disk.


15 cents per gigabyte to store.

RESTful Web Services
- Use Azure or local apps.

Asian data centres are more expensive for data.
Can CDN Enable Account

Account is secured with a 512 bit shared secret key.
500 TB per account.

Storage in the Development Fabric
 - good for developing offline.
 - costs minimal (cents) if developing with less than 1 GB of data a month.

Storage Security

- HTTPS - Digitally sign requests for privileged operations.

Azure Storage Abstractions

Blobs - Could be used to serve static content. 60 MB/s output speed. Account Container - Grouping of blobs. Limited throughput per container. Blob - Identified by name Pages / Blocks - two types of blob. Blob is always accessed by name. Special $root container. - Allows for definition of clientaccesspolicy.xml http://[account][containter]/[blobname] Can use prefix/delimiter and special blob naming to simulate directory structure. Pagination - returns continuation token (MarkerValue) to continue beyond page. Use Affinity group to keep computing and storage together and avoid paying for extra network traffic. Block Blob - used for streaming an entire file. ETags - versioning support over HTML Block blobs - can be uploaded in parallel via blocks and then recombined in Windows Azure Storage. Makes retry more efficient. Page Blob - targeted at random read/write workloads. Fixed 512 bytes Shared Access Signatures - E.g. Grant read access to a certain blob for a period of time and then pass to client as a URL. Revoke by timeout or via a container level policy that can be deleted. Ad Hoc Signatures. Policy Based Signature - container level policy allows revoking. Drives - Wrap the blob storage and allow NTFS volumes Tables - Queues -

Content Delivery Network (CDN)

Public blobs can be served via the Windows Azure CDN URL.
Could map custom domain to the CDN.

INO301 Code Different

Speaker: Ivan Towlson

C# and Visual Basic reconsidered
- Imperative
- Textual
- No extensibility mechanisms
- Minimal abstraction over the underlying machine

The assembly languages of the CLR

- A functional-object hybrid
- Included in Visual Studio 2010
- A CLR language

You can call C# or Visual Basic components from F#
You can call F# components from C# or Visual Basic

F# Features With C#/VB Equivalents

First class functions
Similar to .NET delegates 

Lambdas and closures
Similar to C# lambdas Type inference

Similar to C# var, but used much more extensively
You rarely have to write explicit type annotations in F#

Similar to LINQ

Similar to expression trees

F# Idioms

Emphasis on functions rather than records

Rich data type support: options, tuples, discriminated unions
Pattern matching

Immutable by default

Helps with asynchronous and parallel programming
“Expressions that have values” instead of “statements that perform actions”

F# Interactive REPL
Try out your code as you go (tip: Alt+Enter!)

F# Features

Asynchronous workflows and agents

Example: parallel or cloud computing interop Starcraft

Computation expressions

Customising how a sequence of expressions is executed

Parser generator

Example: simple macro or expression languages

Units of measure

Example: scientific or financial computation

WEB302 Bringing the Web to Life with jQuery

Speaker: Jeremy Boyd

Visual Studio Intellisense support.
Works well with MVC and the existing MS Ajax libraries

Helps avoid cross browser issues.

Microsoft and Google CDN versions

Requires good HTML structure for selectors.

xval for doing validation between client and server.

1. Expanders
- Expanding and collapsing divs.

Select sets using CSS3 selectors.

2. Buttons
- $("#go").click(function() { $("form").submit(); return false; } );

3. Highlighting Errored Form Elements
- .css('prop'. 'val');


4. Consuming server side JSON data
Autocomplete textbox.
$.post(url, payload, callback);
$.ajax({ type: 'POST', ...});



5. jQueryui
UI library of widgets, animation


6. 3rd Party Plugins

7. LightBox

Easing - function over time for animation.

8. Writing your own plugins
- plugin authoring

.live() - for anything that matches the selector now or in the future apply this selector.

9. Copying a cool technique you have seen

Monday, August 30, 2010

DEV304 Increase Productivity and Reduce Costs with Visual Studio Lab Management

Speaker: Anthony Borton

Tech.Ed Online

Automate virtual machine provisioning
Checkpoint as needed
Test and debug multiple environments
* Team Foundation Server 2010
* Microsoft Test Manager 2010

Includes - Microsoft Test Manager 2010

A Logical Configuration
Active Directory, SCVMM, VM Library (Template library), Hyper-V Host, TFS & Lab Management, Build Server, Developer Machines, Tester Machines.

SEC302 Hack-Ed II: Stop the hacking

Presenters: Andy Prow, Kirk Jackson

Tech.Ed Online

Enumerating usernames - finding valid users

Leaking content out to Facebook

Threat modelling


Text file with HTML in IE can run as HTML.
X-Content-Type-Options nosniff
Don't sniff any HTML content out of files.

Serve content via a handler rather than the web servers file system. E.g. They could upload a ASPX file to the upload folder and potentially run it.
Omit Content-Disposition: attachment; filename=%lt;file>

Tab Nabbing
- Change the Title
- Change the favicon
- Load the target site over the top of harvesting site.

DEV207 What's new in C# and VB.NET 4.0

Speaker: Ivan T

Tech.Ed Online

C# 4.0

Generic co- and contra-variance


IEnumerable<t> is safe as only enumerating members. Won't be adding other subtype to collection.


If T appears onlay as an output, it's safe to pass X<tderived> for X<t>
- covariance
- C# syntax X<out>

If T appears only as an input, it's safe to pass X for X
- countravariance
- C# syntax X<int>

List and IList are not supported but IComparer and IEnumerable do support.

Optional and named parameters
- Optional
public static virtual DoStuff(int first, int second = 123, int third = 456)


Not creating an Overload.
Default value is stored in the calling assembly. Something to consider when versioning the libraries. Not for external publicly visible methods.

DoStuff(888, third: 999);

Dynamic Programming
Dynamic Language Runtime

COM interop
"No PIA" Primary Interop Assembly
- Merge COM interop type definitions into the calling assembly.
- Reduces total project size.

COM interop  enhancements
- Can now leave out unnecessary arguments, auto fill in "ref missing" arguments and identify parameters by name.
- Dynamic helps with weak typing problem.

- Simple way of packaging up data into a single object without creating the actual implementation. Not meaningful property names.
Tuple.Create(true, "bob");

WEB202: Designing for HTML5 and CSS3

Speaker: Darren Wood @darren

TechEd Online

WHATWG - HTML5 workgroup. Different to the W3C
Ian Hickson

Why HTML 5?
- Support existing content
- Much reduced HEAD. E.g. Don't need to specify JavaScript as the scripting language used in the page.
- Less bytes, being more mobile friendly.

New Elements
article, aside, audio, canvas, command, datalist, details,figure, footer, header, hgroup, keygen, video.

- Replaces common CSS class that appears on the majority of pages.

- E.g. contains copyright notice.

Links to other documents. Primary navigation.

- Related content. Separate to the main content but related.

- A section of a document. Can be nested.
E.g chapters of a book. Each section can contain an H1.'

- Similar to a section.
Use an article if it could be pulled out of the page and still be meaningful.

- Native video support.
- Can have a default image.
- Can provide different content for different browser.
- Very similar to video tag.

New input types.
- search
- email
- url
- tel
- range
- number
- date
- datetime
- datetime-local
- time

- placeholder = "enter something here"
- autofocus
- Required
- autocomplete="off"

- Less divs and meaningless markup.
- Add further information.

Can now wrap block level elements in a anchor a


Drag & Drop

- Dynamic images.


 - Megabytes of local storage with query syntax

Offline Application Cache.
- Good for mobile web apps

- Substring selector (begins, ends, contains)

- Match odd li elements
- li:last child.



- Vendor Prefixes
- opacity
- rgba - colour including alpha

Multiple background images to one element. Position them separately.

Image borders. border-image.


text-overflow: ellipse;

- Good for roll overs
- skew, scale, rotate
- fade in and out on hover.

@font-face - helps older browsers work with HTML 5. Allows for CSS selectors for determining support level. Also object on the DOM for checking support. - script for embedding video and audio - - Shows cross browser versions of markup. - tells HTML support features for current browser. - Examples of what is capable. - Write ups on new elements, problems, issues. HTML5 schema for Visual Studio 2010.

FDN001 From Concept To Reality with Developer Platform and Tools

Speaker(s): Ryan Tarak

  • TFS Power Tools
  • Visualisation and Modeling Feature Pack - MSDN subscribers only
  • Generate Dependency Graph - dgml file type
  • UML Modeling support and doge generation
  • Productivity Power Tools
  • Windows Server AppFabric
  • Deploy, Scale, Manage
  • AppFabric Dashboard


  • Low capital investment with the ability to expand quickly.
  • Windows Azure Tools for Visual Studio 1.2
  • Package, deploy and debug support.
  • Client, Browser, Phone
  • WCF RIA Services
  • Rich Internet Application Services - support drag and drop for silverlight.
  • Expression 4 - single tool for targeting desktop/phone/web
  • SketchFlow
  • In Expression 4 for prototyping applications
  • Easily translates towards final product
  • TFS Integration for customer feedback.
  • DEV306 WEB307 WPH203

Notes from MS Communities Code Camp in Auckland

Security - 10 things YOU are doing wrong! - Kirk Jackson

- Rainbow table - used for reverse hash lookup
- RNGCryptoServiceProvider is the default implementation of a security standards compliant random number generator. If you need a random variable for security purposes, you must use this class, or an equivalent, but don't use System.Random because it is highly predictable.

- email as username - verify that they own the email address in question.
- autocomplete=off on inputs such as Credit card number to avoid storing the data locally. Also check PCI compliance.
- invalidate session on login.
- Presentation using

Windows Phone 7 Introduction

5 Languages in 50 minutes

- iolanguage
* prototype language similar to java script
* Uppercase indicates types. Lowercase instance.
* Zero index lists
* true is a singleton
* DSL Domain Specific Language
* Actors for concurrency

* Logic rules based language.

- Scala
* Runs on JVM
* Similar to F#
* values are immutable

- Erlang
* Ericsson Language
* Allows for crashing and resuming

- Clojure
* Lisp on the JVM

An introduction to artificial intelligence techniques

- Constraint satisfaction
Scheduling: time boxes and dependencies

Genetic algorithms
Fitness function
Shakespearean Monkeys

Deduction and reasoning
- Uncertain Reasoning
- Bayesian reasoning

Support vector machine - divide up the data space

Learning = feedback
supervised learning - training data
Neural Network connected up in layers - input nodes and output nodes

Reinforcement learning - rewarded or punished on the basis of the outcome.
Unsupervised learning

Natural language processing
F# Parser generator

Image analysis
Edge recognition

Motion detection


The Microsoft Application Server: What is it ...

Windows Server AppFabric - @ryancrawcour
What is the problem?
A: Who should build application infrastructure? plumbing
Microsofts application infrastructure - pipes etc...

Ships as part of Windows Server (soon) - switch on like IIS

Two distinct components
* Caching (codename Velocity)
* Hosting for WCF and WF (codename Dublin)

AppFabric Caching Services
What is the problem?
Distributed caching mechanism.
Improves speed, scalability and availiablity of applications that use data?
Large improvement to applications that primarily retrieve data.
* Cache in memory on single computer. Doesn't work well with load balancing.
* Could throw more hardware at the database.
* Distribute your cache on to shared computers. (AppFabric Caching Services provides this)

Cache Cluster - machines within the cluster hidden from the application using the cluster

AppFabric Hosting Service
What's is the problem?
* Build your own host
* Using IIS(http protocol only)/WAS (on top of IIS for extending bindings) hosting as is
 Difficult to monitor service state
* " with extended capabilities & management

WCF - foundation for building & consuming services
Client connects to endpoints over protocol

WF Windows workflow foundation
Model workflow activities of business process.

Workflow Services
Wrap Workflow in a WCF service. This is very similar to what BizTalk does.
Why implement the service as a workflow?
Not for database calls.
Business application - E.g. take on new staff. Setup PC, username, parking space, payroll.

AppFabric Hosting.
IIS Worker Process

Workflow is good for long running processes.

Persistence Store.

Monitoring Database. AppFabric and monitor events.

AppFabric Extensions to IIS Manager for monitoring status of Workflow and WCF.
- AppFabric DashBoard

AppFabric & Biztalk
* AppFabrix hosting services is for hosting applications
* Biztalk is for integrating systems.

Windows Azure AppFabric
* Service Bus
* Access Control

Think Async LINQ with the .NET Reactive Extensions

SuperCoder 2000

LINQ & RX (Orion Edwards - @borland)
Async - write a lot more code and tends to be harder to read intention that blocking code.
Reactive Framework - Rx
Google Reactive extensions
Add as reference once installed to project.

LINQ Fundamentals
- Any collection or stream is just a series of values
- Can be lazy loaded - values over time
- IEnumerable provides a unifeid interface to pull values.

Rx Fundamentals
- Async operations are also a sequence of values over time, but the values are pushed.
- Rx provides IObservable, a unified interface for any source to push over time.
- IObservable is the mathematical dual of IEnumberable
Use standard LINQ querying.

IObservable for PUSH based sequences
- Subscribe

Unified for
Push IEnumerable
Pull IObservable

IEnumberable on your thread.
IObservable will push on its thread. I.e. Mouse events are on the dispatcher thread.
Redirect to another thread. Dispatcher.BeginInvoke,

.ObserveOn to pass to scheduler.

Wrap up begin end pairs to make IObservable


Tuesday, August 24, 2010

Disabling and/or adjusting the drag and drop activation distance

Updated: A better Visual Studio 2010 specific solution is to install the VSCommands 2010 plugin.

Several times I've caught myself out in Visual Studio Solution Explorer by dragging and dropping a file/folder into another folder by accident. Usually the folder immediately adjacent to the file/folder being moved. The default windows threshold for drag and drop it 4 pixels. By increasing this I'm hoping to avoid accidental drag and drop.

Note: This will affect all drag and drop operations in Windows, not just Visual Studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace AdjustDragDropDistance
 class Program
  /// uAction for drag and drop horizontal threshold
  static int SPI_SETDRAGWIDTH = 76;
  /// uAction for drag and drop vertical threshold
  static int SPI_SETDRAGHEIGHT = 77;
  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

  static void Main(string[] args)
   //Default value to use the can be overridden from the command line.
   //The normal windows default is around 4 pixels.
   int _dragThresholdInPixels = 25;

    if (args.Length > 0)
     if(!int.TryParse(args[0], out _dragThresholdInPixels))
      Console.Error.WriteLine("Failed to parse [{0}] as integer for drag threshold.", args[0]);
    SystemParametersInfo(SPI_SETDRAGWIDTH, _dragThresholdInPixels, "", 0);
    SystemParametersInfo(SPI_SETDRAGHEIGHT, _dragThresholdInPixels, "", 0);
   catch (Exception ex)

See Also:

Monday, August 23, 2010

Inserting file data into a varbinary(max) column

The following are ways I've found to import binary file data into a VARBINARY column on SQL Server 2005.


This method avoids the need for a front end tool such as SSIS.

CREATE TABLE documentTable(Document varbinary(max)) 

INSERT INTO documentTable(Document) 
OPENROWSET(BULK N'C:\ImageFile.png', SINGLE_BLOB) as imagedata

Note: The file path is with respect to the SQL Server. I.e. it is loading a image file from the servers file system.

See Also:


If SSIS is available another option was to use a SSIS package as per SSIS – Importing Binary Files Into A VARBINARY(MAX) Column.

Scripting out to XML with base64 encoding

SELECT * FROM [documentTable] for xml raw, BINARY BASE64

DECLARE @xmlDoc xml
SET @xmlDoc = 


This data can then be scripted in.

DECLARE @xmlDoc xml
SET @xmlDoc = 


DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlDoc

INSERT INTO [myTable] ([Document])
SELECT [udfBase64Decode]([Document]) as [Document] FROM openxml(@idoc, '/ROOT/row') 
  [Document] varchar(max) '@Document'

EXEC sp_xml_removedocument @idoc

Friday, July 30, 2010

Using 32-bit DLLs on a 64-bit machine exposed to a .NET Web Application via COM+

I recently had some challenges calling 32-bit DLLs from a third party from a ASP.NET Web Application via COM+ on a 64-bit machine running Windows Server 2008. The 3rd party DLLs also required an ODBC connection to the database.

Issue 1 - Exception: Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154.

I'd registered the DLLs in Windows\sysWOW64 using the version of regsrv32 in that folder.

Calls to the third party DLL worked from unit tests in Visual Studio but failed from the Web Application hosted in IIS on the same machine with the 80040154 error.

Changing the application pool to "Enable 32-Bit Applications" ([enable32BitAppOnWin64]) resolved the issue.

Issue 2 - The ODBC connection was not available

I'd created the ODBC connectino using %SystemRoot%\system32\odbcad32.exe. Again, this worked fine for the VS unit tests but fell over when run from IIS.

Using odbccad32.exe from the sysWOW32 folder to create the ODBC connection resolved the issue.

Issue 3 - Calling the 32-bit COM class from the WCFTestClient.exe resulted in the 80040154 (Class not registered) exception again

Wcftestclient.exe will need to be flagged to run in as 32-bit by using the CorFlags.exe tool. E.g.

corflags.exe /32BIT+ wcftestclient.exe

See also:

Thursday, July 22, 2010

LINQ To SQL - "String must be exactly one character long.."

I used LINQ to SQL to throw together a quick data access layer to a third party database. In theory in will only be a temporary measure.

When trying to retrieve a record I got the following error:

System.FormatException: String must be exactly one character long..
System.Convert.ToChar(String value, IFormatProvider provider)
System.String.System.IConvertible.ToChar(IFormatProvider provider)
System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
System.Data.Linq.DBConvert.ChangeType(Object value, Type type)
Read_Name(ObjectMaterializer`1 )

Turns out the issue is related to a VarChar(1) NOT NULL column on the table. The Code Generation has interpreted this as char (System.Char). Changing this to string (System.String) got the system going again. There is some risk now of assigning a value longer than one charater but I can live with that for a temporary solution.

Friday, July 2, 2010

Firing an ASP.NET postback for a control on page load

The following can be used to automatically fire the post back event from an ASP.NET control when the page is done loading client side. Using ClientScript.GetPostBackEventReference() avoids the need to manually create the __doPostBack script using the controls client id.

    string triggerScript = ClientScript.GetPostBackEventReference(this.btnRefreshData, string.Empty);
    Page.ClientScript.RegisterStartupScript(this.GetType(), "PostbackControlScript", triggerScript, true);

If using an UpdatePanel with partial postback use the following instead:

    string triggerScript = ClientScript.GetPostBackEventReference(this.btnRefreshData, string.Empty);
        ScriptManager.RegisterStartupScript(this.btnRefreshData, this.GetType(), "PostbackControlScriptUpdate", triggerScript, true);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "PostbackControlScript", triggerScript, true);

Friday, June 25, 2010

IE8 security warning when mixing http and https content

Ran into an issue with IE8 showing the following prompt with every page view under SSL.

Security Warning
Do you want to view only the webpage content that was delivered securely?
This webpage contains content that will not be delivered using a secure HTTPS
connection, which could compromise the security of the entire webpage.

Turns out the addition of the Microsoft AJAX CDN service is the cause in this particular case. Changing the script link to use SSL resolves the issue.

Wednesday, June 23, 2010

Programmatic log4net configuration at runtime

I've been looking for a way to enable/disable a log4net appender at runtime through code. Doing so would remove the need to remote to the production web server to alter the logging config file.

The blog post Tweaking log4net Settings Programmatically has a extension method to perform actions on certain types of appender.

Tuesday, June 22, 2010

Visual Studio 2010 CSS colour picker

Came across a Colour picker dialog for use when editing CSS files in the Visual Studio 2010 editor.

Right click on the style and select Build Style or
Styles (Menu) > Build Style

Thursday, June 17, 2010

Disabling a Trigger for a LINQ to SQL DataContext

I have a trigger on a table that fires on updates and adds a record to another table indicating that it needs to be rolled up to an external system. In a few cases I need to dynamically suppress this trigger to prevent circular updates between the two systems. My data access is via LINQ to SQL for the system in question.

The article Disabling a Trigger for a Specific SQL Statement or Session deals with the same problem.

using(DbDataContext dc = new DbDataContext())
 //Update fields etc...

 //Set the context_info here within the open connection so that it is in-scope 
 //for the triggers
 dc.ExecuteCommand("SET Context_Info 0x55555");
 SELECT @Cinfo = Context_Info() 
 IF @Cinfo = 0x55555 
 PRINT 'Trigger Executed' 
 -- Actual code goes here

See Also:

Wednesday, June 16, 2010

ASP.NET Check if the current user can access a URL/Page

A method to verify that the user from the current HttpContext has sufficient roles to access a URL identified from the SiteMap.

  /// Can the current User access the given URL according to the SiteMap (role trimmed)
  /// URL to check. Can start with ~. Should not include query string parameters.
  /// True if the user has access.
  public static bool CanAccessUrl(string url)
   SiteMapProvider provider = SiteMap.Provider;
   HttpContext current = HttpContext.Current;
   string rawUrl = VirtualPathUtility.ToAbsolute(url);
   SiteMapNode node = provider.FindSiteMapNode(rawUrl);
   return (node != null &&
    provider.IsAccessibleToUser(HttpContext.Current, node));

Friday, June 11, 2010

TFS - Undo Checkout of Unmodified files

I've added a handy console command from the Team Foundation Server Power Tools to the end of our code generation batch file to undo checkouts on any file that hasn't actually changed.

This way the code generator can work blindly off the data source and the change set only contains the files that have actually changed.

tfpt uu "C:\Development\ProjectRoot" /noget /recursive

See also:

Thursday, June 10, 2010

Nelson .NET User Group Presentation - Common TSQL Programming Mistakes - 25th of June

Upcoming presentation

Dave Dustin from the AucklandSQL user group will be giving a presentation on TSQL.

Common TSQL Programming Mistakes

We are going to examine a variety of mistakes to which many developers fall prey - some obvious, some fairly subtle and some just plain evil! Coupled with this, we’ll be investigating some simple, and some not so, tips for increasing performance from your data layer.

Useful links:

Friday 25th June 2010
Gather at 11:50 am, starting at 12:00 pm.
Approximately 1 hour plus pizza afterwards.

FuseIT Ltd,
Ground Floor,
7 Forests Rd,
(Off Nayland Rd and behind Carters)

If you are parking on site, please use the parks marked FuseIT that are at the back of the site.

Catering: Pizza & Drinks
Door Charge: Free

RSVP to me if you are going to attend so I can guesstimate the food and drink requirements.

However, feel free to turn up on the day though if you can't commit at the moment.

Please feel free to invite anyone who may be interested in attending.

Wednesday, June 9, 2010

Codec packs

These are based on the open source ffdshow project and will add support for VP6-encoded Flash (.flv) files, H.264 video in the Matroska (.mkv) container, and Ogg (.ogg) video files to Windows Media Player.

See Also:

Tuesday, June 8, 2010

Changing the Compare/diff tool used in VS2010

Tools > Options > Source Control - Visual Studio Team Foundation Service > Configure User Tools...

For both Compare and Merge I've set the extension to .*.

Compare Arguments for DiffMerge: /title1=%6 /title2=%7 %1 %2

Merge Arguments for DiffMerge: /title1=%6 /title2=%8 /title3=%7 /result=%4 %1 %3 %2

Diffing Word Documents

Better yet, you can configure TFS to Diff Word documents.

Save the diff-doc.js somewhere convenient and reference it as the Command. Then give it the Arguments %1 %2

See Also:

Sunday, June 6, 2010

Gotchas when upgrading from VS2008 to VS2010

Ran into a few issues when upgrading a solution with 26 projects from Visual Studio 2008 to Visual Studio 2010.

I started by creating a new solution file to be used by VS2010 and added the existing projects.

Issue 1 - Referencing a higher framework version

VS2008 was fairly accepting of a framework 2.0 project referencing DLL's or projects with a higher framework target.

VS2010 will stop the build with a error like:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1360,9): warning MSB3268: The primary reference "newerFrameworkProject, Version=, Culture=neutral, processorArchitecture=MSIL" could not be resolved because it has an indirect dependency on the framework assembly "PresentationFramework, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v2.0". To resolve this problem, either remove the reference "newerFrameworkProject, Version=, Culture=neutral, processorArchitecture=MSIL" or retarget your application to a framework version which contains "PresentationFramework, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" and errors that all the functions/types used in the api dll are not defined.

In this case adding <SpecificVersion>true</SpecificVersion> to the reference resolves the issue.

See Also

Issue 2 - Project ToolsVersion

The ToolsVersion attribute on the Project node is changed from 3.5 to 4.0 by the upgrade wizard.

<Project DefaultTargets="Build" xmlns="" ToolsVersion="3.5">
<Project DefaultTargets="Build" xmlns="" ToolsVersion="4.0">

Since our TFS build server hasn't been updated yet I needed to revert this in the TFSBuild.proj

Issue 3 - Microsoft.WebApplication.targets path

The project import for Microsoft.WebApplication.targets differs for VS2010. See Working with both VS 2010 and 2008 on the team for a solution using conditional statements.

Issue 4 - System.Web.Security provider types have been forwarded to System.Web.ApplicationServices

See System.Web.MembershipProvider and RoleProvider references not found in unit tests after VS2010 upgrade

Thursday, May 20, 2010

Using jQuery to show assigned tabindex

This is a bit crude but I've found it useful for debugging tabindex attributes

     $('[tabindex]').each(function () {
             $(this).after('<span style="background-color:red;color:white;">' + $(this).attr('tabindex') + '</span>');

Sunday, May 16, 2010

BinaryFormatter versus XmlElement

Ran into an issue trying to store a Web Reference tool generated class in ViewState that had an internal XmlElement array.

System.Runtime.Serialization.SerializationException: Type 'System.Xml.XmlElement' in Assembly 'System.Xml, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

One possible solution would be to create a ISerializationSurrogate that gets added to the BinaryFormatter.SurrogateSelector (example). However, it isn't clear how this would work with ViewState serilization (I.e. where to plug it in?).

Instead I extended the partial class created by the web reference tool so that it implemented ISerializable. Then using the GetObjectData method and a custom deserilization constructor I stored the OuterXml of the XmlElement at a string.

Saturday, May 15, 2010

S4S web.config settings to use the Sandbox API

The following web.config applicationSettings can be used to override the default Partner API URL for S4S.

Note: The setting names will alter with updates to S4S as the Salesforce Partner API is updated.

        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="FuseIT.Sitecore.SalesforceConnector.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
            <setting name="Sitecore_Salesforce_SalesforcePartner170_SforceService"
            <setting name="FuseIT_Sitecore_SalesforceConnector_SalesforceMetadata160_MetadataService"

As of 1.4 the preferred approach is to change the binding environment in the connection string. E.g.

  <add name="S4SConnString" connectionString="S4S:user id=user_name;password=user_password;token=user_security_token;environment=Sandbox" />



user id

The Salesforce user name that will be used to establish the Partner API session


The password for the Partner API user. If the servers IP address isn’t trusted by the Salesforce Organization being connected to the users security token can be appended to the password.


(Optional) As an alternative to appending the users security token to the password in the connection string it can be defined separately to provide the same functionality.


(Optional) The type of Salesforce environment being connected to. Defaults to Production if unspecified which will also work for developer edition organizations if required.

Possible values:

  • Production
  • DeveloperEdition
  • Sandbox
  • Pre_release