Archive for 'ASP.NET'

Mocking Session in ASP.NET with Moq and VB.NET

logo

It has been a few years since I have had the chance to explore the latest enhancements to ASP.NET. The development in my day job was locked into traditional ASP.NET forms just before MVC 1.0 was released and there has not been any opportunity to change. TDD, dependency injection and inversion of control containers all slipped by with me staring at them with my nose pressed against the window. I also develop in php with CodeIgniter, so I am quite familiar with the idea of MVC and was thoroughly excited when recently, the company I work for, began brewing the idea for a new project. Now was the time to change, so I stocked up on books and blog articles and began the big catch up. I won’t go on about how great MVC is, especially when I spent many hours battling against the web form paradigm – its such an anti-web way of doing things but with these new ways of working, I now feel a new vigour for .Net web development.

My journey found me working with Moq and although it is pretty self explanatory, most examples and articles are in C# and the documentation for the library is a little sparse. I don’t find the switching between C# and VB.NET very difficult as there is mostly only a syntax difference between them but I did find a problem when, in my unit tests, I needed to assert that entries in the session had been set correctly. So here is how to do it in VB.NET.

Checking a value has been set in Session

The first thing that you need is a session object that you can look at in your tests. It needs to inherit from HttpSessionStateBase and is pretty simple as the session is just a key-value store – we can use a generic dictionary to store the values we want to check:

Public Class HttpSessionMock
    Inherits HttpSessionStateBase
    Private ReadOnly objects As New Dictionary(Of String, Object)()
 
    Default Public Overloads Overrides Property Item(ByVal name As String) As Object
        Get
            Return If((objects.ContainsKey(name)), objects(name), Nothing)
        End Get
        Set(ByVal value As Object)
            objects(name) = value
        End Set
    End Property
 
    Public Overrides Sub Add(ByVal name As String, ByVal value As Object)
        objects.Add(name, value)
    End Sub
End Class

So we now have a session store and we can then use Moq to utilise that in our controller during our test. This is done be setting up a controller context:

 'Create a real mock session object to check value against
 Dim session As New HttpSessionMock()
 
 'Create a moq controller context
 Dim mockcontext As New Mock(Of ControllerContext)
 
 'Ensure our session object is returned when the session is requested
 mockcontext.SetupGet(Function(c As ControllerContext) c.HttpContext.Session).Returns(session)
 
 'set our controller context to be the moq context
 MyController.ControllerContext = mockcontext.Object

We can then run our controller action that sets a value in our mock session object and assert that the correct value is set as follows:

  'run the controller action
 Dim result = MyController.SomeAction()
 
 'assert the session contains the object we expect
 Assert.IsInstanceOfType(session.Item("SessionItemToCheck"), GetType(ExpectedSessionObject))
 
 'TODO:other tests to ensure session item is correct

Ensuring a value is returned from Session

You can use the above real mock session object to do this in exactly the same way but we can also setup Moq to return a particular value from session directly:

'create a test object/value we want session to return
Dim MySessionValue as New SomeObject()
 
'create our moq controller context
Dim mockcontext As New Mock(Of ControllerContext)
 
'ensure our test object gets returned by the moq session
mockcontext.SetupGet(Function(c As ControllerContext) c.HttpContext.Session("SessionItemToTest")).Returns(MySessionValue)
 
'assign our context to the controller	
controller.ControllerContext = mockcontext.Object
 
'TODO: run controller action and assert results

When I look at the code now, I realise that it is quite simple to achieve. However, it took me a little while to get my head around Moq and figure this out as all the examples out there seemed to be trying to do so much more than solely testing session state. It confused me anyhow.

IIS7 WordPress and Friendly URLs

As a developer who uses Vista as their main OS, I have always found developing php sites a little bit awkward. Php never liked to play nicely with IIS and unless you installed and used Apache, friendly URLs were even more difficult to get working. I use IIS extensively for ASP.NET development and I never liked having both Apache and IIS installed together as they seemed to lock horns at every opportunity. My answer until now was to use VS.php, which runs an instance of Apache on demand, so I only have to use Apache when I need to. This was great for the most part but last week I had the situation where I was trying to work on both an ASP.NET project and a WordPress project at the same time. Stopping and starting web servers every few minutes was getting a little dull.

rewriteThis spurred me on to take some time to see what all the fuss about IIS7 and php was really about. I was pleasantly surprised. Since Vista SP1, it is possible to configure IIS to run php using FastCGI. I won’t go into the detail here, there are plenty of examples on how to configure php in this way. Needless to say, it was not too difficult and I had a test phpinfo(); page displaying in no time. What’s particularly great is that Microsoft has been doing some great work getting php to run as quickly and efficiently as it can on IIS. If you are happy running php version 5.3, over at Php for Windows, you can pick up a version that has been compiled in Visual Studio 2008 which means faster and more stable than before.

The next step in my investigation was to see what could be done with the new url rewrite module for IIS. Another easy thing to install. What’s more, it has the ability to import .htaccess files. I use these extensively when using Apache and I already had one for the WordPress site I was working on. Importing rules is a pleasure because of the neat interface that shows you which rules it can convert and which it cannot. Editing the original .htaccess directives on-screen allows you to fix those rules it is having trouble with. In my case it was just the RewriteBase, which I could happily remove without worrying about it.

One click of the ‘apply’ button and I was up add running. The site was responsive and low and behold, no issues with the friendly urls. Too easy!

Windows Server 2008, ASP.NET, Pre-compiling and Virtual Directories

windowsserver2008 There has been an interesting problem at work over the last couple of weeks. We are in the process of preparing to move service providers and at the same time upgrading all our servers to run Windows Server 2008 and SQL Server 2008. In preparation for this move, we have been upgrading our staging and test servers so we can be sure that everything will work as expected and to iron out the processes, so the move goes as smoothly as possible.

It took about ten minutes before we hit the strangest of problems. It was focused around the way we use a virtual directory to share common code and controls across different websites. The premise is that you create a project to hold your common javascript/images/ascx controls/web services and so on. You then use a virtual directory inside each of your websites that points to the common project. With only a small amount of tweaking for the common ascx controls everything seems to work without too much trouble. That is, until you try to do this on Windows Server 2008.

When we started up our web application on our new environment, we noticed almost immediately that the AJAX calls that used the common web service were failing. The error message was suggesting that the project that contained the common web service has not been compiled correctly. By copying the website across to a Windows 2003 server, we deduced that the problem was specific to 2008 as it worked perfectly on 2003. Having exhausted all the developers ideas on why this would be, we called Microsoft and got them involved in troubleshooting the issue.

A few days later an answer came: do not pre-compile your website. Sure enough, build the website without pre-compilation and it worked perfectly. Microsoft’s explanation was that it was due to a change in the way that Windows Server 2008/IIS7 worked. Fairly cryptic I must say and certainly does not leave me satisfied as to why it would not work and what have they done to stop it working. For us, using Windows Server 2008 and IIS7 is more important than the slight performance hit you get when deploying without pre-compilation. For others it may not be such a desirable solution.

Thanks for Breaking Things ASP.NET 3.5 Team

broken_glass I have just spent an intense few hours crawling all the JavaScript files in our application (and there are a quite a few) fixing an issue introduced with our upgrade to the .NET framework 3.5. The entire afternoon in fact was spent fixing a single issue: our AJAX calls had stopped working.

The first hurdle was due to a slightly off-the-norm setup we have for our website. In order to save replicating code across the various websites that make up our solution, we opted for a common virtual directory that serves common assets like JavaScript, images and so on. With a little jiggery pokery, it also allows us to use shared .ascx controls. When we upgraded to the 3.5 framework, the upgrade wizard scans the projects and changes any references that should be pointing the new 3.5 versions. Not all references were changed, as the latest framework sits on top of the 2.0 framework, rather than replaces it. Unfortunately, the upgrade wizard could not figure out that our virtual directory project was not an application at all, so it created an unneeded web.config for it . However, removing that made little difference and it took me quite a while until I found that there were additional script handler settings added for framework 3.5 that were causing the errors. We chose jQuery as the backbone of our JavaScript development and only need to have the .ascx web service handler.

As soon as I removed the unwanted handlers, our AJAX calls sprung into life but still none of our AJAX powered controls worked. A quick look with Firebug revealed the reason. All our JSON responses where wrapped in a {d: } object. A little searching on the interweb and the reason was revealed. As a security measure, wrapping the response in that way can stop cross-site scripting attacks.

So why am I annoyed? Well, I cannot fault the reason behind the change, it stops a potentially nasty attack. However, we had no choice in the matter. It broke every one of our AJAX powered controls. Just because Microsoft had handled this change in their own AJAX controls, they decided that nobody else would be using the JSON serializer for anything else. As such, they seem to have no configuration setting to turn it off. We had been running the 2.0 AJAX extension with that vulnerability in it for a while, so I think we should at least be allowed to choose whether we continue that way. Instead, I have to spend hours checking all the JavaScript file for AJAX calls and making them look for their data inside the d object.

Captcha Audio with ASP.NET

The subject of captcha images has been well covered. There are plenty of available resources for creating those warped letters. I created such a control that is a combination of quite a few different ideas and was quite proud of it until not thirty seconds after demonstrating it, someone asked whether it had a ‘play audio’ button for blind people. All of a sudden my fancy captcha control was not so fancy.

I tried to suggest using reCaptcha as a solution that had all the bells and whistles, but the customisation of my control trumped the somewhat fixed design of reCaptcha. So the problem of the audio captcha brewed a little in the back of my mind and a month or two later I turned back to it to see if I could find a solution.

A speech synthesis engine was not on the cards, so I figured that because the captcha image was a random collection of letters and numbers, the only way I could generate the appropriate audio was to have audio files of all the letters and numbers. I would then need to join them together, on demand, and play them from the web page.

Creating all the letters and numbers is straight forward enough (cue microphone and best-est speaking voice) and playing audio files from a web page has also become pretty easy thanks to the great SoundManager 2 javascript plugin.

The trickiest part was definitely joining mp3 files that SoundManager requires. MP3 audio files are particularly tricky as they can contain ID1 or ID3 tag information, so just joining them back to back would not create a correct MP3 file. What I needed to do was determine if a particular file had the tag information in it and strip it out if necessary. This took a lot of Googling and studying of the MP3 specification but I eventually managed to ensure the files had no ID2/3 tags in them before joining the files together:

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
Imports System.IO
 
Public Class MP3Concatenator
 
    Public Shared Function Join(ByVal MP3sToJoin As Generic.List(Of String)) As MemoryStream
        Dim ms As New MemoryStream()
        Dim bw As New BinaryWriter(ms)
 
        'loop around each file and remove the tags and then concatenate the files
        For Each mp3File As String In MP3sToJoin
            Dim bytes() As Byte
            Dim fs As New FileStream(mp3File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            Dim br As New BinaryReader(fs)
            Dim audioStart As Integer = 0
 
            'Check for ID3 Tags
            fs.Position = 0
            If (System.Text.Encoding.ASCII.GetString(br.ReadBytes(3)).ToUpper = "ID3") Then
                'position of the header size bytes
                fs.Position = 6
                'MSB of size is Set to 0 and ignored so we need to convert the value
                audioStart = BitsToLow(br.ReadBytes(9))
                'add the header end position to this
                audioStart += 9
            End If
 
            'Check ID1 Tag
            fs.Seek(-128, SeekOrigin.End)
            If (System.Text.Encoding.ASCII.GetString(br.ReadBytes(3)).ToUpper = "TAG") Then
                'there is a ID3v1 tag on the end which needs removing
                fs.Position = audioStart
                bytes = br.ReadBytes(CInt(fs.Length - 128))
            Else
                fs.Position = audioStart
                bytes = br.ReadBytes(CInt(fs.Length))
            End If
 
            bw.Write(bytes)
            br.Close()
            fs.Close()
        Next
 
        ms.Position = 0
        Return ms
    End Function
 
    Private Shared Function BitsToLow(ByVal Size() As Byte) As Integer
        Dim Ret As Integer
        Ret = Size(3)
        If Size(2) <> 0 Then
            If CBool(Size(2) And 1) Then Ret += 128
            If CBool(Size(2) And 2) Then Ret += 256
            If CBool(Size(2) And 4) Then Ret += 512
            If CBool(Size(2) And 8) Then Ret += 1024
            If CBool(Size(2) And 16) Then Ret += 2048
            If CBool(Size(2) And 32) Then Ret += 4096
            If CBool(Size(2) And 64) Then Ret += 8192
        End If
        If Size(1) <> 0 Then
            If CBool(Size(1) And 1) Then Ret += 16384
            If CBool(Size(1) And 2) Then Ret += 32768
            If CBool(Size(1) And 4) Then Ret += 65536
            If CBool(Size(1) And 8) Then Ret += 131072
            If CBool(Size(1) And 16) Then Ret += 262144
            If CBool(Size(1) And 32) Then Ret += 524288
            If CBool(Size(1) And 64) Then Ret += 1048576
        End If
        If Size(0) <> 0 Then
            If CBool(Size(0) And 1) Then Ret += 2097152
            If CBool(Size(0) And 2) Then Ret += 4194304
            If CBool(Size(0) And 4) Then Ret += 8388608
            If CBool(Size(0) And 8) Then Ret += 16777216
            If CBool(Size(0) And 16) Then Ret += 33554432
            If CBool(Size(0) And 32) Then Ret += 67108864
            If CBool(Size(0) And 64) Then Ret += 134217728
        End If
        BitsToLow = Ret
    End Function
End Class

The trickiest part was handling the ID3 tag, as the specification states:

The ID3v2 tag size is encoded with four bytes where the most significant bit (bit 7) is set to zero in every byte, making a total of 28 bits. The zeroed bits are ignored..

Which is why I have the BitsToLow function in the code above.

The resulting concatenation is returned as a memory stream because I knew I could output this directly to the Response without writing the concatenated file to disk:

1
2
3
4
5
6
7
8
9
            ....
            Dim ms As IO.MemoryStream = Nothing
            ms = MP3Concatenator.Join(MP3FileList)
            Response.ContentType = "audio/mpeg"
            Response.ExpiresAbsolute = Date.MinValue
            If ms IsNot Nothing Then Response.OutputStream.Write(ms.GetBuffer, 0, CInt(ms.Length))
            ms.Close()
            Response.End()
            ....

By wiring up the CaptchaAudio.aspx page that returned the concatenated audio to the SoundManager plugin, I could create a link next to the captcha image, that played the letters in the image. Now my captcha control really was fancy.

jQuery Inline Confirm

I have been using Delicious social bookmarking service ever since Blinklist degraded and finally lost the plot with their new design. When I first started using Delicious, a feature of their interface really leapt out at me and I could not wait to include it into a project.
The feature I am talking about is their inline confirmation. That is, when you, for instance, delete a bookmark by clicking on the delete link, the link is replaced with an ‘Are You Sure? Yes/Cancel’ message.

Inline Confirm - Before

Inline Confirm - After

I really liked this as there was no page refresh for the confirmation message and it was not a modal popup, which is a little obtrusive at best. It also occurred to me that something like that would not require a huge amount of code either. This is what I came up with:

1
2
3
4
5
6
7
8
9
$.inlineconfirm = function(el, callback, parentSel) {
        var hideEl = parentSel ? $(el).parents(parentSel) : $(el);
        hideEl.hide()
        $('<div class="confirm">Are you sure? <a class="confirmyes" href="#">Yes</a> <span>|</span> <a class="confirmcancel" href="#">Cancel</a></div>')
            .find('a.confirmyes').click(function() { callback(); hideEl.show();  $(this).parents('div.confirm:first').remove(); return false; }).end()
            .find('a.confirmcancel').click(function() { hideEl.show(); $(this).parents('div.confirm:first').remove(); return false; }).end()
            .insertAfter(hideEl);
        return false;
    }

I decided on using just a function rather than a plugin, as I wanted asp.net control compatibility (see later). The function just swaps out the element(s) for the confirmation message and puts them back if cancel is pressed, otherwise it runs the callback. It utilises three parameters:

  • el – The element which initiates the inline confirm. i.e. The link
  • callback – A function to run if the answer is Yes
  • parentSel – (optional) This is a jquery selector that identifies a parent element of el that will be replaced with the prompt. This is so that you could for instance hide an entire section of html with the ‘are you sure?’ prompt. Particularly useful to keep layouts consistent.

This is a nice easy function to use in most web development language, however, if you are using asp.net, it becomes difficult to use it with the asp controls like <asp:Button /> or <asp:LinkButton />. This is because ASP.NET likes to take control of the click events of these so that it can create its event model at the server. There is the onClientClick property which allows us to have some control over the click event but we need to pass a callback function. After a little investigating, I discovered the GetPostBackEventReference function:

mylinkbutton.OnClientClick = "$.inlineconfirm(this,function() {" & ClientScript.GetPostBackEventReference(mylinkbutton, "") & ";});return false;"

The GetPostBackEventReference returns a string of the function that will be used to invoke the postback. Just what we needed.

Templating Your ASP.NET Pages

The majority of my ASP.NET development time is spent on web applications. Recently however, I was creating a marketing website to complement one of those applications and realised it required a slightly different approach to that which I was used to – we needed maximum changeability for as little downtime. Switching off the option to compile the pages into the dlls was the first step but I wanted pages with as little structural code in them as possible, as they may be edited by a non-developer. I discovered that the use of template user controls was the answer to this and meant that the pages would contain controls similar to this:

1
2
3
4
<uc:contentarea id="mycontent" runat="server">
  <headingcontent>Some Heading</headingcontent>
  <maincontent>Lorem ipsum..</maincontent>
</uc:contentarea>

In this way, any html code that affects the layout would be hidden away and anyone changing them cannot accidently break the layout. How does one do this? It is fairly straight forward. First you create a new user control and write the html as you want it, with the areas where the content is to be inserted marked to run at server:

1
2
3
4
<div id="mycontentcontrol">
  <h1 id="heading" runat="server"></h1>
  <p id="content" runat="server"></p>
</div>

The differences to a standard user control occur in the codebehind:

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
Imports System.ComponentModel
Partial Public Class MyControl
    Inherits System.Web.UI.UserControl
    Private _headingTemplate As ITemplate = Nothing
    Private _contentTemplate As ITemplate = Nothing
 
    Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Not (HeadingContent Is Nothing) Then
            Dim container As New ContentContainer()
            HeadingContent.InstantiateIn(container)
            heading.Controls.Add(container)
            heading.DataBind()
        End If
        If Not (MainContent Is Nothing) Then
            Dim container As New ContentContainer()
            MainContent.InstantiateIn(container)
            content.Controls.Add(container)
            content.DataBind()
        End If
    End Sub
 
    <TemplateContainer(GetType(ContentContainer)), _
       PersistenceMode(PersistenceMode.InnerProperty), _
       TemplateInstance(TemplateInstance.Single), _
       Browsable(False)> _
   Public Property HeadingContent() As ITemplate
        Get
            Return _headingTemplate
        End Get
        Set(ByVal value As ITemplate)
            _headingTemplate = value
        End Set
    End Property
 
    <TemplateContainer(GetType(ColumnContainer)), _
        PersistenceMode(PersistenceMode.InnerProperty), _
        TemplateInstance(TemplateInstance.Single), _
        Browsable(False)> _
    Public Property MainContent() As ITemplate
        Get
            Return _contentTemplate
        End Get
        Set(ByVal value As ITemplate)
            _contentTemplate = value
        End Set
    End Property
 
    Public Class ContentContainer
        Inherits Control
        Implements INamingContainer
 
        Friend Sub New()
        End Sub
    End Class
End Class

There is quite a lot here but it is fairly straight forward. The key to it is using the ITemplate interface for the properties that represent each of the areas you want as editable. This allows you to place the tags within the control in your page. At runtime , the content of these is placed into a control – the ContentContainer class, using the InstantiateIn method and that control is then placed into the html.