June 0902

Embedded resources in VB.Net

I’m a C# developer but at the company I work for all development is to be done using VB.Net; I like this because it means I get to (re)learn another language. I say relearn because I started out as a classical ASP developer using VBScript so much of the syntax is familiar to me, using VB.Net is a bit like putting on an warm jumper that’s been forgotten at the back of the wardrobe for a while (nice and cosy).

There are times, however, when I find myself cursing at VB. Just recently I have needed to create a server control for deployment with a number of web applications we are working on, I wanted the control to use a built in CSS so it had a basic style out-of-the-box. So I created my CSS file, put it in a Styles folder, selected the file and set it to an Embedded Resource and added a reference to it in my AssemblyInfo.vb then created a method to add a link to the CSS, something like this:

Private Sub EmbedStyles()

    Dim page = DirectCast(System.Web.HttpContext.Current.Handler, System.Web.UI.Page)
    Dim link As New HtmlLink()
    link.Href = page.ClientScript.GetWebResourceUrl(Me.GetType(), "siblings.css")
    link.Attributes.Add("type", "text/css")
    link.Attributes.Add("rel", "stylesheet")

    page.Header.Controls.Add(link)

End Sub

I am using ClientScript.GetWebResourceUrl to access the embedded CSS file. Note the 2nd parameter; it is the RootNamespace.FileName.FileExtension. Yes I know it only shows the FileName.FileExtension… weird. See I’m used to working with Namespaces in C#, the folder structure is included whereas in VB.Net I found that the RootNamspace was added along with the AssemblyName and as they were both identical I was ending up with namespaces of the format sjmdev.ProjectName.sjmdev.ProjectName – which to my mind is not intuitive and unneccessarily clutters things up. In VB to solve this I have been deleting the RootNamespace from the project so I can add my namespaces to classes as I want. This was the cause of nearly a full days head scratching and cursing. I had looked at loads of articles online which suggested my problem might be due to VB not including the folder structure I was using in the namespace, but I hadn’t considered that my project actually didn’t have a root namespace. Going right back down to it all I needed, in this case, was the name of the resource as it was being added to the very root of my project.

I added this code to my class to get the actual assembly details displayed – it may help if you need to debug or if you’re simply not sure what the full names are of your embedded resources.

'bit of debugging here
For Each resourceName As String In Me.GetType().Assembly.GetManifestResourceNames()
    Controls.Add(New LiteralControl(resourceName))
    Controls.Add(New LiteralControl("<br />"))
Next
Permalink | Comments (1)

Comments

  1. Slankepiller Denmark Slankepiller (Thursday, July 23, 2009) #

    Thanks a lot for this post

Comments are closed