Masterpages causing null exception error ASP.NET, VB

Hi EE,

Im playing with the excellent photoshow 11 app and want to use a masterpage with it. The problem Im getting is that as soon as I load it via the masterpage I get a nullreferenceerror on Server.MapPath.
From what I can figure, this is because the object does not exist in the masterpage. The masterpage only controls layout, nothing in the code behind.
How do I fix this? Im using the masterpage for the entire site, so didnt want this doing too much needlessly on pages that dont have the gallery.

Have attached the codebehind, this works nicely when displayed without the masterpage


VB code behind

Imports System.IO
Imports System.Xml
Imports System.Data
Partial Class gallery_view1
    Inherits System.Web.UI.Page
    Private count As Integer = 0
    Private thumbsize As Integer = 0
    Private imagesinrow As Integer = 0
    Private popupsize As Integer = 0
    Private borderwidth As Integer = 0
    Private description As String = ""
    Private labelselect As String = ""
    Private titleTag As String = ""
    Private cropToSquare As String = ""
    Private dpfn As String = ""
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        folders.DataSource = New DirectoryInfo(Server.MapPath("images")).GetDirectories
        folders.AutoPostBack = True
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'get the images in images-folder
        Dim dirInfo As New DirectoryInfo(Server.MapPath("images") & "\" & HttpUtility.UrlDecode(folders.SelectedValue))
        If dirInfo.Exists Then
            'overrule settings?
            initXML(Server.MapPath("images") & "\" & HttpUtility.UrlDecode(folders.SelectedValue) & "\settings.xml")
            Dim files As Array = dirInfo.GetFiles()
            Dim image As Image
            Dim link As HyperLink
            Dim table As New Table
            table.Attributes.Add("align", "center")
            Dim row As New TableRow
            Dim cell As TableCell
            'Dim delbtn As Button
            'Dim count As Integer = 0
            Dim File As System.IO.FileInfo
            For Each File In files
                Select Case LCase(File.Extension)
                    Case ".jpg", ".gif", ".png", ".jpeg", ".bmp"
                        cell = New TableCell
                        'Create a link for each image that opens a new window
                        link = New HyperLink
                        link.NavigateUrl = "showThumb.aspx?FSR=0&maxSize=" & popupsize & "&img=images/" & HttpUtility.UrlEncode(folders.SelectedValue) & "/" & File.Name
                        link.Attributes.Add("rel", "lightbox[GALLERY]")
                        'create delete button DP
                        'Dim delbtn As New Button
                        'delbtn.ID = File.Name
                        'adds the button event handler
                        'delbtn.Text = ("Delete" & count)
                        'AddHandler delbtn.Click, AddressOf button_Click
                        'create an image
                        image = New Image
                        image.ImageUrl = "showThumb.aspx?maxSize=" & thumbsize & "&img=images/" & HttpUtility.UrlEncode(folders.SelectedValue) & "/" & File.Name
                        If cropToSquare.ToString = "yes" Then
                            image.ImageUrl = image.ImageUrl & "&FSR=1"
                            image.ImageUrl = image.ImageUrl & "&FSR=0"
                        End If
                        image.BorderWidth = borderwidth
                        image.Attributes.Add("alt", File.Name)
                        'attach the image to the link
                        count = count + 1
                        If count > (imagesinrow - 1) Then
                            count = 0
                            row = New TableRow
                        End If
                        link = Nothing
                        image = Nothing
                End Select
            files = Nothing
            dirInfo = Nothing
        End If
        'assign values
        LBdescription.Text = description
        LBselect.Text = labelselect
    End Sub
    Private Sub initXML(ByVal filepath As String)
        If File.Exists(filepath) Then
            On Error Resume Next
            Dim xml As New XmlDocument
            thumbsize = xml.GetElementsByTagName("thumbsize")(0).InnerText
            imagesinrow = xml.GetElementsByTagName("imagesinrow")(0).InnerText
            popupsize = xml.GetElementsByTagName("popupsize")(0).InnerText
            borderwidth = xml.GetElementsByTagName("borderwidth")(0).InnerText
            cropToSquare = xml.GetElementsByTagName("cropToSquare")(0).InnerText
            description = xml.GetElementsByTagName("description")(0).InnerText
            labelselect = xml.GetElementsByTagName("labelselect")(0).InnerText
            titleTag = xml.GetElementsByTagName("title")(0).InnerText
            xml = Nothing
            On Error GoTo 0
        End If
    End Sub
    '    Sub button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'Dim sButton As String = CType(sender, Button).ID
    ' MessageBox.Text = "The Button " & sButton & "was clicked."
    'Dim FileToDelete As String
    ' Set full path to file 
    'FileToDelete = "C:/"
    '   FileToDelete = Server.MapPath("~/images/" & HttpUtility.UrlEncode(folders.SelectedValue) & "/" & sButton)
    '  MessageBox.Text = FileToDelete
    ' Delete a file
    ' File.Delete(FileToDelete)

    'End Sub
End Class

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Is it necessary to execute those three lines of code in the Page_PreInit subroutine? I find that when I use masterpages and I call something in a page that is using a masterpage, I also get nullpointer errors. I think some object only get initialized after all page components (that includes the masterpage) get loaded. Mostly I cover up this problem by putting that code in the Page_Load subroutine instead, because that subroutine only gets triggered after everything is loaded.

Probably there are more elegant ways to fix this, though.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gingermolemanAuthor Commented:
Hi Juamez,

Its all helps!  Its not my code (got it from apart from a button I added to delete the photos (commented all that out in the snippet).
Will give your suggestion a try tho
gingermolemanAuthor Commented:
Hi Juamez,

This initially gave me a form error but I fixed that and your suggestion was a good one.


Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Glad to hear that!
gingermolemanAuthor Commented:
Small issue left behind, multi folder function gets killed by moving the code here (makes sense, the postback forces this to kick off again so default folder gets set again). Think Im going to end up laying out the page manually to retain this :(
Another shot in the dark: can't you move the folder object to the Master Page, let it execute it's code in the Master Page's Preinit subroutine, add a property for this object in the Master Page and in the Page_Load subroutine of the codebehind you just posted here call that property.

The way to call a masterpage is to call the Page's Masterpage and cast it to the specific class of the Master Page that is used.

For example: (provided your Master Page is of class Generalmaster)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     folder = ctype(this.Master,Generalmaster).Folder
gingermolemanAuthor Commented:
again, its all good to know that little bit more. I'll give this a try though I dont truly understand you (not your words, the last bit of 'serious' coding I did was as a kid on the 128k speccy!)

I get what your saying (let the master page handle that part then just pull through a var)
Im not entirely certain how to do this. If i create the page_preint  in the master page I get "folders not defined", should I declare folders? Ive assumed its part of DirectoryInfo up till now.
The variable Folders might be defined in the designer back-end of your page. If you use Visual Studio, you can right click the variable (in this case "folders") and then select from the right-click-menu: Go To Definition. This might help you understand what that variable really is, and if it is doable to move it to the Master Page.

I'm not sure if this will work though, I'm all about trial & error and poking around in the dark.
gingermolemanAuthor Commented:
no probs, im all for shooting in the dark! Thanks for the pointers, will post back how I get on, likely much later, spurs are on!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.