Saturday, March 15, 2008

LINQ to String

LinqInAction

I'm currently reading the excellent Linq in Action by Marguerie, Eichert and Wooley. It's great exposition of all things Linq and there are lots really well explained examples. Something which tickled me, which I hadn't realized before is that you can use Linq over strings. Well of course, since System.String implements IEnumerable<T>. It gives you some interesting alternatives to standard string functions:

string text = "The quick brown fox jumped over the lazy dog.";

// substring
text.Skip(4).Take(5).Write();   // "quick"

// remove characters
text.Where(c => char.IsLetter(c)).Write(); // "Thequickbrownfoxjumpedoverthelazydog."

string map = "abcdefg";

// strip out only the characters in map
text.Join(map, c1 => c1, c2 => c2, (c1, c2) => c1).Write(); // "ecbfedeeadg"

// does text contain q?
text.Contains('q').Write(); // true

The 'Write()' at the end of each expression is just an extension method on IEnumerable<T> that writes to the console.

OK, so most of these aren't that useful and there are built in string functions to do most of these (except the mapping I think). The cool thing is that you can write a little function, called 'Chars' in my example, that exposes a file stream as IEnumerable<T>. This means you can do the same tricks on a file and since we're just building up a decorator chain of enumerators the entire file isn't loaded into memory, only one character at a time. In this example, showing the 'substring' again, the file will stop being read after the first nine characters.

string text = "The quick brown fox jumped over the lazy dog.";
string myDocuments = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string path = Path.Combine(myDocuments, "someText.txt");

File.WriteAllText(path, text);

using (StreamReader reader = File.OpenText(path))
{
    reader.Chars().Skip(4).Take(5).Write();
}

Here's the code for the 'Chars' function.

public static class StreamExtensions
{
    public static IEnumerable<char> Chars(this StreamReader reader)
    {
        if (reader == null) throw new ArgumentNullException("reader");

        char[] buffer = new char[1];
        while(reader.Read(buffer, 0, 1) > 0)
        {
            yield return buffer[0];
        }
    }
}

In the book the authors show a similar function that reads a file line by line and they use it to enumerate over a csv file. The resulting syntax is extremely neat, but I'll let you buy the book and see it for yourself:)

Thursday, March 13, 2008

Currying in C# with Oliver Sturm

I really enjoyed last night's talk at the London DNUG by Oliver Sturm titled 'Functional programming with C#'. I had a genuine 'I did not know you could do that' moment when he showed us how to do Currying in C#. Of course there was much more to the talk than that, including lambda expressions, closures and map-filter-reduce, but they were less of a surprise. Still an excellent explanation of all things functional.

So, what's currying? Well it's got nothing to do with vindaloo, it's a really simple idea which basically says that if you give a function less arguments than it expects you get back another function that only expects the missing arguments. Now, of course if you give a function in C# less arguments than it expects you get a compilation error. What Oliver showed us was that its trivially easy to write a 'Curry' function that will return any function you give it in a curried version. You can curry to your hearts content.

OK, so lambda expressions give us this great syntax for creating anonymous delegates, or little functions you can assign to a variable. Here's a trivial example; add:

Func<int, int, int> add = (x, y) => x + y;
int a = add(2, 3);  // a = 5

You use the add function like any other. Here we're adding 2 and 3 and returning 5. Now we can also use the lambda syntax to build an add function that within it returns a function that's just waiting for the other side of the add expression. OK, that's gobbledygook, it's easier to show than explain:

Func<int, Func<int, int>> curriedAdd = x => y => x + y;
int b = curriedAdd(2)(3); // b = 5

The result is the same, it's just that the syntax looks unfamiliar. Now we can curry our curriedAdd by just supplying one argument and then use our new add5 function as many times as we want:

var add5 = curriedAdd(5);

int c = add5(3); // c = 8
int d = add5(5); // d = 10

But you don't have to explicitly define your curried function when you've got a 'Curry' function that will create it for you. Here's another stupidly trivial example: We've got a function called addFourThings, we pass it into our Curry function and out pops curriedAddFourThings. We can use that to simply add four numbers, or we can progressively assign the arguments one at a time.

Func<int, int, int, int, int> addFourThings = (a, b, c, d) => a + b + c + d;

var curriedAddFourThings = Curry(addFourThings);

int result = curriedAddFourThings(1)(2)(3)(4);  // result = 10

var addOne = curriedAddFourThings(1);
var addOneAndTwo = addOne(2);
var addOneAndTwoAndThree = addOneAndTwo(3);

int result2 = addOneAndTwoAndThree(4); // result2 = 10

Here is Oliver's set of Curry function overloads.

public Func<T1, Func<T2, T3>> Curry<T1, T2, T3>(Func<T1, T2, T3> function)
{
    return a => b => function(a, b);
}

public Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> function)
{
    return a => b => c => function(a, b, c);
}

public Func<T1, Func<T2, Func<T3, Func<T4, T5>>>> Curry<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5> function)
{
    return a => b => c => d => function(a, b, c, d);
}

Pretty simple eh. This is all very neat, and I can imagine how it could be very useful in factoring algorithms. Oliver showed us an example in his talk. But I think I'm going to need to see a few more cases of it being used in real world situations and maybe try it out a few times before it becomes a natural part of my programming toolkit.

Windsor IoC Container and MVC Framework CTP 2

I spent all morning upgrading my current MVC project to use the MVC Framework CTP 2. It went mostly OK. There are a few funnies, like the way the arguments to Html.Form() extension method's parameters have been reversed and the changes to Html.ActionLink, but generally speaking it was pretty smooth. All the stuff that was in the MvcToolkit is now in the System.Web.Mvc assembly, so I was able to remove that reference from my project. MvcContrib has been updated for CTP 2, but the source is in a branch, so you shouldn't just get the latest trunk like I did initially (Duh!) Go here instead: http://mvccontrib.googlecode.com/svn/branches/MVCPreview2/. I checked it out and it built no problem. Then it was a simple case of dropping in the new assemblies.

I'm using Castle Windsor in my MVC project which means I use the WindsorControllerFactory from MvcContrib rather than the default controller factory. One of the things that has changed is the signature of the IControllerFactory's CreateController method, it now takes a string of the controller name rather than its type. I can see why this makes more sense because your controller factory might not have the same idea about the type it wants to supply as the routing framework. This means that we have to use the string ID of the controller that's registered with windsor rather than it's type. I had to make a small change in the code of the WindsorControllerFactory to fix a casing bug (URLs aren't case sensitive, but the windsor service ids are):

public IController CreateController(RequestContext context, string controllerName)
{
 //Hack...
 controllerName = controllerName.ToLower() + "controller"; 

 IWindsorContainer container = GetContainer(context);
 return (IController)container.Resolve(controllerName);
}

That means you also have to register the controllers with lower case names. Here's my InitializeWindsor method in my global.asax file:

protected virtual void InitializeWindsor()
{
    if (container == null)
    {
        // create a new Windsor Container
        container = new WindsorContainer(new XmlInterpreter("Configuration\\Windsor.config"));

        // automatically register controllers
        Assembly.GetExecutingAssembly().GetExportedTypes()
            .Where(type => IsController(type))
            .Each(type => container.AddComponentWithLifestyle(
                type.Name.ToLower(), 
                type, 
                Castle.Core.LifestyleType.Transient));

        // set the controller factory to the Windsor controller factory (in MVC Contrib)
        ControllerBuilder.Current.SetControllerFactory(typeof(WindsorControllerFactory));
    }
}

private bool IsController(Type type)
{
    return typeof(IController).IsAssignableFrom(type);
}

The .Each extension method is a little addition to Linq that a lot of people have blogged about, including me in this post.

Update

Jeremy Skinner, who's responsible for the WindsorControllerFactory has updated it in MvcContrib. He's also added some extension methods for the windsor container to register controllers, so now my InitializeWindsor method looks like this:

protected virtual void InitializeWindsor()
{
    if (container == null)
    {
        // create a new Windsor Container
        container = new WindsorContainer(new XmlInterpreter("Configuration\\Windsor.config"));

        // automatically register controllers
        container.RegisterControllers(Assembly.GetExecutingAssembly());

        // set the controller factory to the Windsor controller factory (in MVC Contrib)
        ControllerBuilder.Current.SetControllerFactory(typeof(WindsorControllerFactory));
    }
}

Thursday, March 06, 2008

Forms Authentication with the MVC Framework

I'm just wrapping up writing my first commercial application with the new MVC Framework. Because it sits on top of ASP.NET, simply replacing the Web Forms model, you can use all of the ASP.NET infrastructure. This includes Forms Authentication. I want to show how I used Forms Authentication with my own database rather than using the membership API, but you can plug in membership quite easily too.

The first thing you need to do is set up your Web.config file to use Forms authentication:

<!--Using forms authentication-->
<authentication mode="Forms">
  <forms loginUrl="/login.mvc/index" defaultUrl="/home.mvc/index" />
</authentication>

Just set mode to Forms and the login URL to your login page. This means that any unauthenticated users are redirected to the login page. I've also set the default URL to my home page. The other change you'll need to make to your web.config file is to allow unauthenticated users to see your login page and any CSS and image files (although this depends on how you configure IIS). If you've got public areas of your web site you will need to add these as well.

  <!-- we don't want to stop anyone seeing the css and images -->
  <location path="Content">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <!-- allow any user to see the login controller -->
  <location path="login.mvc">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

Next we need to set up the login controller. Since I'm using my own data access I need to pass in my user repository; that's the class that wraps my user data access.

public class LoginController : Controller
{
    readonly IUserRepository userRepository;

    public LoginController(IUserRepository userRepository)
    {
        this.userRepository = userRepository;
    }
}

We need a controller action method to render the login form. I've called mine Index. The LoginViewData simply allows me to include an error message, we'll see how that works later on.

[ControllerAction]
public void Index()
{
    RenderView("index", new LoginViewData());
}

Next we need to create the view for the login form. I've just rendered a simple form.

<%= Html.ErrorBox(ViewData.ErrorMessage) %>

<% using(Html.Form("Authenticate", "Login")) { %>
<div id="login_form">

    <p>Enter your details</p>
    
    <label for="username">User name</label>
    <%= Html.TextBox("username") %>
    
    <label for="password">Password</label>
    <%= Html.Password("password") %>

    <%= Html.SubmitButton() %>
</div>
<% } %>

Note that the form posts to the Authenticate action. This action is where we do all the work of checking the user's credentials and logging them in.

[ControllerAction]
public void Authenticate(string username, string password)
{
    User user = userRepository.GetUserByName(username);

    if (user != null && user.Password == password)
    {
        SetAuthenticationCookie(username);
        RedirectToAction("Index", "Home");
    }
    else
    {
        // If we got here then something is wrong with the supplied username/password
        RenderView("Index", new LoginViewData
            {
                ErrorMessage = "Invalid User Name or Password."
            });
    }
}

public virtual void SetAuthenticationCookie(string username)
{
    FormsAuthentication.SetAuthCookie(username, false);
}

Yes, I know, it's very naughty storing passwords unencrypted in the database, but I wanted to keep this demonstration simple. That's my excuse anyway :) You can see that we simply get the user with the given username from the database (my user repository) , make sure the passwords match and call the public virtual method SetAuthenticationCookie which calls the forms authentication API's SetAuthCookie method. This effectively logs the user in. Why is SetAuthenticationCookie a separate method, why not just call SetAuthCookie in the Authenticate action? This is so that we can unit test the Login controller without invoking the forms authentication API. We can create a partial mock of the Login controller and set up an expectation for SetAuthenticationCookie because it's marked public and virtual.

This is all you need to do to make forms authentication work with the MVC Framework. However, there was one additional thing I wanted to achieve. I have my own User class that implements IPrinciple:

public partial class User : IPrincipal
{
    public static User Guest
    {
        get
        {
            return new User() { Username = "Guest", Role = Role.Guest };
        }
    }

    #region IPrincipal Members

    public IIdentity Identity
    {
        get 
        {
            bool isAuthenticated = !(Role.Name == Role.Guest.Name);
            return new Identity(isAuthenticated, this.Username);
        }
    }

    public bool IsInRole(string role)
    {
        return this.Role.Name == role;
    }

    #endregion
}

This User class was generated by the LINQ to SQL designer and the above code is simply a partial extension of it. My data model also includes Roles so I can supply an implementation of IsInRole method. The identity property is handled by returning a simple implementation of IIdentity. To be able to make use of my IPrinciple implementation I need to supply my User to the HttpContext on each request and the best way of doing this is to handle the OnAuthenticateRequest event in Global.asax.

protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
{
    if (Context.User != null)
    {
        if (Context.User.Identity.IsAuthenticated)
        {
            User user = userRepository.GetUserByName(Context.User.Identity.Name);

            if (user == null)
            {
                throw new ApplicationException("Context.User.Identity.Name is not a recognised user.");
            }

            System.Threading.Thread.CurrentPrincipal = Context.User = user;
            return;
        }
    }
    System.Threading.Thread.CurrentPrincipal = Context.User = CreateGuestUser();
}

We get HttpContext's user, check if it's been authenticated. If it has, it means this user has already logged in and is one of the users in our database. We retrieve the user from our user repository and set the HttpContext's User to our user. We also set the current thread's currentPrinciple to our user. If the user is not authenticated we create a guest user and use that instead.

Now that the current thread's currentPrinciple is one of our users, we can do role based checks on any bit of code we want. Here, for example we're making sure that only administrators can execute this DeleteSomethingImportant action:

[ControllerAction]
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public void DeleteSomethingImportant(int id)
{
 ....
}

You can access the current user at any time in the application simply by casting the HttpContext's User to your User. This makes role based menu's or features trivial to write.

Update

I had a question recently (hi Jasper) about the Identity class returned by the Identity property of my User class. This is a simple implementation of the System.Security.Principle.IIdentity interface that just returns the Username of my User class. Here it is in full:

public class Identity : IIdentity
{
    bool isAuthenticated;
    string name;

    public Identity(bool isAuthenticated, string name)
    {
        this.isAuthenticated = isAuthenticated;
        this.name = name;
    }

    #region IIdentity Members

    public string AuthenticationType
    {
        get { return "Forms"; }
    }

    public bool IsAuthenticated
    {
        get { return isAuthenticated; }
    }

    public string Name
    {
        get { return name; }
    }

    #endregion
}

Hopefully this makes things a little clearer.

Monday, March 03, 2008

How to output Windsor Container's dependency graph

I was asked about this today (hi Sham!). It turns out to be very easy since the Windsor Container exposes it's dependency graph via it's GraphNodes collection. Here's a little console application that'll output the dependency graph of any application. You simply give it the path of the Windsor configuration file and the path of your application's bin folder.

Here's the output from a sample run:

C:\>Suteki.DependencyViewer
"C:\source\Suteki\Suteki.SomeApplication\Configuration\Windsor.config"
"C:\source\Suteki\Suteki.SomeApplication\bin"

Suteki.SomeApplication.Controllers.StatusController
        Suteki.SomeApplication.Repositories.UserRepository
                Suteki.SomeApplication.SomeApplicationDataContext
        Suteki.SomeApplication.Repositories.InstructionRepository
                Suteki.SomeApplication.SomeApplicationDataContext
        Suteki.SomeApplication.Repositories.Repository`1
                Suteki.SomeApplication.SomeApplicationDataContext
        Suteki.SomeApplication.Repositories.Repository`1
                Suteki.SomeApplication.SomeApplicationDataContext
        Suteki.SomeApplication.Services.MatterSubmissionService
                Suteki.SomeApplication.MatterServiceProxy.MatterServiceClient
                Suteki.SomeApplication.Services.DocumentUploadServiceProxy
                Suteki.SomeApplication.Services.InstructionPdfService
                        Suteki.SomeApplication.Service.Model.Services.DocumentService
                                Suteki.SomeApplication.Service.Model.Services.DateService
        Suteki.SomeApplication.Services.EmailToFileSender
        Suteki.SomeApplication.Services.EmailTemplateService

And here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
using Castle.Core;
using System.Reflection;
using System.IO;

namespace Suteki.DependencyViewer
{
    public class Program
    {
        private Dictionary<string, Assembly> assemblyList;

        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("usage: Suteki.DependencyViewer <config file> <bin directory>");
                return;
            }

            Program program = new Program();
            program.Execute(args[0], args[1]);
        }

        private void Execute(string configPath, string binPath)
        {
            if (!File.Exists(configPath))
            {
                Console.WriteLine("The config file at '{0}' does not exist");
            }
            if (!Directory.Exists(binPath))
            {
                Console.WriteLine("The bin directory at '{0}' does not exist");
            }

            LoadDlls(binPath);

            WindsorContainer container = new WindsorContainer(configPath);

            GraphNode[] graphNodes = container.Kernel.GraphNodes;

            foreach (GraphNode graphNode in graphNodes)
            {
                if (graphNode.Dependers.Length == 0)
                {
                    Console.WriteLine();
                    WalkGraph(graphNode, 0);
                }
            }
        }

        private void WalkGraph(IVertex node, int level)
        {
            ComponentModel componentModel = node as ComponentModel;
            if (componentModel != null)
            {
                Console.WriteLine("{0}{1}", new string('\t', level), componentModel.Implementation.FullName);
            }

            foreach (IVertex childNode in node.Adjacencies)
            {
                WalkGraph(childNode, level + 1);
            }
        }

        private void LoadDlls(string binPath)
        {
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            string[] dlls = System.IO.Directory.GetFiles(binPath, "*.dll");
            assemblyList = new Dictionary<string, Assembly>(dlls.Length);

            foreach (String fileName in dlls)
            {
                Assembly asm = System.Reflection.Assembly.LoadFrom(fileName);
                assemblyList.Add(asm.FullName.Split(',')[0], asm);
            }
        }

        Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            return assemblyList[args.Name];
        }
    }
}

Wednesday, February 27, 2008

Nasty IE margin inheritance bug

I've recently been caught out by a nasty IE bug. The symptom is form elements that have strangely large left margins that are not defined in your style sheet:

ie-margin-bug

Luckily it's quite a well known bug and once I stumbled upon the correct keywords to google (margin inheritance bug) there's plenty of advice out there on how to fix it. I found this blog post very useful, it's a shame the guy's stopped blogging there's some great stuff there; I love this pie chart. For me, it was a simple case of getting rid of my form div's margin-left property. Since my left menu floats left anyway the form will sit nicely to the right without the margin. The form elements inherit the margin of their container, so getting rid of it removes the problem.

Monday, February 11, 2008

Extension method validators

I'm building an MVC Framework application at the moment and I wanted a simple, easy to grep way of validating fields passed back from forms. In MVC-land all the form variables are passed as parameters to the action method. Extension methods turned out to be a very neat solution for doing validation and data conversion. Here's an example:

[ControllerAction]
public void UpdateContact(
    int contactId,
    string name,
    string address1,
    string address2,
    string address3,
    string county,
    string postcode,
    string telephone,
    string email)
{
    try
    {
        name.Label("Name").IsRequired();
        address1.Label("Address 1").IsRequired();
        county.Label("County").IsRequired();
        postcode.Label("Postcode").IsRequired().IsPostcode();
        telephone.Label("Telephone").IsRequired().IsTelephoneNumber();
        email.Label("Email").IsRequired().IsEmail();
    }
    catch (ValidationException exception)
    {
        ContactViewData viewData = ContactViewData(contactId);
        viewData.ErrorMessage = exception.Message;
        RenderView("Contact", viewData);
        return;
    }

 // update the contact and render the view
}

As you can see we pass the contact's details from a form. In the try block the extension method validators are called. Any of them can raise a validation exception which is caught by the catch block and a view is rendered showing the validation error.

The 'Label' extension returns a ValidateField instance that can be consumed by any other validator, this is so that we can raise exceptions that can be displayed directly to the user:

public static ValidateField Label(this string value, string label)
{
    return new ValidateField { Value = value, Label = label };
}

The 'IsRequired' extension takes a ValidateField and checks that the value is not null or empty:

public static ValidateField IsRequired(this ValidateField validateField)
{
    if (string.IsNullOrEmpty(validateField.Value))
    {
        throw new ValidationException(string.Format("{0} is required", validateField.Label));
    }
    return validateField;
}

And finally the 'IsEmail' extension uses a Regex to validate the string value:

public static ValidateField IsEmail(this ValidateField validateField)
{
    // ignore is null or empty, use IsRequired in parrallel to check this if needed
    if (string.IsNullOrEmpty(validateField.Value)) return validateField;

    string patternLenient = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
    if (!Regex.Match(validateField.Value, patternLenient).Success)
    {
        throw new ValidationException(string.Format("{0} must be a valid email address", validateField.Label));
    }
    return validateField;
}

I'm finding extension methods a real boon for writing DSL-ish APIs. I'll leave the 'IsTelephone' and 'IsPostcode' exercises for your enjoyment :)

Wednesday, February 06, 2008

RESTful file uploads with HttpWebRequest and IHttpHandler

I've currently got a requirement to transfer files over a web service. I would normally have used MTOM, but after reading Richardson & Ruby's excellent RESTful Web Services and especially their description of the Amazon S3 service, I decided to see how easy it would be to write a simple file upload service using a custom HttpHandler on the server and a raw HttpWebRequest on the client. It turned out to be extremely simple.

First implement your custom HttpHandler:

public class FileUploadHandler : IHttpHandler
{
    const string documentDirectory = @"C:\UploadedDocuments";

    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string filePath = Path.Combine(documentDirectory, "UploadedFile.pdf");
        SaveRequestBodyAsFile(context.Request, filePath);
        context.Response.Write("Document uploaded!");
    }

    private static void SaveRequestBodyAsFile(HttpRequest request, string filePath)
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Create, FileAccess.Write))
        using (Stream requestStream = request.InputStream)
        {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int byteCount = 0;
            while ((byteCount = requestStream.Read(buffer, 0, bufferSize)) > 0)
            {
                fileStream.Write(buffer, 0, byteCount);
            }
        }
    }
}

As you can see, it's simply a question of implementing IHttpHandler. The guts of the operation is in the ProcessRequest message, and all we do is save the input stream straight to disk. The SaveRequestBodyAsFile method just does a standard stream-to-stream read/write.

To get your handler to actual handle a request, you have to configure it in the handers section of the Web.config file, for examle:

<httpHandlers>
 <add verb="*" path="DocumentUploadService.upl" validate="false" type="TestUploadService.FileUploadHandler, TestUploadService"/>
</httpHandlers>

Here I've configured every request for 'DocumentUploadService.upl' to be handled by the FileUploadHandler. There are a couple of more things to do, first, if you don't want to configure IIS to ignore requests for non-existent resources you can put an empty file called 'DocumentUploadService.upl' in the root of your web site. You also need to configure IIS so that requests for .upl files (or whatever extension you choose) are routed to the ASP.NET engine. I usually just copy the settings for .aspx files.

On the client side you can execute a raw HTTP request by using the HttpWebRequest class. Here's my client code:

public void DocumentUploadSpike()
{
    string filePath = @"C:\Users\mike\Documents\somebig.pdf";

    string url = "http://localhost:51249/DocumentUploadService.upl";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Accept = "text/xml";
    request.Method = "PUT";

    using(FileStream fileStream = File.OpenRead(filePath))
    using (Stream requestStream = request.GetRequestStream())
    {
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int byteCount = 0;
        while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
        {
            requestStream.Write(buffer, 0, byteCount);
        }
    }

    string result;

    using (WebResponse response = request.GetResponse())
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }

    Console.WriteLine(result);
}

Here too we simply stream a file straight into the request stream and then call GetResponse on the HttpWebRequest. The last bit just writes the response text to the console. Note that I'm using the HTTP method PUT rather than POST, that's because we're effectively adding a resource. The resource location I'm adding should be part of the URL. For example, rather than:

http://localhost:51249/DocumentUploadService.upl

it should really look more like:

http://localhost:51249/mikehadlow/documents/2345

Indicating that user mikehadlow is saving a file to location 2345. To make it work would simply be a case of implementing some kind of routing (the MVC Framework would be ideal for this).

Sunday, February 03, 2008

Never write a for loop again! Fun with Linq style extension methods.

One of the things I like about Ruby is the range operator. In most C style languages in order to create a list of  numbers you would usually use a for loop like this:

List<int> numbers = new List<int>();
for (int i = 0; i < 10; i++)
{
    numbers.Add(i);
}
int[] myArray = numbers.ToArray();

But in Ruby you just write this:

myArray = o..9.to_a

But now with extension methods and custom iterators we can do the same thing in C#. Here's a little extension method 'To':

public static IEnumerable<int> To(this int initialValue, int maxValue)
{
    for (int i = initialValue; i <= maxValue; i++)
    {
        yield return i;
    }
}

You can use it like this:

1.To(10).WriteAll();

1 2 3 4 5 6 7 8 9 10

Note the WriteAll() method, that's an extension method too, it simply writes each item in the list to the console:

public static void WriteAll<T>(this IEnumerable<T> values)
{
    foreach (T value in values)
    {
        Console.Write("{0} ", value);
    }
    Console.WriteLine();
}

You can mix your custom extension methods with the built in Linq methods, let's count up to fifty in steps of ten:

1.To(5).Select(i => i * 10).WriteAll();

10 20 30 40 50

Or maybe just output some even numbers:

1.To(20).Where(i => i % 2 == 0).WriteAll();

2 4 6 8 10 12 14 16 18 20

Here's another extension method 'Each', it just applies a Lambda expression to each value:

public delegate void Func<T>(T value);

public static void Each<T>(this IEnumerable<T> values, Func<T> function)
{
    foreach (T value in values)
    {
        function(value);
    }
}

Let's use it to output a ten by ten square of zero to ninety nine:

0.To(9).Each(i => 0.To(9).Select(j => (i * 10) + j).WriteAll());

0 1 2 3 4 5 6 7 8 9 
10 11 12 13 14 15 16 17 18 19 
20 21 22 23 24 25 26 27 28 29 
30 31 32 33 34 35 36 37 38 39 
40 41 42 43 44 45 46 47 48 49 
50 51 52 53 54 55 56 57 58 59 
60 61 62 63 64 65 66 67 68 69 
70 71 72 73 74 75 76 77 78 79 
80 81 82 83 84 85 86 87 88 89 
90 91 92 93 94 95 96 97 98 99 

Now here's something really cool, and more than a little dangerous. Because chaining extension methods of IEnumerable<T> means that you're effectively building a decorator chain of enumerators, you don't actually execute every iteration unless you ask for it. This means we can write infinite loop generators and then bound them by only asking for some members. Best to demonstrate. Here's a method that returns an infinite number of integers (not really, it'll end with an exception at int.MaxValue):

public static IEnumerable<int> Integers
{
    get
    {
        int i = 0;
        while (true)
        {
            yield return i++;
        }
    }
}

We can use it with the built in Linq method 'Take'. For example here we are printing out zero to nine:

Numbers.Integers.Take(10).WriteAll();

0 1 2 3 4 5 6 7 8 9

And here is Five to Fifteen:

Numbers.Integers.Skip(5).Take(11).WriteAll();

5 6 7 8 9 10 11 12 13 14 15

Why is it dangerous? If you put any operation in the chain that simply iterates all the values you'll get an infinite loop. So you couldn't say:

Numbers.Integers.Reverse.Take(10).WriteAll();

Let's wrap up with an infinite Fibonacci series:

public static IEnumerable<int> Fibonacci
{
    get
    {
        int a = 0;
        int b = 1;
        int t = 0;

        yield return a;
        yield return b;

        while (true)
        {
            yield return t = a + b;
            a = b;
            b = t;
        }
    }
}

And use it to print out the first ten Fibonacci numbers:

Numbers.Fibonacci.Take(10).WriteAll();

0 1 1 2 3 5 8 13 21 34

I'm really enjoying learning the possibilities of Linq style extension methods. It makes C# feel much more like a functional language and let's you write in a nicer declarative style. If I've tickled your interest, check out Wes Dyer's blog. Here he writes an ASCII art program using Linq. Nice!

Saturday, February 02, 2008

ALT.NET UK

02022008625

I just got back to Brighton after spending last night and all of today at the ALT.NET UK open spaces conference. It was inspired by the US ALT.NET conference that took place last summer and ably organized by Ian Cooper, Alan Dean and Ben Hall.  I was more than slightly suspicious about the idea of a load of programming geeks turning up with no agenda and just seeing what happened. I did come away thinking that this kind of event is no substitute for something with prepared speakers, but it was great; I really enjoyed myself. Without dressing it up in 'open spaces' language, it was a fantastic opportunity to get together with like minded uber-keen developers and chew the cud.

The night before we all put our suggestions for topics on the white board wall (see the photo above) and then retired to the pub. Ian, Alan and Ben organized them into topics the next morning. To kick off the day in one room, I'd suggested the topic of IoC containers after my talk at DDD. I briefly introduced the subject by describing how I'd come to the IoC game via TTD and Dependency Injection. Uber blogger Roy Osherove (who'd come all the way from Israel) then started up a really interesting discussion around the limits of IoC, or rather how doing TDD forces you to do DI rather than giving you a choice. It was a very good point, and one that hadn't really struck me before. Of course Roy works for Typemock, so he obviously interested in showing how Typemock can alleviate TDD's arm lock on your architecture. Personally I'm still in my honeymoon period with IoC containers and TDD and haven't found the edge cases yet where I feel like enforced DI is dragging my architecture or productivity down enough that I need to do something about it. The discussion continued about the depth of unit testing that's appropriate, how to test legacy code and tradeoff between integration and unit tests. All good stuff.

I hung out in the room discussing F# and all things functional for the rest of the morning and learnt a lot about the why-of-functional that I hadn't really appreciated before. I must fire up the F# shell again and have another play.  During the afternoon I failed to attend any sessions at all. Firstly I got into a very long and interesting conversation with Michael Foord. I've been reading his blog for a while and I caught his talk at Mix UK last summer, so it was good to get to chat to the man in person. He showed me Resolver, the python code generator / spreadsheet that his company is building. It's a very impressive piece of work that brings together the immediate graphical data manipulation of a traditional spreadsheet and any managed code that you want, all glued together with python. You can imagine building component-oriented financial software and binding it together under the spreadsheet front end. Or, building a model with the spreadsheet and simply taking the python code it generates, sticking it an assembly and then harnessing that model from your application. We also chatted about his upcoming book, Iron Python in Action, which I'll be getting a copy of as soon as it hits the (virtual) shelves.

For the rest of the afternoon I just stayed in the lobby area chatting. That was probably the best thing about the event for me, just being able to meet other .net geeks and talk about coding all day. Usually when I do that, even with many people who's full time job is coding, I tend to see eyes glazing over, but not today :) Hey, I'm already looking forward to the next one.

There's a wiki: http://altnetpedia.com/ that's going to act as a record of the discussions today. Hopefully, along with the mailing list, it can act as the nucleus of a growing UK ALT.NET community.