Making It Better: ASP.NET with Visual Basic 14

BASIC is part of the DNA of Microsoft, and we have continued to evolve the language for most of the 40 years of the company’s existence.  In the next evolution of the language, Visual Basic 14, there are a number of great features that are being added and we want to make sure that you know we are fully supporting them with ASP.NET in Visual Studio 2015.  Let’s take a look at a few samples of how using Visual Basic with ASP.NET 4.6 makes developers more productive and their code more readable.

 

String Interpolation Makes Web Forms Strings Feel like Razor Syntax

String formatting with Visual Basic is usually a mess.  How many times can you connect strings with ampersand (&) marks and underscores when you span rows?  If you assemble and format your strings by hand, you know what a mess this is.  You already have some nice syntax in razor like the following:

 

<a href="https://twitter.com/@ViewBag.ScreenName/status/@Item.StatusID">

 

If we wanted to do something similar in web forms for this anchor we could end up with a concatenated mess:

 

<a href="https://twitter.com/<%: screenName %>/status/<%#: Item.StatusID %>">

 

Perhaps we got a little more creative and tried to use a String.Format method call:

 

<a href="<%#: String.Format("https://twitter.com/{0}/status/{1}", screenName, Item.StatusID) %>">

 

Yuck… That makes my eyes hurt to read that, with looking back and forth across the string to understand what values are formatted and placed into the output I feel like I’m watching a tennis match.  We know we can do better to make this more readable. With the new string interpolation feature, the string can be decorated with a dollar symbol and then formatted with even simpler template text with a format like the following:

 

<a href="<%#: $"https://twitter.com/{screenName}/status/{Item.StatusID}" %>">

 

Now our string looks more readable, just like the razor syntax without having to scan back and forth across the code.  Values inside of curly braces in our text are interpreted as code values to be inserted at that point in the string, just like our previous String.Format text format but without the annoying back and forth reading for us humans.  This feature isn’t limited to just ASP.NET use, as you can use it in all of the .NET frameworks that support Visual Basic 14.

 

Use the New NameOf Operator in MVC to Validate Arguments

Magic strings are the practice of having string constants in our code that control behavior of our application.  An example of this is when we throw the ArgumentNullException when verifying input parameters:

 

 Public Function TwitterStatus(screenName As String) As ActionResult

If (String.IsNullOrEmpty(screenName)) Then

Throw New ArgumentNullException("screenName")

End If

 

That sample has a code smell, or a deep-seeded problem… if the parameter name changes and an error scenario is triggered, our code will break with this ugliness:

 

As someone who reads stack traces and debugger output, this helpful bit of information that the previous developer attempted to provide for me no longer makes any sense.

The new NameOf operator will take a variable and return a string value for the name of that variable.  Take a look at how our code changes when we use the NameOf operator:

 

 Public Function TwitterStatus(screenName As String) As ActionResult

If (String.IsNullOrEmpty(screenName)) Then

Throw New ArgumentNullException(NameOf(screenName))

End If

 

With that change, we can protect our MVC and WebAPI action methods from inadvertent changes.  Remember, the new refactoring capabilities in Visual Studio (or another refactoring tool that you may be using) will not capture references to the parameter in strings.   If you do use the automatic refactor it will not replace the parameter name in the previous string example, however it will capture this reference to the parameter name. Additionally, our thrown error looks like the following:

 

Now that error statement makes more sense for the next developer who will be maintaining your code.

 

Asynchronous Model Binding in Web Forms

Asynchronous operations have been available with the Task Parallel Library since .NET 4 in 2011.  It’s been around for a long time, and Web Forms just has not had a chance to really feel that love in the more complex interactions that they host. Let’s face it, Web Forms is the event-driven model that could have significant problems if an event is not finished an asynchronous operation when the next event is about to start.  It’s a complex model, but in the latest update to ASP.NET 4.6, we have opened the web forms model to allow Asynchronous Model Binding operations with the Task Parallel library.  Let’s take a look at how easy it is to migrate an existing set of controls to model binds asynchronously.

In this sample, I’m going to load the tweets for both the Visual Studio and ASP.NET twitter accounts into two columns on a web page.  I’ll use the ASP.NET ListView control to output a simple list of the 5 most recent tweets with a syntax and formatting like this:

 

<asp:ListView runat="server" ID="vsTweetList"

SelectMethod="vsTweetList_GetData" ItemType="LinqToTwitter.Status">

<ItemTemplate>

<p>

<%#: $"At: {Item.CreatedAt.ToString("T")} on {Item.CreatedAt.ToString("d")}" %>

<br />

<%#: Item.Text %>

</p>

</ItemTemplate>

<ItemSeparatorTemplate><hr /></ItemSeparatorTemplate>

</asp:ListView>

 

I’m using Model Binding with this control by declaring a SelectMethod on the control.  This method will be called when the control is ready to bind data for presentation, typically after the Page_Load event.  Model Binding for Web Forms is available starting with ASP.NET 4.5, and the syntax is not changed for 4.6 

The ItemType argument on the ListView provides strongly-typed databinding capabilities.  This allows me to avoid the magic-string problem with databinding syntax like Eval(“Status”) If Status was misspelled or did not appear in my data object, I wouldn’t see an error until the page was requested.  By using the ItemType, all of the references to Item in this control are strongly-typed and I get editor intellisense assistance.

Notice I used the new string interpolation feature from Visual Basic in the date format.  While not entirely necessary, it just felt cool to be able to write that as a complete sentence.

The code-behind to fetch the tweets for this presentation would normally look something like this:

 

 Public Function vsTweetList_GetData() As IEnumerable(Of Status)

Return GetTweetsFor("VisualStudio")

End Function

 

That would normally work really well, fetching the data and loading it into my resultant HTML very quickly.  In this case, I want to load two sets of tweets.  That means two requests to Twitter to load data and blocking page processing while those two requests are fulfilled by the Twitter APIs.

We can make these requests asynchronous by changing the syntax of the specified SelectMethod to return a Task.  We also need to mark the @Page directive with an async=”true” attribute.  It seems too simple, but the web forms framework was updated to allow this type of simple update to “just let the magic happen”

 

 Public Async Function vsTweetList_GetDataAsync() _

As Threading.Tasks.Task(Of IEnumerable(Of Status))

Return Await GetTweetsForAsync("VisualStudio")

End Function

 

Seriously, that’s all that you need to do in order to allow your requests to fire asynchronously.  Just add the async keyword, return a task, and await the asynchronous method call.  Now, both of my requests to the Twitter API will fire at the same time, the ASP.NET runtime will manage the threads that call the API and ensure that they are all processed before returning the page to the requesting user.

 

Roslyn Support for Visual Basic Compilation

Graph of comparison between compiler versionsWith the introduction of the new Roslyn compiler,  you now have a turbo-charged ASP.NET compiler experience.  In the tests in our lab, we have measured an almost 50% speed increase for Visual Basic developers at compile time.  However, we didn’t stop there.

Since May 2014, there has been a NuGet package available called “CodeDOM Providers for .NET Compiler Platform (Roslyn)” and wow was that hard to find.  Only 600 downloads of this package have been recorded at the time of this article’s writing, and that’s a real shame.  This package activates the Roslyn compiler for ASPX page parsing and compiling.  Do you remember waiting for the compiler to re-interpret your ASPX pages each time you change HTML formatting?  This package cuts that time significantly, but is in pre-release mode and only works for C#-based ASPX files.  With the coming release of Visual Studio 2015, we are going to release a 1.0 version of this package and add Visual Basic support.

 

ASP.NET 5 – C# Support And Also Visual Basic

We’ve talked about ASP.NET 5 as a major update of the ASP.NET framework with Roslyn and cross-platform support in mind since our initial public discussions.  It is not a short path, and we focused initially on completing support for C#.  In the months since our initial announcements, we have heard from many of you, telling us how much you like Visual Basic and that they want to see support for it in ASP.NET 5. 

We are excited today to announce that ASP.NET 5 will have full support with Visual Basic (both tooling and runtime – including cross platform runtime support).  As always, we will continue this development of ASP.NET 5 in the open, and you can track our progress or even contribute on GitHub at http://github.com/aspnet/home.

 

Summary

Visual Basic, ASP.NET and even Classic ASP before that have had a long history together.  We’re committed to that partnership, and we will continue to evolve the Visual Basic story with ASP.NET.

You can learn more about the new features in Visual Basic 14 from Lucian Wischik and from Kathleen Dollard in a pair of snack-sized five-minute videos.