Wednesday, 25 March 2015

ASP.NET Tips #31 - New Database Access Method in Web API

Most examples of Web API use either Entity Framework directly or show some abstractions such as Repository and/or UnitOfWork, which introduce a number of classes, as well as strong typing.

That's all good. However, in many Web API cases you're simply exposing, and possibly transforming, data from a data store. You are probably reading in values from a query string, JSON, or XML, and manipulating SQL.

All of these are strings. While you can certainly use a serializer to work with inputs and use casting to correctly validate data types, in many cases you can forego the cost of boxing/unboxing or serializing/deserializing by using dynamics.

I have a gist that shows how to do this using Dapper (with Async support):

Use it as a way of eking out extra performance, rather than a standard approach.

Web API Tracing

Web API integrates tracing, so as to make it very easy to know what's going on throughout the lifetime of your services. Microsoft has released an addon package to enable tracing of Web API using System.Diagnostics. You can also find adapters for NLog and log4net on NuGet.

This is really helpful for tracking down unexpected responses or unhandled exceptions, especially in production applications. For the best performance, of course, you should use Event Tracing for Windows (ETW).

Tuesday, 24 March 2015

ASP.NET Tips #30 - Use ConfigureAwait to avoid thread hopping, especially in library code

One of the most amazing thing about using async/await keywords for async and background processes is that you don't have to do anything special to be able to interact with the UI thread.

For example, if you trigger an async operation on the UI thread, then interact with a TextBox after the code returns, the .NET framework will automatically marshal the continuation back to the UI thread for you behind the scenes.

This is often very helpful, because you need to interact with the UI thread, but there are other times where you really are thread agnostic. In those cases it is important to use ConfigureAwait to set ContinueOnCapturedContext to false. This ensures that the .NET runtime doesn't have to go through the effort of resuming your method on the thread that called it. In general, this prevents a lot of back-and-forth thread hopping, but in some cases it can be even more helpful

Consider this example using ConfigureAwait:

byte [] buffer = new byte[0x1000];
int numRead;
while((numRead = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
   await source.WriteAsync(buffer, 0, numRead).ConfigureAwait(false);

This code reads an input source in small blocks. If we were working with a large input stream, we could easily have 10, 20, or even more different await cycles. Each cycle through is at least two async calls, with two sets of callbacks to the calling thread. By using ConfigureAwait(false), the total time to execution is much lower and we truly get the best performance out of async.

Monday, 23 March 2015

ASP.NET Tips #29 - Use JValue in JSON.Net to parse complex JSON objects

When parsing the JSON response from an API, it's not always easy to model the response perfectly in C#. Fortunately, you may only need part of the response. This is where the static JValue class in JSON.Net comes in handy.

If you've got your response string, you can parse it into a dynamic type and then access the object in whatever way you need, so long as you know its structure:

using Newtonsoft.Json.Linq;
dynamic json = JValue.Parse(response_string);
foreach (dynamic something in json)
   string name =;
   int count = Convert.ToInt32(;

It's quite handy and much easier than trying to model a giant POCO after some large JSON response.

Tuesday, 17 March 2015

ASP.NET Tips #28 - Throwing HttpResponseExceptions

This is a very handy way to skip to the end of a processing chain when something goes wrong. Sure, you can return an HttpResponseMessage, but it will pass through the filters and handlers on its way out.

Throwing an HttpResponseException skips all that and goes right to the end. Use it with the same care you would use in throwing any exception.

Friday, 13 March 2015

ASP.NET Tips #27 - Protect from Cross-Site Scripting (XSS) Attack

Cross-Site Scripting attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspecting user. The end user's browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.

Cross-Site Scripting (XSS) attacks occur when:

  • Data enters a Web application through an untrusted source, most frequently a web request.
  • The data is included in dynamic content that is sent to a web user without being validated for malicious code.

The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash or any other type of code that the browser may execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to web content controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.

Microsoft AntiXSS Library

Due to the popularity of the Microsoft AntiXSS Library, ASP.NET 4.5 now incorporates core encoding routines from version 4.0 of that library.

The encoding routines are implemented by the AntiXssEncoder type in the new System.Web.Security.AntiXss namespace. You can use the AntiXssEncoder type directly by calling any of the static encoding methods that are implemented in the type. However, the easiest approach for using the new anti-XSS routines is to configure an ASP.NET application to use the AntiXssEncoder class by default. To do this, add the following attribute to the Web.config file:

  <pages validateRequest="true" />
  <httpRuntime targetFramework="4.5" requestValidationMode="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

When the encoderType attribute is set to use the AntiXssEncoder type, all output encoding in ASP.NET automatically uses the new encoding routines.

These are the portions of the external AntiXSS library that have been incorporated into ASP.NET 4.5:

  • HtmlEncode, HtmlFormUrlEncode, and HtmlAttributeEncode
  • XmlAttributeEncode and XmlEncode
  • UrlEncode and UrlPathEncode (new)
  • CssEncode

HTML Encoded Data-Binding Expressions

You can now HTML-encode the result of data-binding expressions. Add a colon (:) to the end of the <%# prefix that marks the data-binding expression:

   <asp:TemplateField HeaderText="Name">
      <ItemTemplate><%#: Bind("FirstName") %></ItemTemplate>

For one-way data binding, you use Eval:

   <%#: Eval("FirstName") %>

For two-way data binding, you use Bind:

   <%#: Bind("FirstName") %>

Thursday, 12 March 2015

ASP.NET Tips #26 - Use Microsoft’s PDBs to debug or profile external assemblies or libraries

To accurately debug or profile an external assembly or library (i.e. one you're not directly compiling), you need the PDB files that accompany each of the DLLs. These files give your debugger or profiler access to information such as function names, line numbers, and other related metadata.

One thing that sucks in particular is debugging and profiling native Microsoft .NET assemblies without this kind of information. Fortunately, there's a solution for this very issue. With a little-known feature in Visual Studio 2012 (and 2010 too!), you can connect to Microsoft’s Symbol Servers and obtain most of the debugging symbols for their assemblies and libraries.

Just go to Tools –> Options –> (expand) Debugging –> Symbols, and select the Microsoft Symbol Servers as your source for Symbols.

Getting the symbols from Microsoft every time you debug or profile is slow and painful. It'll even give you a pop-up saying as much once you check the Microsoft Symbol Servers, so be sure to specify a directory under "Cache symbols in this directory".

It will keep a local copy of the PDBs and check for updates every so often. As a result, you get your regular debugging/profiling AND you can see the function names of the Microsoft assemblies.