Skip to contentSkip to author details

VB.NET

A 8-post collection

Project changes! More C# posts to come

Written by Michael Earls
 C#  VB.NET

After a meeting this morning, we have decided to go with ASP.NET 5 and C#, rather than ASP.NET 4.5.2 and Visual Basic .NET. So, my technical posts will switch back to C#.

I’m pretty excited about the change. I had the base framework completed in VB, but that would have ensured that my client would be stuck in the near future as Microsoft is not supporting VB in the next version of ASP.NET.

Now, the dilemma is whether or not to use AngularJS. :)

Dynamic Bootstrap themes with ASP.NET using server-side bundling

Written by Michael Earls
 bootstrap  bundling  css  themes  VB.NET

I am setting up a system that needs to load the bootstrap theme that is being used from the web.config file (eventually, this might move to a database field for runtime changes).

Initially, I had my theme defined in the bundle.config file like so:

<?xml version="1.0" encoding="utf-8" ?> 
<bundles version="1.0"> 
    <styleBundle path="~/Content/css"> 
        <include path="~/Content/bootstrap.css" /> 
        <include path="~/Content/Site.css" /> 
        <include path="~/Content/bootstrap-theme.superhero.min.css" /> 
    </styleBundle>
</bundles>

This worked well for statically defined theme, but I need to make it dynamic. It turns out that this was quite easy. Simply remove the theme from bundle.config and add it to BundleConfig.vb (or BundleConfig.cs for C# projects).

Before doing that, let’s go ahead and add it to the web.config file:

<appSettings>  
    <add key="theme" value="bootstrap-theme.superhero.min.css"/>
</appSettings>

Then, we just add this one line to the bottom of the BundleConfig.vb file:

bundles.GetBundleFor("~/Content/css").Include("~/Content/" & ConfigurationManager.AppSettings("theme"))

It is important to notice that the virtual path for the bundle matches the same name as the path defined in your bundle.config file.

Now, whenever pages on your site are served, the theme css will be served along with the other bundled css. After testing, I’m pretty sure that the newly included css is last in line.

To change your theme, simply change it in web.config and reload. Or, replace the call to ConfigurationManager.AppSettings to a database call to retrieve the theme.

Also, make sure you’ve downloaded and saved the css theme to the Content folder before trying to access it.

You can get some nice free themes from Bootswatch.

Adding the [Authorize] attribute to an ASP.NET Web Forms Page control using custom routing

Written by Michael Earls
 ASP.NET  programming  VB  VB.NET  WebForms

I am developing a system that uses custom routing to load pages. I needed a quick way to secure the pages so I didn’t have to put the same

The "old" way

If Not Page.User.Identity.IsAuthenticated Then  
    Response.Redirect("~/Account/Login?ReturnUrl=" & Server.UrlEncode(Request.Url.ToString())
End If

You get the idea.

Anyway, I remember how beautifully WebAPI and MVC handle this by using the “AuthorizeAttribute” attribute. So, I decided to implement this in my page router.

The "new" way

First, you’ll want to enable custom routing in your application as outlined here. Notice that the article I linked to has a solution already outlined for security. I decided not to go that route as I like this solution better.

I have a custom class for handling the IRouteHandler interface implementation required by the custom routing solution.

Within that handler, I do various things like check the virtual paths to make sure that they are valid. Most custom routes get converted to a custom base page that has a public property on it for use with my system. I instantiate that class, set the custom property, and then return that page as the IHttpHandler required by the GetHttpHandler method of the IRouteHandler interface.

Here is the definition of the route in my RouteConfig.vb file:

'Content editor route '  
routes.Add("Edit Content", New Route _  
    ( _ 
        "EditContent/{contentControl}", New CMSPageRouteHandler("~/Pages/CMSContentEditor.aspx") _
     ))

Here is the class definition of a page with the Authorize attribute on it:

<Authorize(Roles:="Editor")> _  
Public Class CMSContentEditor Inherits System.Web.UI.Page  
    ...
End Class

Only users in the Editor role will be able to access this page. Let’s see why.

To start off with, we need to see if our page is decorated with the Authorize attribute. I created a function that does this. I pass in the requestContext that was handed off to me in the GetHttpHandler() method (make sure you Import the System.Web.Http namespace):

Protected Function IsPageAuthorized(ByVal page As Page, ByVal requestContext As System.Web.Routing.RequestContext)  
    Dim authorized As Boolean = requestContext.HttpContext.User.Identity.IsAuthenticated 
    ' Check to see if this page is decorated with the "Authorize" attribute '    
    Dim authAttribute As AuthorizeAttribute = Nothing 
    Dim ptype As Type = page.GetType() 
    For Each attr In ptype.GetCustomAttributes(True) 
        If TypeOf attr Is AuthorizeAttribute Then 
            authAttribute = attr 
            Exit For 
        End If 
    Next 
    If authAttribute Is Nothing Then 
        ' there was no Authorize attribute on this page, so go ahead and let them in '
        authorized = True 
    Else 
        ' see if this page is authorized '
        If Not String.IsNullOrEmpty(authAttribute.Users) Then 
            ' reset the authorized variable since we have Users listed '
            authorized = False 
            If authAttribute.Users.ToLower().Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries).Contains(requestContext.HttpContext.User.Identity.Name.ToLower()) Then 
                authorized = True 
                GoTo EndOfAuthCheck 
            End If 
        End If 
        If Not String.IsNullOrEmpty(authAttribute.Roles) Then 
            ' reset the authorized variable since we have roles '
            authorized = False 
            ' split the roles into an array '
            Dim roles() As String = authAttribute.Roles.Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries) 
            If roles.Count > 0 Then 
                For Each role In roles 
                    If requestContext.HttpContext.User.IsInRole(role) Then
                        authorized = True 
                        GoTo EndOfAuthCheck 
                    End If 
                Next 
            End If 
        End If 
    End If 

EndOfAuthCheck:  
    Return authorized 

End Function

First, we set the authorized variable to equal whether or not the user is authenticated. This will save us time later when none of the other checks fail.

After we loop through the attributes on the page, the authAttribute will either be null or it will be equal to the instance of the AuthorizeAttribute that is on the page. If we check it and it’s null, then we know the page is authorized, so we go ahead and set the authorized variable to true and continue on. However, if the authAttribute has a value, then we need to check the properties on the attribute to see if the page is authorized.

User list check

First, we look to see if the User’s name is included in the array of Users (we get it by splitting the Users property of the attribute by commas). I went ahead and converted the Users property to lower case for comparison sake, just in case.

If we find the User’s name in the Users property, then we simply set the authorized variable to true and continue on. I used a GoTo to short circuit and save the work of the next step:

Role checks

Next, we split the Roles into an array, then loop through each one, seeing if the user is in that role. If so, we set the authorized variable to true and continue on.

Authorized or not?

Once all of this has taken place, I return the authorized variable to the caller.

Handling the authorization response

In the calling method, here’s what I do:

If IsPageAuthorized(redirectPage, requestContext) Then  
    Return redirectPage 
Else  
    RedirectToLoginPage(requestContext) 
End If

Here is the RedirectToLogin() method. I add a referrer to the ReturnUrl so I know where the originating request came from. Otherwise, it gets lost when the Login page redirects to the desired page as the Login is now the referrer.

Protected Sub RedirectToLoginPage(ByVal requestContext As System.Web.Routing.RequestContext)  
    ' redirect to the login page, but send the current referrer as a QueryString on the return page so it can be accessed '
    Dim referrer As String = String.Empty 
    If Not requestContext.HttpContext.Request.UrlReferrer Is Nothing Then 
        referrer = "/?referrer=" & requestContext.HttpContext.Request.UrlReferrer.AbsolutePath 
    End If 
    requestContext.HttpContext.Response.Redirect("~/Account/Login?ReturnUrl=" & requestContext.HttpContext.Server.UrlEncode(requestContext.HttpContext.Request.Url.AbsolutePath & referrer)) 
End Sub

Then, in my custom page, I simply check the value of the referrer like so:

If Not Request.UrlReferrer.AbsolutePath.ToLower().Contains("login") Then  
    Session(SESSION_KEY_REFERRER) = Request.UrlReferrer.ToString() 
Else  
    Session(SESSION_KEY_REFERRER) = Request.QueryString("referrer") 
End If

I can’t use ViewState because of issues I’ve run into with custom routing and ViewState with my pages, so I’ve had to resort to using the Session.

As you can see, adding the Authorize attribute to a custom page is easy when you’re doing custom routing. Of course, if custom routing isn’t for you, then this solution won’t work, but I thought I’d share it for those of you who do use custom routes with dynamic pages.

Of "old versus new" - Why not AngularJS? Why ASP.NET?

Written by Michael Earls
 AngularJS  C#  VB.NET  WebForms

I recently commented on a friend’s Facebook post about AngularJS stating that I hoped Angular dies a quick and horrible death. I guess that was a bit harsh, but I have to admit that I’m tired of reading about it. To be fair, I have created an Angular app that used routing, controllers, basic authentication, WebAPI, and messaging, so I do have some experience with it. I liked it, it was nice, and the architecture is sound.

I don’t understand why people are abandoning ASP.NET for SPA (Angular in particular). Are postbacks really that bad? The AJAX-style communication with the server is overrated in my book. If you build a good user interface and have a decent connection, then Angular and ASP.NET should take the same amount of time. Front-loading JS libraries or waiting for the server to respond take the same amount of effort. And, you are more kind to a larger install base of browsers. Angular takes a somewhat arrogant approach to browsers in that it only works on the latest. It is unapologetic about this.  I see much the same attitude from developers of Angular apps, as well. They seem to state that “if you don’t use the latest technology to access my app, then I have no time for you. I’ll be damned if I’m going to use that ‘old’ technology”. Not everyone is like this, but I have seen this attitude on some posts.

Simply using a technology because it’s new is not a good enough reason for me. When I developed my Angular JS app, I immediately saw where I was going to have trouble maintaining it in the future. Upgrades would require a complete rewrite and changes to the structure would require the same architectural challenges as any other technology.

I have Dependency Injection in my current application to help with dependencies, but with Entity Framework being the core of my data story, I don’t have a whole lot of trouble getting to what I need.

In the end, I think it comes down to your comfort level with using “old” technology. In my eyes, it’s a sign that it is tried and true. Just because something is new doesn’t mean it is better. However, looking at it from another angle, there are many new features being added to ASP.NET these days that make life a lot easier for the developer and make the application more efficient.

Of course, you’ll probably be reading another AngularJS post in the future where I’ve decided to use it after all and I couldn’t imagine using anything else.  Maybe for my next project. But for now, I must work with WebForms and VB.NET.

Getting Unity Dependency Injection Working with ASP.NET 4.5.1

Written by Michael Earls
 Dependency Injection  DI  Unity  VB.NET

There are a lot of articles and blog posts out there about how to get Unity working with ASP.NET. After all of those, I found the best reference for doing this was the MSDN Unity documentation. However, there are a few things that you have to change in order to get it working with ASP.NET 4.5.1.

Here is a page on MSDN that describes what to do:

http://goo.gl/kOxwFo

However, in order to make this work, you will need to change the following lines in Web.config (in the element):

... other HTTP modules defined here

To use the following:

This will load the correct HttpModule that will perform the dependency injection. This HttpModule is defined on this page:

http://goo.gl/pwXH5E

Don’t forget to follow all of the steps in the above document. This includes a link to the code for extending HttpApplication to allow you to retrieve the container.

http://goo.gl/97E768

I am also using Unity dependency injection with a WebAPI that is also in this project. I am using the same custom resolver with this, so I have created a Module that contains a public method for setting up the dependencies:

Module UnityRegistrationModule Public Sub RegisterTypes(ByRef container As IUnityContainer) container.RegisterType(Of ITestDtoRepository, TestRepository)(New HierarchicalLifetimeManager()) End Sub End Module

I can then call this method from the two places where dependencies need to be set up. That gives me a single place for setting up dependencies. In VB.NET, this is a module, this could be done in C# as a static method on a public Utility class.

Here is my WebAPIConfig that calls this method…

Public Module WebApiConfig Public Sub Register(ByVal config As HttpConfiguration) ' Web API configuration and services ' Set up dependency injection with Unity Dim container As New UnityContainer() RegisterTypes(container) config.DependencyResolver = New UnityResolver(container) ' Web API routes config.MapHttpAttributeRoutes() config.Routes.MapHttpRoute( name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {.id = RouteParameter.Optional} ) End Sub End Module

I had a little trouble getting all of this to work because my custom HttpModule was not executing. This is because I did not have it configured in the Web.Config correctly. After some messing around with the namespaces and project name, I was finally able to get it working.

Here is some code that uses a dependency from within a web page (the page has a label on it named “lblTest1”):

Public Class Default Inherits Page _ Public Property _repository As ITestDtoRepository Protected Sub PageLoad(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load lblTest1.Text = _repository.GetAll(Function(x) x.Id = "5c577a7a-13c4-4391-ab80-8ff567274d2e").SingleOrDefault().Description End Sub End Class

As you can see, once you get the configuration correct, using dependencies from within an ASP.NET page is easy. Now, I can simply add a public property to the page of the desired interface and the DI resolver will inject an instance of it for me at runtime. All I have to do is code to the interface. If the required class changes in the future, all I have to do is associate the new class with the interface in the RegisterTypes() method. This is the beauty of dependency injection. I’m completely sold on this idea.

It took me a while to fully grasp the importance of DI, but now that I have, I can’t imagine life without it.

More VB posts on the way

Written by Michael Earls
 VB.NET

I recently started a new large project. Because of a client request, it will be developed entirely in VB.NET. So, from the core architecture all the way through the client code itself, everything will be in VB.NET. That means that a lot more posts on my blog will be about VB.NET topics and code samples.

Personally, I’m not all that worried, nor am I the least bit upset by this. My last projects had me maintaining legacy VB code written by someone else. This new project will be all new code written by me, so I’ll be the one to make sure it’s maintainable for the people that will follow behind me doing the maintenance.

I’m pretty excited. VB can do just about everything C# can do (no yield or anonymous methods – and I’ll miss the anonymous methods). I think the future of development is more in the framework changes and not so much in the language of choice. Microsoft is still improving VB.NET, so I don’t think they’ll abandon it any time soon.

So, look for more VB code samples and articles on this blog in the future.

It should still be relevant for .NET developers (including C# developers), as the core ideas and implementation will still be the same, it’s just a different language. I don’t think any C# developer will have trouble porting my VB samples to C# if they need the code.

Calling DataBind() on a GridView within an UpdatePanel to handle a row delete command

Written by Michael Earls
 .NET  ASP.NET  C#  VB.NET

I was working on maintaining a site that used a GridView within an UpdatePanel and had difficulties with the DataBind() call. I added a delete button (using a CommandField) to the grid and wired up the command logic to delete from a generic list that I was keeping up with. The grid was bound to the List. It just wasn’t updating the contents of the Grid when I removed records from the source.

It turns out that when I added the Delete command, I was also supposed to handle the OnRowDeleting event. I didn’t receive an error message to let me know this until I removed the UpdatePanel and tried it again. Once I added the handler for the event, it worked just fine. So I added the UpdatePanel back and everything now works as it should.

Refactoring some common VB.NET Code

Written by Michael Earls
 .NET  VB.NET

One of my tasks at work is to maintain a few VB.NET applications written before I started working here. I’ve had the opportunity to learn a lot about large websites using VB.NET.

I thought I’d take a few moments to point out some common refactoring that you can do to shorten your code when dealing with If statements and boolean assignments.

Let’s start with a line of code that appends some text to an existing string if certain conditions are true.

If chkRailCar.Checked = True Then C1 = C1 & "Y" Else C1 = C1 & "N"

This is simple enough, but it’s a bit redundant. Let’s look at another way of expressing this.

C1 &= IIf(chkRailCar.Checked, "Y", "N")

This uses the &= operator which just tells VB to append whatever follows to the variable on the left. We use IIf to determine what value to set based on the state of the checkbox.

Another common situation is using the value of a variable to determine the state of a boolean property. Here is some code to illustrate the “old” way:

If Mid(C1, 40, 1) = "Y" Then C1GridView1.Columns.ColumnByName("Age Allocated").Visible = True Else C1GridView1.Columns.ColumnByName("Age Allocated").Visible = False End If

This has some redundant code in it that is begging to be refactored. Let’s take a look at how we can accomplish this same amount of logic in a single line of code:

C1GridView1.Columns.ColumnByName("Age Allocated").Visible = Mid(C1, 40, 1) = "Y"

This tells VB to set the Visible property to the boolean value of the result of the expression to the right of the first = sign. VB will then evaluate the expression Mid(C1, 40, 1) = “Y” to come up with either True or False, which it will then assign to the Visible property. So, if Mid(C1, 40, 1) = “Y”, then the Visible property will be set to True.

Instead of using “Flags” (Dim myFlag as String = “Y”), try using Boolean values instead. “Y” and “N” are strings and must be manually converted to a boolean when setting properties. I’ve never seen a control use a “Y” or “N” as a property setting. They use True and False.

Sometimes, you need a short representation of true and false that can be easily cast to a boolean. In these cases, use an integer of 1 and 0 to represent true and false. One easy way to remember which is which is to remember that “non zero equals true”. That would also include -1 to equal true.

If you need a flag with multiple values, create an Enumeration like so:

Public Enum trafficLightEnum Red Yellow Green End Enum

Then, just use it in your If statements:

Dim lightState as trafficLightEnum lightState = trafficLightEnum.Yellow If lightState = trafficLightEnum.Red Then Vehicle.Stop() Else If lightState = trafficLightEnum.Green Then Vehicle.Go() Else If lightState = trafficLightEnum.Yellow Then Vehicle.FloorIt() End If

Check out Microsoft’s documentation on Enumerations. They are very useful.

http://msdn.microsoft.com/en-us/library/8h84wky1.aspx

VB.NET brings with it so many improvements to the Visual Basic language of days-gone-by. It’s worth it to get out there and experiment a little. Try something new. Don’t settle on what you remember doing from your old VB 6 days.