HttpListener Series – 2 – Websiting   1 comment

The series index here.

One of the most common uses of IIS is to host websites through a file system folder where relative paths are used for resources. There isn’t much to it but some string prefix handling and some stream copying but I’ll provide a simple implementation of what it needs to be done to run a simple static website.

Let’s say we have a folder containing a website looking like this:


The content of the files is as follows…


    <title>HttpListener Demo HTML Page</title>
    <link rel="stylesheet" type="text/css" href="Files/Styles.css" />
        Here is the HTML page.</p>
    <input type="button" id="aButton" value="Click to Run Script" />
<script type="text/javascript" src="Files/Scripts.js"></script>


    font-size: 20px;
    font-weight: bold;

    border: 2px solid blue;
    font-style: italic;


document.getElementById("aButton").onclick = function () {
    alert("You clicked the button");

The implementation of this website hosting would be something like so:

string baseFolder = @"C:\WebSite\";

var listener = new HttpListener();

Console.WriteLine("Listening ...");

while (true)
    var context = listener.GetContext();

    Console.WriteLine("Request received for: " + context.Request.Url.AbsoluteUri);

    var baseUrl = "http://+/HLD/".Replace("+", context.Request.Url.Authority);
    var resourceRelativePath = context.Request.Url.AbsoluteUri.Substring(baseUrl.Length);
    var resourceFullPath = Path.Combine(baseFolder, resourceRelativePath);

    if (File.Exists(resourceFullPath))
        context.Response.StatusCode = 200;
        context.Response.StatusDescription = "OK";

        string contentType = "application/octet-stream"; // just to have a default
        switch (Path.GetExtension(resourceFullPath))
            case ".htm":
                contentType = "text/html";
            case ".css":
                contentType = "text/css";
            case ".js":
                contentType = "application/x-javascript";
        context.Response.ContentType = contentType;

        var fileStream = File.OpenRead(resourceFullPath);
        context.Response.ContentLength64 = fileStream.Length;
        fileStream.CopyTo(context.Response.OutputStream, 64*1024);
        context.Response.StatusCode = 404;
        context.Response.StatusDescription = "Not Found";
        var writer = new StreamWriter(context.Response.OutputStream);
        writer.Write(string.Format("<!DOCTYPE HTML><html><head><title>Resource Not Found</title></head><body><b>Error 404 - Resource Not Found</b> - There resource ('{0}') requested was not found.</body></html>",


A little bit of string comparison and we’re all done. Now you can access “http://localhost/HLD/Page.htm”.


  • The functionality of a default document can be easily be implemented by responding to an empty resourceRelativePath with a predefined document.
  • Response.ContentType must be set before beginning to send the resource stream, otherwise it will not be taken in account.
  • 64KB (64B * 1024) of buffering to copy the resource stream should be enough. Play with and find what it implies in the speed of the delivery and find your own buffer size.

Posted 2012/07/09 by Bigsby in Hands On

HttpListener Series – 1 – Get It Listening   1 comment

The series index here.

After getting a grip of what HTTP is, we can start playing with the HttpListener class that was presented to the world in .Net 2.0.

HttpListener, provides a wrapper that manages the socket and TCP levels of communication (streaming, buffering and so on) and reads and sets the protocol parameters, i.e, method, headers, status, content, etc..

So, if you want to start your own web server, HttpListener is the best way to start with. Let’s implement the example of the previous post in this series.

Starting a HttpListener couldn’t be simpler.

Instanciate it:

var listener = new HttpListener(); //instanciate it
listener.Prefixes.Add("http://+/HLD/"); //tell it what to listen to

listener.Start();  // start it

while (true)
    var context = listener.GetContext();  // get the request

    Console.WriteLine("Request received for: " + context.Request.Url.AbsoluteUri);
   // answer the request
    context.Response.ContentType = "text/html";
    context.Response.StatusCode = 200;
    context.Response.StatusDescription = "OK";

    var writer = new StreamWriter(context.Response.OutputStream);
    writer.Write("<!DOCTYPE HTML><html><head><title>Http Listener demo.</title></head><body><b>Hello</b>, this is the <i>HttpListener</i> responding.</body></html>");

    context.Response.Close(); // end the response


  • In the prefix the“+” wildcard is used for the domain name. This means every domain coming into the machine in the indicated port. So, “localhost” locally, the machine name or network IP will be valid URLs.
  • As this is Http, the port 80 is implicit. If a different port, for instance 8080, is intended just set “http://+:8080/HLD”.
  • An HttpListenerException “Access is denied” exception might be thrown in the listener.Start() statement if the user running the process is not allowed to open the port. Check here.
  • Setting Response.ContentType is very important. Maybe not so in Internet Explorer that “reads” the content and tries to figure what’s in it. Try changing it to “text/plain” and you’ll find IE and Chrome don’t exactly display alike.
  • You must always close the response by calling context.Response.Close(), otherwise the client will never get the response and will, eventually, time out.

You can now go to any Http client, for instance, the internet browser of your choice, access “http://localhost/HLD/&#8221;.

So, this is just what IIS does in the most simplified way. Mostly reading the content from a file system stream, setting the MIME type (context.Reponse.ContentType) according to the file extension. Will get there in the next post of these series.

Posted 2012/07/04 by Bigsby in Hands On

HttpListener Series – 0 – What is HTTP?   2 comments

The series index here.

When I started working in computer programming (not that long ago) I was amazed how developers (not necessarily bad ones) didn’t know, or care to know, about what happens underneath their coding and what standards rule their unconscious processes. As 90% of the computer programming work I see and do is web-base, I find it intriguing, to say the least, the amount of “professionals” that don’t know what HTTP and a HTTP request/repsonse is. I’ll try and make it simple.

This is one of the rare cases where a naming in technology (computer, mainly) didn’t loose it’s meaning with its extended usage.

H.T.T.P. stands for Hypertext Transfer Protocol.

So, it’s a protocol (a set of rules and standards) to communicate data that is not just text. It’s official documentation is set and provided by W3C (World Wide Web Consortium) here.

I won’t go into the deep depths of the bits communication but, you can go there by looking into Sockets or, up one level, TCP. Let’s just say that, for a HTTP communication to occur, a Socket connection based on TCP must be open.

HTTP provides a standardization for a request-response data in a client-server communication. A raw HTTP request and consequent response look like so…

The request:

GET http://localhost/HLD/ HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: localhost
Pragma: no-cache

The response:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/html
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 04 Jul 2012 15:04:59 GMT

<!DOCTYPE HTML><html><head><title>Http Listener demo.</title></head><body>Hello, this is the HttpListener responding.</body></html>

Simple, no? A first line defining:

– in the request: the type “GET” (or method, we’ll get there); the resource to retrieve “http://localhost/HLD/”; and the protocol version “HTTP/1.1”

– in the response; the procotol version “HTTP/1.1”; the repsonse status code “200”; and the status description “OK”.

A bunch of, so called, headers. “New line” separated values in the form of name:value.

And, in this case just in the response, some content which, in this case, happens to be HTML.

In the end, the protocol provides a way a of, in a commonly known manner,  communicate data with some extra information that helps each side deal with the data in an organize and predictable way.

There really isn’t much more to say about the protocol but it is, IMO, vital to know this happens to understand what goes on underneath every client (e.g., a web-browser) request. Of course, the protocol provides, though methods, headers and statuses ton’s of standardized functionalities. I’ll go through some of those along these series.

See ya!

Posted 2012/07/04 by Bigsby in Hands On

Tagged with ,

HttpListener Series   Leave a comment

In this series, all about HttpListener class will thoroughly explained and exemplified. After this, any one will be able to self-host web-based scenarios without the need of an IIS and everything that comes with it.

The series is divided in the following topics (links will be provided along completion of each topic):

0 – What is HTTP? – Overview of HT.T. Protocol

1 – Get it listening

2 – Websiting – Simple web site hosting

3 – Windows Authentication – Using Windows provided authentication

4 – "Manual" Authentication – Handling HTTP authentication

5 – ASPing – Non-static request processing

6 – HTTPS – SSL secure communication

7 – WCF Data Service Hosting – OData is friends with HttpListener


As always, if there is any suggestion or unanswered topic about the subject, feel free to comment anywhere. I’ll be delighted to make this series as though and helpful as I can.

A full working solution with all these implementations can be downloaded here:

Posted 2012/07/04 by Bigsby in Hands On

Tagged with , ,

Gambolling with Delegates   1 comment

In my previous post I explained the concept and basics of Delegates. I’ll assume that there is an understanding of Lambda Expressions. The following content’s interest is close to just academic but, understanding it is key to really take advantage of Delegates and wonders a good implementation provides.


Simple Start

Let’s start with this simple delegate implementation:

delegate void StringVoidDelegate(string input);

As I exposed in my previous post, this defines a method signature where a string is received as a parameter and there is no return.

Since I’m in a Console Application I’ll implement some helpers to understand what is going on using the delegate just implemented:

static int CallCount = 0;
static StringVoidDelegate CWL = input => Console.WriteLine(++CallCount + " " + input);


A simple usage of this method can be:

CWL("Calling Elvis");

With output:

1 Calling Elvis


Generic Delegate

Like any other generic capable object in .Net, delegates receive a type generically on implementation. Something like so:

delegate string ToString<T>(T obj);


If, for instance, we have a Person class like this:

class Person
    public string Name { get; set; }
    public DateTime Birthday { get; set; }


We can have a method compliant with ToString delegate signature like so:

ToString<Person> personToString = person => person.Name;


Which can be used like so:

ToString<Person> personToString = person => person.Name;
var jCleese = new Person { Name = "John Cleese", Birthday = new DateTime(1939, 10, 27) };

With output:

1 John Cleese


Stacking Delegates

Since calling a method with the assurance of its signature is so ‘OK’ we can easily stack delegates to be run consecutively, provided that the signature is the same. Same signature means all the delegates reference to de same implementation; delegates with same input and output type signatures but different implementation won’t be interoperable. Stacking and unstacking delegates is done using arithmetic ‘+’ and ‘–’ operators.

Adding adds the delegate on the right hand to the list of methods that will be called.

StringVoidDelegate Echo = input => CWL("Echo..." + input);
Echo += CWL;

With output:

1 Echo...John Cleese
2 John Cleese

So CWL will be run consequently after Echo with the same parameter.

Removing removes the last call to that method on the ‘stack’ if there is any. Say we have this parameter less delegate:

delegate void ParameterlessVoidDelegate();


This sequence:

ParameterlessVoidDelegate writeOne = () => CWL("One");
ParameterlessVoidDelegate writeTwo = () => CWL("Two");
ParameterlessVoidDelegate writeThree = () => CWL("Three");
ParameterlessVoidDelegate writeA = () => CWL("A");

ParameterlessVoidDelegate write = writeOne + writeA + writeTwo + writeA + (() => CWL("Four"));
write -= writeA;
write -= writeA;
write -= writeA;

Would have this output:

1 One
2 A
3 Two
4 A
5 Four
7 One
8 A
9 Two
10 Four
12 One
13 Two
14 Four
16 One
17 Two
18 Four


Composing results

When  adding delegates with a return object, all methods are ran from left to right but only the last return is accounted for, all others are discarded.

Let’s take this signature:

delegate int IntToIntDelegate(int value);


The following code:

IntToIntDelegate baseAddingDelegate = value =>
        return value;

IntToIntDelegate AddOne = value => baseAddingDelegate(value + 1);
IntToIntDelegate AddTwo = value => baseAddingDelegate(value + 2);

var addAll = AddOne + AddTwo + (value => baseAddingDelegate(value + 3));

(baseAddingDelegate is just a wrapper to shorten the code)

The output is this:

1 2
2 3
3 4
4 4


If the intension is to have the result of the application of all methods the implementation would have to look like so:

IntToIntDelegate AddOne = value => baseAddingDelegate(value + 1);
IntToIntDelegate AddTwo = value => baseAddingDelegate(value + 2);
IntToIntDelegate AddThree = value => baseAddingDelegate(value + 3);
IntToIntDelegate progressiveSum = value => AddOne(AddTwo(AddThree(value)));

And the result:

1 4
2 6
3 7
4 7


In Event Handling

Using delegates you can easily propagate method calling without having to reference methods in each others. For instance, having this methods:

RoutedEventHandler DoOneThing = new RoutedEventHandler((s, e) => { });
void ButtonHandler(object s, EventArgs args) { }
void DoAnotherThing() { }


This code is very OK and might be very useful:

button.Click += DoOneThing;
DoOneThing += ButtonHandler;
button.Click += (s, e) => DoAnotherThing();


.Net Action and Function

Just a quick note to say that our .Net Framework friends, since .Net 2.0, were kind enough to provide some common delegate implementation and, using generics, a short way to request for a certain signature.

Their implementation is as simple as this.



public delegate void Action();

public delegate void Action<T>(T obj);

public delegate void Action<T1, T2>(T1 arg1, T2 arg2);

public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);



That can be used like so:

var a = new Action<string, int, string>((s1, i, s2) => { CWL(s1); CWL(i.ToString()); CWL(s2); });
a("One", 2, "Three");

With this output:

1 One
2 2
3 Three



Is the same as Action but, at least, one generic type must be provide to serve as the return type. Something like so:

var f = new Func<int>(() => 3);


1 3




Delegates that can help you simplify and encapsulate your code in an error safe way. The sky is the limit. I use them all the time to wrap generic asynchronous call handlings and stuff like that.

That’s all…hope it’s useful.

Posted 2011/02/08 by Bigsby in General

Tagged with , , , ,

Once upon a Delegate   1 comment

For the short life as a computer programmer I’ve enjoyed so far, the most miss, or not at all, understood feature of programming are delegates and, subsequently, handlers and events. I’ll try, here, to provide easily understandable way of looking at this mystery for so many ‘good’ programmers.


What is a delegate?

According to MSDN, a delegate is a type-safe and secure function pointer. To me this mean, a delegate is a definition of a method signature, i.e., it defines input and output parameter types for methods. Having this in mind, the following delegate definition:

delegate int StringToIntDelegate(string input);

…means that the methods compliant with this delegate, receive a string as input parameters and return an integer.


What is it worth?

By the first paragraph of this post, one might notice that the great majority of programmer don’t use (or so they think, as will see further down) delegates which means that they’re not essential for a computer programme to work. But, in the same direction, neither are classes and that’s not a place one wants to go. Delegates, like classes, provide strongly typed encapsulation and polymorphism whose purpose and consequences are the elimination of code redundancy and thus then probability of error and simplifies error correction.


An example

For instance, imagine we are implementing a class for form input field to wrap is properties and provide some validation. It would be nice to be able to generically but strongly-typed access a method that provides some validation. Bla, bla, bla…a little code might help.

The validator method would be, for our definition, a method that receives a string (that might be inserted by the user) and returns a boolean indicating if the value is valid. Something like so:

delegate bool ValidateStringDelegate(string input);


Having this definition at hand the implementation for an input field wrapper could look like this:

public class InputField
    public string Value { get; set; }
    public string Caption { get; set; }
    public ValidateStringDelegate Validator { get; set; }
    public bool IsValid { get { return Validator(Value); } }


A validator method could look like so:

bool MinimumLengthValidator(string value)
{ return value.Length > 3; }


An instance of InputField could look like so:

var field = new InputField(); 
field.Caption = "Property Caption";
field.Validator = new ValidateStringDelegate(MinimumLengthValidator);


And, at any time, there’s a safe and strongly typed way of checking if the field is valid, like:

if (field.IsValid)
    Console.WriteLine("Incorrect input!");
    Console.WriteLine("Input OK!");



Lambdas and delegates

I’d say lambdas and delegates are one of coding best friends ever. This happens because, as long as the delegate (the method signature, remember?) is defined a lambda expression is all that is needed to implement a method. Taking the example above, there are other shorter ways of instantiating an InputField. The following are valid and with the exact same outcome:

field.Validator = MinimumLengthValidator;

ValidateStringDelegate validator = (value) => { return value.Length > 3; };
field.Validator = validator;

field.Validator = (value) => { return value.Length > 3; };

…and, the one I would write…

field.Validator = value => value.Length > 3;


All these are possible because the signature of the method is established. By the time this line of code is reached, everybody knows that Validator property is to be a method that receives a string and returns a boolean.

Note that this:

var validator = (value) => { return value.Length > 3; };

is not valid and will result in compiler error because the compiler can’t tell what type value is supposed to be.


What about handlers and events?

As there is no chicken or egg, the event comes first.

Conceptually, and as the naming suggests, an event something that is suppose to be used (raised, so they say) when something happens. Technically it is just a delegate defined property like in the example above but whose setting is limited by the compiler. This means you can add methods to it but you can’t set it but, in my next post, I’ll explain delegate operations and the reason for this will be clear.

If will look at the customary implementation of an event in a class (or interface) it looks like so:

event HandlerType EventName;


Here, HandlerType is a defined delegate. In fact, our first delegate definition is just as valid as any other to use in the definition of an event:

event ValidateStringDelegate ValidateEvent;


This means that any handler assigned to this event must match the signature of ValidateStringDelegate.

Yes, although it is not the usual .Net approach, an event handler can have a return value. I’ll expose more on events in a future post but I’ll drop a simple implementation of the InputField class above that would be more useful in some scenarios, for instance, when the validation processing is to be called from some external object holding the InputField instance.

public class InputField
    public string Value { get; set; }
    public string Caption { get; set; }
    public bool IsValid { get; private set; }
    public event ValidateStringDelegate Validation;
    public void Validate()
        if (null == Validation)
            IsValid = true;
            IsValid = Validation(Value);

With this implementation, a form holding the InputField would just need to call Validate method and everything else would run its course in a safe and strongly-typed manner. Here, the naming ‘event’ makes less sense conceptually but I’ll get there in a future post.



Hope this made sense and that it may help at least one programmer doing better code.

Posted 2011/02/08 by Bigsby in General

Tagged with , , , ,

SQL Server Compact not for ASP.Net   1 comment

“SQL Server Compact is not intended for ASP.NET development.”

Right…So you have this cool thing that allows you to have a SQL database in a hosting that only provides MySQL databases and such but you can’t use it. You got to be kidding me.

But, if really, really, really want it, there you go:

AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);

Just put before the call to the database is made (Global.asax, etc.).

Posted 2010/11/17 by Bigsby in Tips & Tricks

Tagged with , ,