Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, October 2, 2020

Azure Files Storage Development Part III

We've switched to using Azure Files for file storage with our ResearchStory web application. I've already written a couple of posts (here and here) about some of the things I've figured out along the way. The most recent issue I sadly discovered only after pushing code from development into production. Turns out there is a 4MB upload limit. Files can be much larger in the cloud but you need to transfer them up in 4MB (or smaller) chunks. Of course all of the files I tested with during dev were smaller than this.

Once in production I started getting RequestBodyTooLarge exceptions:

The request body is too large and exceeds the maximum permissible limit.

Searching on that exception you get this page and explanation:

Cause - There's a 4-MB limit for each call to the Azure Storage service. If your file is larger than 4 MB, you must break it in chunks.

Trying to track down possible fixes, I started with the Azure Files documentation and specially the v12.x client libraries. The overall documentation is pretty sparse. There are some basic examples but nothing complex. The Azure.Storage.Files.Shares reference documentation enumerates all of the classes, methods and parameters but just gives simple descriptions for each of them.

For example the first two parameters for the UploadRangeAsync method are commented as follows:

range   HttpRange
Specifies the range of bytes to be written. Both the start and end of the range must be specified.

content Stream
A Stream containing the content of the range to upload.

The rest of the descriptions are also this useless and there is no mention on this page of the 4MB limit (at least at the time of this blog post). This limit is documented in the REST API put-range reference but it is not documented for any of the SDK Upload* methods. There are also no examples of working around this.

After much trial and error I was able to create the following method to work around the file upload limits. In the code below _dirClient is an already initialized ShareDirectoryClient set to the folder I'm uploading to.

If the incoming stream is larger than 4MB the code reads 4MB chunks from it and uploads them until done. The HttpRange parameter specifies where the bytes will be added to the file already uploaded to Azure. The index has to be incremented to point to the end of the Azure file so the new bytes will be appended.

public async Task WriteFileAsync(string filename, Stream stream) {

    //  Azure allows for 4MB max uploads  (4 x 1024 x 1024 = 4194304)
    const int uploadLimit = 4194304;

    stream.Seek(0, SeekOrigin.Begin);   // ensure stream is at the beginning
    var fileClient = await _dirClient.CreateFileAsync(filename, stream.Length);

    // If stream is below the limit upload directly
    if (stream.Length <= uploadLimit) {
        await fileClient.Value.UploadRangeAsync(new HttpRange(0, stream.Length), stream);
        return;
    }

    int bytesRead;
    long index = 0;
    byte[] buffer = new byte[uploadLimit];

    // Stream is larger than the limit so we need to upload in chunks
    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) {
        // Create a memory stream for the buffer to upload
        using MemoryStream ms = new MemoryStream(buffer, 0, bytesRead);
        await fileClient.Value.UploadRangeAsync(new HttpRange(index, ms.Length), ms);
        index += ms.Length; // increment the index to the account for bytes already written
    }
}

Azure Files seems like a pretty good product but the SDK documentation and examples are lacking. Hopefully this improves in the future. Until then maybe this post can help someone else.

Thursday, October 1, 2020

Azure Files Storage Development Part II

Since posting last time about using two file separate subfolders for development and production I've decided to modify the approach somewhat. I still want to be able to develop and test directly against Azure but realize that there are times when I might not want to use the cloud for development. One scenario is that I might be disconnected from the internet and I don't want to be unable to develop and debug code. The other consideration is cost. While file storage is fairly cheap on Azure it still costs more than just using my local hard drive.

So (with some inspiration from this blog post) I decided to create an abstraction layer. I created a generic storage interface for the basic storage functionality I needed (list files/create/delete/read/write) and then specific wrappers for Azure Files and local files.

Here is a simple UML for the StorageFolder interface:

IStorageFolder UML

In Startup.cs I can either instantiate one of the concrete implementations based on the environment and then use Dependency Injection with the interface.

services.AddScoped<IStorageClient, AzureStorageClient>(client => {
	var shareName = WebEnvironment.IsDevelopment() ? "dev" : "prod";
	var connectionString = Configuration.GetConnectionString("StorageConnection");
	var shareClient = new ShareClient(connectionString, shareName);
	return new AzureStorageClient(shareClient);
});

I've uploaded the full implementation at this Github Gist but here are the two implementations for creating a subfolder

Here is the Azure Files implementation. The StorageFolder class is instantiated pointing to a specific folder. So creating a subfolder is relative to that directory.

public class AzureFolder : IStorageFolder {
	private readonly ShareDirectoryClient _dirClient;

	public AzureFolder(ShareDirectoryClient directoryClient) {
		_dirClient = directoryClient;
	}

	public async Task<IStorageFolder> CreateSubfolderAsync(string folderName) {
		var directoryClient = await _dirClient.CreateSubdirectoryAsync(folderName);
		return await Task.FromResult(new AzureFolder(directoryClient.Value));
	}
}

Here is the local storage implementation. Since most of the calling code is from a website I wanted to use async where available. The local file API doesn't use async but using Task.Run() you can simulate that behavior and allow for a common interface.

public class LocalFolder : IStorageFolder {
	private readonly DirectoryInfo _dirInfo;

	public LocalFolder(DirectoryInfo dirInfo) {
		_dirInfo = dirInfo;
	}

	public async Task<IStorageFolder> CreateSubfolderAsync(string folderName) {
		var path = Path.Combine(_dirInfo.FullName, folderName);
		await Task.Run(() => Directory.CreateDirectory(path));
		return new LocalFolder(new DirectoryInfo(path));
	}
}

Wednesday, September 23, 2020

Azure Files Storage Development

We've been using an App Service in Azure since first developing our site (ResearchStory). An App Service allows you to run your code in the cloud with out having to maintain a full server or virtual machine. You get local storage but it's not unlimited (there is different storage levels by tier see: Azure App Service Tiers). It's also not easy to manage remotely. You can use Kudu and extensions (like Azure Web Apps Disk Usage) to view the data in a web browser but it's still a bit disconnected.

So we've decided to add Azure Files for storage of logs and generated reports. There are some samples and basic documentation but not a lot of extended examples. In particular I tried to find an example of how others were using the code to develop locally as well as use it in production yet keep the data separated.

I had first considered two storage accounts with separate connection strings like we do for database development but that seemed overly complicated. In the end, I created two root subfolders (one 'dev' and one 'prod') inside the Azure file share. During startup the code sets the root folder based on the environment and adds a scoped reference to DI.


services.AddScoped(client => {
	var shareName = WebEnvironment.IsDevelopment() ? "dev" : "prod";
	var connectionString = Configuration.GetConnectionString("StorageConnection");
	return new ShareClient(connectionString, shareName);
});

Then any code that needs to interact with the storage system will get it injected already configured to the right subfolder.


public async Task OnGetAsync(int id, [FromServices] ShareClient shareClient) {
	...
	var dirClient = shareClient.GetDirectoryClient("reports");
	await dirClient.CreateIfNotExistsAsync();
	...
}

Friday, December 6, 2019

Enumerating a Collection with an Index

There is often the case where you want to loop over a collection of objects along with an indicator of where you are in the loop. While some languages have a built-in syntax for expressing this C# does not (yet). Using a bit of LINQ you can easily accomplish this.

Normally starting with a collection of things you might use a for loop to iterate over list and provide your index.

For example:


 var items = new List<string>();

 for (int i = 0; i < items.Count; i++) {
  var item = items[i];
  Console.WriteLine($"Item {i}: {item}");
 }

You can also use a foreach and use an temp variable to track the index.


 int i = 0;
 foreach (var item in items) {
  Console.WriteLine($"Item {i}: {item}");
  i++;
 }

Recently I discovered this gem. The following code uses a Linq Select statement to transform the list into tuples containing the index and the object as named properties. Not quite as nice as if this was built-in to the language but still nice to be able to reduce the code down.


 foreach (var (item, index) in items.Select((v, i) => (v, i))) {
  Console.WriteLine($"Item {index}: {item}");
 }

You can also add an extension method to encapsulate the Select and make it a little cleaner.


  /// <summary>
  /// Return the list as an enumerable of tuples with the item and it's index in the list. 
  /// </summary>
  /// <typeparam name="T">The typeof items in the list</typeparam>
  /// <param name="list">List to converted</param>
  /// <returns>Enumerable of tuples with the item and it's index</returns>
  public static IEnumerable<(T, int)> WithIndex<T>(this IEnumerable<T> list) => 
    list.Select((value, index) => (value, index));

And then use it like this:


 foreach (var (item, index) in items.WithIndex()) {
  Console.WriteLine($"Item {index}: {item}");
 }

Friday, July 21, 2017

Colorful serialization

I was writing some code to serialize a C# class to JSON and needed to export a System.Drawing.Color field as a hex string. Thankfully it's easy to customize the output using Json.NET. I created the following custom converter to save colors as hex strings (like #FFF0B6)

And example usage:

Saturday, April 2, 2016

Find and Replace Placeholders in a Word Template

We have a template file that we use as a baseline in our report generation (see here for help creating a new Word document from a template). The template file has some placeholders for title, subtitle, author, etc. I wanted to be able to dynamically replace those with content when the rest of the document was generated. This took me way longer than I expected to figure out so here is hopefully some info to help the next person. First I found the relevant section in the XML (the Open XML Productivity Tools are a great help for this). Then with a bunch of trial and error I figured out how to find and replace the '[Document title]' placeholder.

Tuesday, December 15, 2015

Scratchpad Tools

Whenever I want to test out some small C# code I use the excellent LINQPad. It's great as a quick scratchpad for everything from a couple of lines of code to a small program. You can reference your own class libraries so it's great for performance testing. I also use it a lot to transform files. The free version is nice but if you can swing it, Pro is worth it just for the auto-completion.

For JavaScript testing and debugging it's hard to beat JSFiddle. I use it often and like the ability to save and share snippets of JS. I was interested when I found .NET Fiddle online. Could it offer the same versatility of LINQPad and the online sharing of JSFiddle.

I took the code from my last blog post and pasted it in .NET Fiddle. Interestingly by default code is evaluated and run as you enter it (you can turn this option off by setting Auto Run to 'No'). The first thing that occurred was that I got this error message:

Fatal Error: Memory usage limit was exceeded

Apparently the number of iterations in my test loop was too many. Once I dialed that back to 100,000 the code ran fine. This code is pretty basic and not creating a lot of large objects so this limit seems low. Also looks like no GC is running so this limit my hinder other tests.

It does have a 'Share' link that gives you either a direct link to the fiddle or a widget that you can embed directly in a blog post. Here is the widget for this post:


Definitely a nice tool for sharing code but think I will stick with LINQPad for most of my scratchpad needs.

Monday, December 7, 2015

All Your Base Are Belong To Us

I wanted to encode a number in Base 36. A simple enough task, but as these things sometimes do, this took me down the rabbit hole of wanting to create a generic routine. I needed a set of methods, one that would take an integer and convert it to an arbitrary base and another to convert it back to a Base 10 number. There are a bunch of examples floating around the web but I wanted to create my own (combining some of the best elements from the code I found). It's a relatively easy problem to solve but along the way I found some interesting tricks to speed up the process.

So here is my C# take on this old problem:

I used LINQPad to create a quick program to test it out.

Friday, November 20, 2015

N-Gram Extraction

For reporting purposes we do some simple word analysis. I've been looking to expand on that by analyzing the frequency of 2 and 3 word pairs. So I've been evaluating some n-gram extraction algorithms.

Wikipedia defines an n-gram as follows:

In the fields of computational linguistics and probability, an n-gram is a contiguous sequence of n items from a given sequence of text or speech. An n-gram of size 1 is referred to as a "unigram"; size 2 is a "bigram" (or, less commonly, a "digram"); size 3 is a "trigram"

Initially I had been using string.split() to break the text into words and process each one but found the overhead to be too high (lots of string copying). So I changed the approach to loop through each character in the text and build up words. To get the word pairs (or triplets) my first thought was to use Queues. First I had to have a queue that was a fixed size. It needed to drop items from the front when new ones were added to the end. From StackOverflow I found a simple example to do just that:

With that in place I could do something like the following:

That worked but still had some unnecessary overhead with a StringBuilder for each word and having to join the words back together to get the bigram. So I rewrote the code using pointers into the text and copying out the words (or word pairs) as I found them. This approach proved to be the fastest.

I also took one more pass and made the code more generic. Rather than using specific variables for each pairing I used an array to hold on each word location. This code was slower than the previous due to the loops and array access. For looking for larger number of n-grams (say 4+) I think this would be the better code to use.

Monday, July 27, 2015

Now more dynamic than ever

The dynamic keyword was introduced in C# 4 and I remember reading about it back then. Most of the articles (like this one) highlighted using it for late binding of method calls. Useful for calling external libraries in a different language or interfacing with old COM code but not something I would normally need in managed C# land.

Well the other day as I was reading about the Visitor pattern in C# I came across this article (Farewell Visitor) which used dynamic dispatch to simplify the visitor code. Very neat use of dynamic to essentially dynamically cast a variable to the underlying object type before calling a matching overridden method.

To see a quick example of this in action past the following code in LinqPad and check out the results.
void Main() {

 var shapes = new List();
 shapes.Add(new Shape());
 shapes.Add(new Circle());
 shapes.Add(new Square());
 
 // Only the Shape method gets called each time
 foreach (var element in shapes) {
  PrintShape(element);
 }
 
 Console.WriteLine();
 
 // Using dynamic the matching object method gets called
 foreach (dynamic element in shapes) {
  PrintShape(element);
 }
}

public void PrintShape(Shape shape) {
 Console.WriteLine("I am a Shape");
}

public void PrintShape(Circle circle) {
 Console.WriteLine("I am a Circle");
}

public void PrintShape(Square square) {
 Console.WriteLine("I am a Square");
}

// Simple shape and two subclasses
public class Shape {
}

public class Circle : Shape {
}

public class Square : Shape {
}

Monday, November 3, 2014

Creating Word documents with Open XML SDK


Creating a simple Word document and adding content is relatively easy using the Open XML SDK (2.5). Here's a basic Hello World example:

public static void CreateWordDocument(string filename) {
    // Create a document by supplying the filename. 
    using (var wordDocument = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document)) {
        // Add the MainDocumentPart, root Document and the Body.
        var mainPart = wordDocument.AddMainDocumentPart();
        var document = mainPart.Document = new Document();
        var body = document.AppendChild(new Body());

        // Add a Paragraph and a Run with the specified Text
        var para = body.AppendChild(new Paragraph());
        var run = para.AppendChild(new Run());
        run.AppendChild(new Text("Hello World"));
    }
}

That's great for creating a simple document but what about when you want to add some real content and style it. Once you try and do that you quickly learn that what you are creating with the Open XML SDK truly is an empty document. This is not like opening Word and selecting "New Blank document" which has a bunch of preset styles available. To start having your document look like a real Word document (with things like styles and bullet lists) you have to start adding in classes like StyleDefinitionsPart and NumberingDefinitionsPart (and lots of additional stuff). Even when you add in those additional elements it's hard to make a document look as a good as Word out of the box.

An easier solution is to create your own template and use that as the basis for your new document. That way you will get a bunch of stuff already defined. The simplest way to do this is to open Word and create a new blank document and then save this as a Word template (*.dotx). You can also go into Word and customize the styles and add items like a header page and use that in your template. Once you have a template the code to create that basic Hello World example can be altered like so to use it:

public static void CreateFromTemplate(string templateFilename, string documentFilename) {
    // WordprocessingDocument.Create will overwrite an existing file. 
    // If we are using Open we have to delete the file first 
    // if we want to copy that behavior.
    if (File.Exists(documentFilename)) {
        File.Delete(documentFilename);
    }

    // Copy the template to the output file name.
    File.Copy(templateFilename, documentFilename);

    // Now open the copied file
    using (var wordDocument = WordprocessingDocument.Open(documentFilename, true)) {
        // We need to change the file type from template to document.
        wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);

        // MainDocumentPart, root Document and Body already exist just access them
        var mainPart = wordDocument.MainDocumentPart;
        var document = mainPart.Document;
        var body = document.Body;

        // Add a Paragraph and a Run with the specified Text
        var para = body.AppendChild(new Paragraph());
        var run = para.AppendChild(new Run());
        run.AppendChild(new Text("Hello World"));

        document.Save();
    }
}

It's a little more verbose but now you have a document with lots of predefined style ready to add content.

Friday, October 10, 2014

Adding a formatted hyperlink to a Word document using Open XML

I was looking for a way to insert a hyperlink into a Word document I am creating using the Open XML SDK (v2.5). I found a couple of examples on the web and got them to work. The link that was created was clickable but it wasn't styled like a hyperlink. After some trial and error I figured out the issue. Since I was creating the document from scratch it has no styles defined in it. So I created a link in word and copied the hyperlink style.

Here is the example code:

const string outputFilename = @"c:\temp\linked.docx";
						
using (var wordDocument = WordprocessingDocument.Create(outputFilename, WordprocessingDocumentType.Document)) {
	var mainPart = wordDocument.AddMainDocumentPart();

	// Create the document structure and add some text.
	var doc = mainPart.Document = new Document();
	var body = doc.AppendChild(new Body());

	// Start a paragraph with some text
	var para = body.AppendChild(new Paragraph());
	var run = para.AppendChild(new Run());
	run.AppendChild(new Text("This is a formatted hyperlink: ") {
		Space = SpaceProcessingModeValues.Preserve // Need this so the trailing space is preserved.
	});

	// Create a hyperlink relationship. Pass the relationship id to the hyperlink below.
	var rel = wordDocument.MainDocumentPart.AddHyperlinkRelationship(new Uri("http://www.example.com/"), true);
				
	// Append the hyperlink with formatting.
	para.AppendChild(
		new Hyperlink(
			new Run(
				new RunProperties(
					// This should be enough if starting with a template
					new RunStyle { Val = "Hyperlink", }, 
					// Add these settings to style the link yourself
					new Underline { Val = UnderlineValues.Single },
					new Color { ThemeColor = ThemeColorValues.Hyperlink }),
				new Text { Text = "Click Here"}
			)) { History = OnOffValue.FromBoolean(true), Id = rel.Id });

	doc.Save();
}

Thursday, December 5, 2013

Var-ious Thoughts

I started my programming career as a Smalltalker (before Java or C# even existed) and enjoyed the "everything is an object" dynamically-typed variables. In the late 90's, I worked on the VisualAge for Java product (which eventually became the Eclipse platform) using Java. Then I switched jobs and ended up using VB6. It wasn't as bad as I feared because VB6 at least had objects, classes and interfaces (but no inheritance). Still, I was happy when I convinced my bosses that we should switch to C#. It was nice to be back using a fully object-oriented language.

Coming from a Smalltalk background I had been reluctant to embrace a strongly-typed language (let alone strongly-type collections). I found after awhile I liked the some of the benefits like having the compiler catch type exceptions and having the type declaration be a way of self-documenting the code. With the introduction of the var keyword in C# 3.0 I was concerned that we were taking a step back to the VB days. I understood the scenarios with anonymous types they needed to add it for but didn't want to lose documentation benefits. I've come to realize that when you are declaring a variable and then instantiating and assigning an object to it 'var' can save a bunch of typing. Just don't overuse it when the type declaration is not readily apparent (ie don't make me think or have to search to figure out the type).

Here are my general guidelines for using 'var':

  1. Don't use 'var' when the type of variable is not readily apparent.
  2.   var s = SomeMethod();
  3. Use 'var' when declaring a variable and assigning an obvious type to it.
  4.    var collection = new List<string>();
  5. Use 'var' when required to (e.g. with anonymous types).
  6.   var anon = new { Name = "Joe", Age = 34 };

Wednesday, December 4, 2013

Fast XML parsing with XmlReader and LINQ to XML

Using XmlDocuments to parse large XML strings, as we know, can spike memory usage. The entire document is parsed and turned into an in-memory tree of objects. If we want to parse the document using less memory there are a couple of alternatives to using XmlDocuments. We could use an XmlReader but the code can be messy and it’s easy to accidentally read too much (see here). We could use XPath but that’s more designed for searching sections of XML rather than parsing an entire document. Lastly we could use LINQ to XML which offers the simplicity of XmlDocument along with LINQ queries but by default will load the entire document into memory.

This blog post offered an interesting alternative of combining LINQ to XML with XmlReaders. This hybrid approach seemed to offer the speed of forward parsing XmlReaders with the simplicity and functionality of LINQ objects.

The first step was creating a method in an utility class that abstracted out the reader and returns just the matching elements. The secret sauce is the ‘yield return’ keyword which I will explain below.

/// <summary>
/// Given an xml string and target element name return an enumerable for fast lightweight 
/// forward reading through the xml document. 
/// NOTE: This function uses an XmlReader to provide forward access to the xml document. 
/// It is meant for serial single-pass looping over the element collection. Calls to functions 
/// like ToList() will defeat the purpose of this function.
/// </summary>
public static IEnumerable<XElement> StreamElement(string xmlString, string elementName) {
    using (var reader = XmlReader.Create(new StringReader(xmlString))) {
        while (reader.Name == elementName || reader.ReadToFollowing(elementName))
            yield return (XElement)XNode.ReadFrom(reader); 
    }
}
Say you have a large CD catalog to read in like:
<Catalog>
  <CD>
    <Title>Stop Making Sense</Title>
    <Band>Talking Heads</Band>
    <Year>1984</Year>
  </CD>
  ...
</Catalog>
If you were using an XmlDocument to read that from an XML string and process each element you might have code like:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(catalogXml);
XmlNodeList discs = xmlDoc.GetElementsByTagName("CD");
foreach (XmlElement discElement in discs) {
    //... Process each element
}
You can convert that to using the hybrid LINQ/XmlReader approach like the following:
IEnumerable<XElement> discs = from node in XmlUtils.StreamElement(catalogXml, "CD") select node;
foreach (XElement discElement in discs) {
    //... Process each element
}
The one big caveat is that you can’t call any functions on the discs collection that would require looping over all of the items to get the answer (eg ToList(), Count, etc). This is because we are relying on yield to return each element one at a time. We process it and then move on to the next one. This allows memory associated with individual elements to be garbage collected as we go along and not held into memory en masse. This approach works best when we have an XML document with a set of homogenous elements that can be forward processed.

More on yield:
You consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
One thing to stress when making any performance related changes is that you need to establish baseline performance numbers and then verify that the changes improve it. So for each method record the time and memory use before any changes are made and after. You can use something like the following to determine the baseline and any performance gains.
Stopwatch stopWatch = Stopwatch.StartNew();
long startMem = GC.GetTotalMemory(false)

// Code to benchmark

stopWatch.Stop();
long endMem = GC.GetTotalMemory(false);
Console.WriteLine ("{0} ms", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine ("{0} mem", endMem - startMem);

Friday, November 22, 2013

User-Freindly URLs for HttpHandlers

I was interested in implemented a cleaner URL scheme for an HttpHandler in ASP.NET. Out of the box it's pretty easy to set up an HttpHandler. Simply add a file with an ".ashx" extension and the @WebHandler directive and IIS will use the the Generic Web Handler to route traffic to your handler. The downside is that the handler has to end with ".ashx" and all parameters have to go on the querystring.

With the introduction of MVC, Microsoft built RESTful style routing functionality. I had read that with ASP.NET 4.0 they exposed this functionality so it could be used outside of MVC. I found a number of articles (here and here) on how I could set up custom routes to my handler. As I tried to follow the examples in the articles they all had more complexity than I needed to get going. I was eventually able to get it working but wished for a simpler example.

So I created a stripped down example. In the example below you access the site like http://example.com/quote/MSFT. URLs with /quote are routed to the handler and the next item in the URL is used as a parameter.
  1. Create a new 4.0 (or higher) empty ASP.NET website.
  2. Add an App_Code directory and custom HttpHandler like the following:
    /// 
    /// HTTP Handler to return raw HTML.
    /// 
    public class CustomHttpHandler : IHttpHandler {
    
      // This holds the additional parameters from the URL.
      public RouteData RouteData { get; set; }
    
      public void ProcessRequest(HttpContext context) {
        string symbol = RouteData.Values["symbol"] as string;
        context.Response.ContentType = "text/html";
        context.Response.Write("Stock symbol is " + symbol);
      }
    
      public bool IsReusable {
        get { return false; }
      }
    }
  3. Add the Global.asax file and in Application_Start add a route to the RouteTable. This takes an instance of a class that implements IRouteHandler.
     void Application_Start(object sender, EventArgs e) {
      RouteTable.Routes.Add("quote", new Route("quote/{symbol}", new CustomRouteHandler()));
      }
    
  4. Add the route handler class that implements IRouteHandler. This must return an instance of the HttpHandler you want the URL directed to.
    public class CustomRouteHandler : IRouteHandler {
      public CustomRouteHandler() {
      }
    
      public IHttpHandler GetHttpHandler(RequestContext requestContext) {
        var handler = new CustomHttpHandler();
        handler.RouteData = requestContext.RouteData; // Include the reference to the RouteData
        return handler;
      }
    }
    

Wednesday, February 13, 2013

Virtual Static


In Smalltalk a Class is a first level object just like everything else in the system. Objects get instantiated using the Class as a template but the Class itself can have its own properties and methods. In fact constructors are just class methods in Smalltalk that return an instance.

Now as a C# programmer I've always thought of static properties and methods as the same thing as Smalltalk's class properties and methods. In the back of my head I knew that C# didn't have first-level Class objects but the static paradigm seemed to fit. So when the other day I wanted to override a static method in a subclass I figured no problem just mark the one in the superclass 'virtual' and then add my new implementation. One problem was that compiler balked at 'virtual static'.

After some searching around I found this blog post explaining why this was not a valid combination of keywords. As Eric Libbert writes:
Related questions come up frequently, in various forms. Usually people phrase it by asking me why C# does not support “virtual static” methods. I am always at a loss to understand what they could possibly mean, since “virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”.
Turns out 'static' is really not equal to 'class'. I must admit I almost shed a tear that day as this sunk in.

Monday, October 1, 2012

Simple Mechanical Turk example using C#


I started looking at the AWS API and specifically the Mechanical Turk Requester API the other day. After reading the overview and understanding the basics I wanted to test making a simple call to get a feel for it. I set up an account and got my access credentials (getting credentials is a whole other story as it involves two different websites and seems overly complicated but it's done for now). I figured the GetAccountBalance operation seemed like the best first option as I didn't want to create a HIT (Human Intelligence Task - their term for tasks you can create) and manage that. Since I hadn't added any money it should be easy for them to return a zero to me.
The web services are REST based and calling them seems pretty straightforward. You figure out the operation you want to perform, set some querystring parameters and make a web request. The complicated bit is calculating the signature (a SHA1 hash of the operation, service and current time using your secret access id as the key). Amazon doesn't have a nice simple example of constructing this in C# and even the other language examples don't look simple. There is a SDK for .NET it looks like it does a good job wrapping the Amazon endpoints but I wanted to figure out the basics for myself. So by starting with the examples from the SDK I was able to simplify the code down to the following:
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace TurkTest {
 class Program {

  static void Main(string[] args) {
   const string SERVICE_NAME = "AWSMechanicalTurkRequester";  // requester service for MTurk
   const string TIMESTAMP_FORMAT = "yyyy-MM-ddTHH:mm:ss.fffZ";

   // Modify these with your values.
   const string operation = "GetAccountBalance";
   const string accessKey = "[Your access key]";
   const string secretAccessKey = "[Your secret access key]";

   // Millisecond values in the timestamp string can result in intermittent BadClaimsSupplied errors.
   // Get the current UTC time and use that to create a new time with milliseconds set to zero to avoid this case.
   DateTime now = DateTime.UtcNow;
   now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, DateTimeKind.Utc);
   string timeStamp = now.ToString(TIMESTAMP_FORMAT, CultureInfo.InvariantCulture);

   // Create the hash-based messaged authentication algorithm (SHA1) using our secret access key as the key.
   var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secretAccessKey));

   // Combine the service name, operation and timestamp and then hash them to produce the signature.
   var dataBytes = Encoding.UTF8.GetBytes(SERVICE_NAME + operation + timeStamp);
   string signature = Convert.ToBase64String(hmac.ComputeHash(dataBytes));

   // Build the URL to send to Amazon
   string url =
    @"https://mechanicalturk.amazonaws.com/?Service=AWSMechanicalTurkRequester&AWSAccessKeyId={0}&Version=2012-03-25&Operation={1}&Signature={2}&Timestamp={3}";
   url = string.Format(url, accessKey, operation, signature, timeStamp);

   // Send the request and write the respose to the console
   using (WebClient client = new WebClient()) {
    using (StreamReader reader = new StreamReader(client.OpenRead(url))) {
     Console.WriteLine(reader.ReadToEnd());
    }
   }

   Console.Read();
  }
 }
}
After a couple of false starts I was able to get it to return my zero balance. Hope this helps the next person get started.

Sunday, September 30, 2012

Is If Condition

Awhile back I wrote about some general rules I had for writing if conditions. So I found it amusing the other day to read a blog post on Coding Horror about new programming jargon and see the following:

Yoda Conditions

Yoda-conditions

Using if(constant == variable) instead of if(variable == constant), like if(4 == foo). Because it's like saying "if blue is the sky" or "if tall is the man".
I will have to add that to my guidelines.

Thursday, August 16, 2012

Return of the Extension Method

Recently a small team of us branched the code to start work on a new feature for a future release while work continued in the mainline for the current upcoming release. As I was working on our new feature I realized that I wanted to extend some common core classes with new functionality. The classes have their own hierarchy tree and normally I would have created a base method for the shared functionality and overridden it for some of the subclasses. However, since I knew that other developers were working on these same classes I looked for ways that I could minimize merging code later. I've written before about extension methods (here and here) and thought this might be a good time to use them.

I quickly ran into an issue where extension methods only work with the same class that the object is cast to. Say for example you have a Shape superclass and Circle subclass. Normally we would pass around Circle objects as Shapes and rely on virtual or abstract methods to provide a common interface. With extension methods there is no inheritance so you have to either explicitly cast our objects or do some type of switching in a common method.

I've created a simple program in LINQPad to demonstrate this behavior:

void Main() {
    // Create a new Circle but cast it as a Shape
    Shape obj = new Circle();
    // Call the virtual method
    Console.WriteLine(obj.WhoAmI());
    // Call the extension method
    Console.WriteLine(obj.WhoAmIEx());
}

public class Shape {
    public virtual string WhoAmI() {
        return "Virtual Shape";
    }
}
public class Circle : Shape {
    public override string WhoAmI() {
        return "Overriden Circle";
    }
}

public static class Extensions {
    public static string WhoAmIEx(this Shape obj) {
        return "Shape Extension";
    }
    public static string WhoAmIEx(this Circle obj) {
        return "Circle Extension";
    }
}

Running this produces:
 Overriden Circle
Shape Extension

Took me a little while to figure out this behavior (although I should have realized it from the start). I still ended up using an extension method to add one new call but after we merge the code I think I will change that back to a virtual method.

Wednesday, May 16, 2012

Fluent Smalltalk

The other week I wrote about creating HTML controls in ASP.NET MVC using the Fluent Interface pattern. I haven't been a Smalltalker since the 90s so it took awhile for it click where I had seen this pattern before. In Smalltalk the default return value from a message send (aka method) is the receiver (aka the object itself or 'self'). You are encouraged by the language to create readable chains of method sends.

I also had a thought about how the C# compiler could support this as a language level feature by allowing the 'this' keyword as the return type for a method.

So instead of having to write a method like:
public Image ImagePath(string path) {
  imagePath = path;
  return this;
}
You could just write:
public this ImagePath(string path) {
  imagePath = path;
}