CodeVerge.Net Beta


   Explore    Item Entry   Register  Login  
Microsoft News
Asp.Net Forums
IBM Software
Borland Forums
Adobe Forums
Novell Forums

ASP.NET Web Hosting – 3 Months Free!



Zone: > NEWSGROUP > Asp.Net Forum > general_asp.net.master_pages_themes_and_navigation_controls Tags:
Item Type: NewsGroup Date Entered: 2/1/2006 2:22:57 PM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
(NR, 0)
XPoints: N/A Replies: 4 Views: 71 Favorited: 0 Favorite
Can Reply:  No Members Can Edit: No Online: Yes
5 Items, 1 Pages 1 |< << Go >> >|
codispdp
Asp.Net User
Building sitemap from Database null value error using iif2/1/2006 2:22:57 PM

0/0

I am building a sitemap from a sql database and using IIF to check for null values but it doesn't seem to be evaluating it correctly.

Dim parentnode As SiteMapNode = nodes(Microsoft.VisualBasic.IIf(reader.IsDBNull(parent), Nothing, reader.GetInt32(parent)))

When I use the immediate window the isdbnull returns true but based on the error I assume it is executing the GetInt32(parent).

I receive the following error:

System.Data.SqlTypes.SqlNullValueException was unhandled by user code
  Message="Data is Null. This method or property cannot be called on Null values."
  Source="System.Data"
  StackTrace:
       at System.Data.SqlClient.SqlBuffer.get_String()
       at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
       at SqlSiteMapProvider.BuildSiteMap() in D:\Documents and Settings\jzkl6w\My Documents\Visual Studio 2005\WebSites\MyApps\App_Code\SqlSiteMapProvider.vb:line 52
       at SqlSiteMapProvider.GetRootNodeCore() in D:\Documents and Settings\jzkl6w\My Documents\Visual Studio 2005\WebSites\MyApps\App_Code\SqlSiteMapProvider.vb:line 95
       at System.Web.SiteMapProvider.get_RootNode()
       at System.Web.UI.WebControls.SiteMapDataSource.GetNodes()
       at System.Web.UI.WebControls.SiteMapDataSource.GetTreeView(String viewPath)
       at System.Web.UI.WebControls.SiteMapDataSource.GetHierarchicalView(String viewPath)
       at System.Web.UI.HierarchicalDataSourceControl.System.Web.UI.IHierarchicalDataSource.GetHierarchicalView(String viewPath)
       at System.Web.UI.WebControls.HierarchicalDataBoundControl.GetData(String viewPath)
       at System.Web.UI.WebControls.TreeView.DataBindNode(TreeNode node)
       at System.Web.UI.WebControls.TreeView.PerformDataBinding()
       at System.Web.UI.WebControls.HierarchicalDataBoundControl.PerformSelect()
       at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
       at System.Web.UI.WebControls.TreeView.DataBind()
       at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
       at System.Web.UI.WebControls.TreeView.OnPreRender(EventArgs e)
       at System.Web.UI.Control.PreRenderRecursiveInternal()
       at System.Web.UI.Control.PreRenderRecursiveInternal()
       at System.Web.UI.Control.PreRenderRecursiveInternal()
       at System.Web.UI.Control.PreRenderRecursiveInternal()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Here is my class:

Imports System

Imports System.Web

Imports System.Data.SqlClient

Imports System.Collections.Specialized

Imports System.Configuration

Imports System.Collections.Generic

Imports System.Runtime.CompilerServices

Imports Microsoft.VisualBasic

Imports System.Web.StaticSiteMapProvider

Public Class SqlSiteMapProvider

Inherits StaticSiteMapProvider

Shared ReadOnly _errmsg1 As String = "Missing connectionStringName attribute"

Shared ReadOnly _errmsg2 As String = "Duplicate node ID"

Private _root As SiteMapNode

Private _connect As String

Public Overloads Overrides Sub Initialize(ByVal name As String, ByVal attributes As NameValueCollection)

MyBase.Initialize(name, attributes)

If attributes Is Nothing Then

Throw New ConfigurationErrorsException(_errmsg1)

End If

_connect = attributes("connectionStringName")

If String.IsNullOrEmpty(_connect) Then

Throw New ConfigurationErrorsException(_errmsg1)

End If

End Sub

Public Overloads Overrides Function BuildSiteMap() As SiteMapNode

' Return immediately if this method has been called before

If Not (_root Is Nothing) Then

Return _root

End If

Dim nodes As Dictionary(Of Integer, SiteMapNode) = New Dictionary(Of Integer, SiteMapNode)

' Query the database for site map nodes

Dim connection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings(_connect).ConnectionString)

Try

connection.Open()

Dim command As SqlCommand = New SqlCommand("SELECT ID, Title, Description, Url, Roles, Parent FROM SiteMap ORDER BY ID", connection)

Dim reader As SqlDataReader = command.ExecuteReader

Dim id As Integer = reader.GetOrdinal("ID")

Dim url As Integer = reader.GetOrdinal("Url")

Dim title As Integer = reader.GetOrdinal("Title")

Dim desc As Integer = reader.GetOrdinal("Description")

Dim roles As Integer = reader.GetOrdinal("Roles")

Dim parent As Integer = reader.GetOrdinal("Parent")

If reader.Read Then

_root = New SiteMapNode(Me, reader.GetInt32(id).ToString, Microsoft.VisualBasic.IIf(reader.IsDBNull(url), Nothing, reader.GetString(url)), reader.GetString(title), Microsoft.VisualBasic.IIf(reader.IsDBNull(desc), Nothing, reader.GetString(desc)))

If Not reader.IsDBNull(roles) Then

Dim rolenames As String = reader.GetString(roles).Trim

If Not String.IsNullOrEmpty(rolenames) Then

Dim rolelist As String() = rolenames.Split(New Char() {","c, ";"c}, 512)

_root.Roles = rolelist

End If

End If

If _root.Roles Is Nothing Then

_root.Roles = New String() {"*"}

End If

If nodes.ContainsKey(reader.GetInt32(id)) Then

Throw New ConfigurationErrorsException(_errmsg2)

End If

nodes.Add(reader.GetInt32(id), _root)

AddNode(_root, Nothing)

While reader.Read

Dim node As SiteMapNode = New SiteMapNode(Me, reader.GetInt32(id).ToString, Microsoft.VisualBasic.IIf(reader.IsDBNull(url), Nothing, reader.GetString(url)), reader.GetString(title), Microsoft.VisualBasic.IIf(reader.IsDBNull(desc), Nothing, reader.GetString(desc)))

If Not reader.IsDBNull(roles) Then

Dim rolenames As String = reader.GetString(roles).Trim

If Not String.IsNullOrEmpty(rolenames) Then

Dim rolelist As String() = rolenames.Split(New Char() {","c, ";"c}, 512)

node.Roles = rolelist

End If

End If

Dim parentnode As SiteMapNode = nodes(Microsoft.VisualBasic.IIf(reader.IsDBNull(parent), Nothing, reader.GetInt32(parent)))

If node.Roles Is Nothing Then

node.Roles = parentnode.Roles

End If

If nodes.ContainsKey(reader.GetInt32(id)) Then

Throw New ConfigurationErrorsException(_errmsg2)

End If

nodes.Add(reader.GetInt32(id), node)

AddNode(node, parentnode)

End While

End If

Finally

CType(connection, IDisposable).Dispose()

End Try

Return _root

End Function

Protected Overloads Overrides Function GetRootNodeCore() As SiteMapNode

BuildSiteMap()

Return _root

End Function

End Class

 

Giorgio
Asp.Net User
Re: Building sitemap from Database null value error using iif5/3/2006 3:17:04 PM

0/0

Hi,

Did you managed to get this right?
Can I see an example of your sitemenu with web.config and the menu control on the page?
It would be a great help.

Thanks
Giorgio
eoghan
Asp.Net User
Re: Building sitemap from Database null value error using iif4/5/2007 3:49:25 PM

0/0

Hi codispdp,

I was having the same problem with a line like this: 

Dim parentnode As SiteMapNode = nodes(Microsoft.VisualBasic.IIf(reader.IsDBNull(parent), Nothing, reader.GetInt32(parent)))

 

The problem, I think is that the IIf method evaluates the false portion [i.e. reader.GetInt32(parent) ] even if the expression [i.e. reader.IsDBNull(parent)]evaluates to True.

A solutions is to refactor to 

 Dim parentnode as SiteMapNode

if reader.IsDBNull(parent) then

    parentnode = nothing

else

    parentnode = nodes(reader.GetInt32(parent))

end if

 

 

I haven't tested the code but hope it will work
 

RhythmAddict112
Asp.Net User
Re: Building sitemap from Database null value error using iif8/22/2007 3:04:47 PM

0/0

Pretty sure this thread isn't active...but anyone interested may want to check this post out, as it's got a functional VB.NET sqlSiteMapProvider..

http://geekswithblogs.net/SanjayU/archive/2007/08/07/114455.aspx

 
 

gammash
Asp.Net User
Re: Building sitemap from Database null value error using iif10/3/2007 5:47:15 PM

0/0

This the VB.NET provided by Jeff Prosise

http://www.wintellect.com/cs/DasBlogContentBinary/SqlSiteMapProvider.zip

Here is the contents of the above link:

Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Collections.Generic
Imports System.Configuration.Provider
Imports System.Security.Permissions
Imports System.Data.Common
Imports System.Data
Imports System.Web.Caching

<SqlClientPermissionAttribute(SecurityAction.Demand, Unrestricted:=True)> _
Public Class SqlSiteMapProvider
    Inherits StaticSiteMapProvider

    Private _errmsg1 As String = "Missing node ID"
    Private _errmsg2 As String = "Duplicate node ID"
    Private _errmsg3 As String = "Missing parent ID"
    Private _errmsg4 As String = "Invalid parent ID"
    Private _errmsg5 As String = "Empty or missing connectionStringName"
    Private _errmsg6 As String = "Missing connection string"
    Private _errmsg7 As String = "Empty connection string"
    Private _errmsg8 As String = "Invalid sqlCacheDependency"
    Private _cacheDependencyName As String = "__SiteMapCacheDependency"
    Private _connect As String ' Database connection string
    Private _database, _table As String ' Database info for SQL Server 7/2000 cache dependency
    Private _2005dependency As Boolean = False ' Database info for SQL Server 2005 cache dependency
    Private _indexID, _indexTitle, _indexUrl, _indexDesc, _indexRoles, _indexParent As Integer
    Private _nodes As Dictionary(Of Integer, SiteMapNode) = New Dictionary(Of Integer, SiteMapNode)(16)
    Private _lock As New Object()
    Private _root As SiteMapNode


    Public Overrides Sub Initialize(ByVal name As String, ByVal config As NameValueCollection)
        ' Verify that config isn't null
        If config Is Nothing Then
            Throw New ArgumentNullException("config")
        End If
        ' Assign the provider a default name if it doesn't have one
        If String.IsNullOrEmpty(name) Then
            name = "SqlSiteMapProvider"
        End If
        ' Add a default "description" attribute to config if the
        ' attribute doesn?t exist or is empty
        If String.IsNullOrEmpty(config("description")) Then
            config.Remove("description")
            config.Add("description", "SQL site map provider")
        End If

        ' Call the base class's Initialize method
        MyBase.Initialize(name, config)

        ' Initialize _connect
        Dim connect As String = config("connectionStringName")

        If String.IsNullOrEmpty(connect) Then
            Throw New ProviderException(_errmsg5)
        End If
        config.Remove("connectionStringName")

        If WebConfigurationManager.ConnectionStrings(connect) Is Nothing Then
            Throw New ProviderException(_errmsg6)
        End If
        _connect = WebConfigurationManager.ConnectionStrings(connect).ConnectionString

        If String.IsNullOrEmpty(_connect) Then
            Throw New ProviderException(_errmsg7)
        End If
        ' Initialize SQL cache dependency info
        Dim dependency As String = config("sqlCacheDependency")

        If Not String.IsNullOrEmpty(dependency) Then
            If String.Equals(dependency, "CommandNotification", StringComparison.InvariantCultureIgnoreCase) Then
                SqlDependency.Start(_connect)
                _2005dependency = True
            Else
                ' If not "CommandNotification", then extract database and table names
                Dim info As String() = dependency.Split(New Char() {":"c})
                If info.Length <> 2 Then
                    Throw New ProviderException(_errmsg8)
                End If
                _database = info(0)
                _table = info(1)
            End If

            config.Remove("sqlCacheDependency")
        End If

        ' SiteMapProvider processes the securityTrimmingEnabled
        ' attribute but fails to remove it. Remove it now so we can
        ' check for unrecognized configuration attributes.
        If Not (config("securityTrimmingEnabled") Is Nothing) Then
            config.Remove("securityTrimmingEnabled")
        End If
        ' Throw an exception if unrecognized attributes remain
        If config.Count > 0 Then
            Dim attr As String = config.GetKey(0)
            If Not String.IsNullOrEmpty(attr) Then
                Throw New ProviderException("Unrecognized attribute: " + attr)
            End If
        End If
    End Sub 'Initialize

    Public Overrides Function BuildSiteMap() As SiteMapNode
        SyncLock _lock
            ' Return immediately if this method has been called before
            If Not (_root Is Nothing) Then
                Return _root
            End If
            ' Query the database for site map nodes
            Dim connection As New SqlConnection(_connect)

            Try
                Dim command As New SqlCommand("proc_GetSiteMap", connection)
                command.CommandType = CommandType.StoredProcedure

                ' Create a SQL cache dependency if requested
                Dim dependency As SqlCacheDependency = Nothing

                If _2005dependency Then
                    dependency = New SqlCacheDependency(command)
                Else
                    If Not String.IsNullOrEmpty(_database) And Not String.IsNullOrEmpty(_table) Then
                        dependency = New SqlCacheDependency(_database, _table)
                    End If
                End If
                connection.Open()
                Dim reader As SqlDataReader = command.ExecuteReader()
                _indexID = reader.GetOrdinal("ID")
                _indexUrl = reader.GetOrdinal("Url")
                _indexTitle = reader.GetOrdinal("Title")
                _indexDesc = reader.GetOrdinal("Description")
                _indexRoles = reader.GetOrdinal("Roles")
                _indexParent = reader.GetOrdinal("Parent")

                If reader.Read() Then
                    ' Create the root SiteMapNode and add it to the site map
                    _root = CreateSiteMapNodeFromDataReader(reader)
                    AddNode(_root, Nothing)

                    ' Build a tree of SiteMapNodes underneath the root node
                    While reader.Read()
                        ' Create another site map node and add it to the site map
                        Dim node As SiteMapNode = CreateSiteMapNodeFromDataReader(reader)
                        AddNode(node, GetParentNodeFromDataReader(reader))
                    End While

                    ' Use the SQL cache dependency
                    If Not (dependency Is Nothing) Then
                        HttpRuntime.Cache.Insert(_cacheDependencyName, New Object(), dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, New CacheItemRemovedCallback(AddressOf OnSiteMapChanged))
                    End If
                End If
            Finally
                connection.Close()
            End Try

            ' Return the root SiteMapNode
            Return _root
        End SyncLock
    End Function 'BuildSiteMap


    Protected Overrides Function GetRootNodeCore() As SiteMapNode
        SyncLock _lock
            BuildSiteMap()
            Return _root
        End SyncLock
    End Function 'GetRootNodeCore


    ' Helper methods
    Private Function CreateSiteMapNodeFromDataReader(ByVal reader As DbDataReader) As SiteMapNode
        ' Make sure the node ID is present
        If reader.IsDBNull(_indexID) Then
            Throw New ProviderException(_errmsg1)
        End If
        ' Get the node ID from the DataReader
        Dim id As Integer = reader.GetInt32(_indexID)

        ' Make sure the node ID is unique
        If _nodes.ContainsKey(id) Then
            Throw New ProviderException(_errmsg2)
        End If
        ' Get title, URL, description, and roles from the DataReader
        Dim title As String = Nothing
        If Not reader.IsDBNull(_indexTitle) Then
            title = reader.GetString(_indexTitle).Trim()
        End If

        Dim url As String = Nothing
        If Not reader.IsDBNull(_indexUrl) Then
            url = reader.GetString(_indexUrl).Trim()
        End If

        Dim description As String = Nothing
        If Not reader.IsDBNull(_indexDesc) Then
            description = reader.GetString(_indexDesc).Trim()
        End If

        Dim roles As String = Nothing
        If Not reader.IsDBNull(_indexRoles) Then
            roles = reader.GetString(_indexRoles).Trim()
        End If

        ' If roles were specified, turn the list into a string array
        Dim rolelist As String() = Nothing
        If Not String.IsNullOrEmpty(roles) Then
            rolelist = roles.Split(New Char() {","c, ";"c}, 512)
        End If
        ' Create a SiteMapNode
        Dim node As New SiteMapNode(Me, id.ToString(), url, title, description, rolelist, Nothing, Nothing, Nothing)

        ' Record the node in the _nodes dictionary
        _nodes.Add(id, node)

        ' Return the node       
        Return node
    End Function 'CreateSiteMapNodeFromDataReader


    Private Function GetParentNodeFromDataReader(ByVal reader As DbDataReader) As SiteMapNode
        ' Make sure the parent ID is present
        If reader.IsDBNull(_indexParent) Then
            Throw New ProviderException(_errmsg3)
        End If
        ' Get the parent ID from the DataReader
        Dim pid As Integer = reader.GetInt32(_indexParent)

        ' Make sure the parent ID is valid
        If Not _nodes.ContainsKey(pid) Then
            Throw New ProviderException(_errmsg4)
        End If
        ' Return the parent SiteMapNode
        Return _nodes(pid)
    End Function 'GetParentNodeFromDataReader


    Sub OnSiteMapChanged(ByVal key As String, ByVal item As Object, ByVal reason As CacheItemRemovedReason)
        SyncLock _lock
            If key = _cacheDependencyName And reason = CacheItemRemovedReason.DependencyChanged Then
                ' Refresh the site map
                Clear()
                _nodes.Clear()
                _root = Nothing
            End If
        End SyncLock
    End Sub 'OnSiteMapChanged
End Class 'SqlSiteMapProvider 

 

5 Items, 1 Pages 1 |< << Go >> >|


Free Download:


Web:
Building sitemap from Database null value error using iif - ASP ... Building sitemap from Database null value error using iif. Last post 10-03-2007 1:47 PM by gammash. 4 replies. Sort Posts: ...
VAL file out of date - borland.public.bde - fix error problem ... master page sites and cookies · call function in usercontrol through masterpage ? building sitemap from database null value error using iif ...
Microsoft Access / VBA Forum Page 6 - Bytes Site Map Page 6-Microsoft Office Access database and VBA - Ask questions about microsoft ... and null value issue · Open form in a New Window using a command button ...
Error "dbnul"l if a field contains a null value during routine This routine bombs out if the field fldMfrnumOrif contains a null or during the looping. Error message when a value in...
Microsoft Access / VBA Forum Page 4 - Bytes Site Map Page 4-Microsoft Office Access database and VBA - Ask questions about microsoft ... Getting Error 3014 - how to tell what vversion of "Jet" I am using? ...
MSDN Visual Basic Language Why can't I use Sum(NZ(field,0)) in a ... http://www.builderau.com.au/architect/database/soa/Avoid-Null-value-conflicts-in -Access-SQL-Server/0,339024547,320274689,00.htm ...
CodeGuru: Using Gantt Diagrams in Windows Applications If a null value is supplied for this parameter, a default function is used. ... in a Database or to initialize the Gantt diagram with meaningful data. ...
InformIT: Building a Visual FoxPro Application for SQL Server ... However, if you're using SQL Server or an XML Web Service, you're only halfway there. .... I'm responsible for inserting a unique value into the table. ...
Fall In Love with Visual Basic All Over Again in Visual Studio 2008 This is a great enhancement for anyone who uses types that can be set to NULL. It prevents the overhead and error-prone nature of using state variables to ...
CodeProject: Ader Template Engine. Free source code and ... isnull(obj) - tests whether obj is null . not(boolvalue) - returns not (!) of boolean value. iif(booleanExpression, iftruevalue, iffalsevalue) - same as ...




Search This Site:










stored procedure

.net faq's needed..

how-to: database from vwd to shared host

how-to: reliably trap a web client disconnect!

how to move databases between computers that are running sql server

custom columns are not appearing while uploading documents in document library

cultureinfo, currentculture, currentuiculture stuff

update/delete not working in data controls

error "allowcustompaging must be true and virtualitemcount must be set for a datagrid..."

searching for dynamically creating user web control anticipated problems

searching sql database with stored procedure vs searching through a dataset

validations

why am i not able to access the context objects in my code?

custom paging without stored procedures

tracking users online

how to: accessing config file mail settings programmatically

birthday remainder mail

adding controls to asp.net page at runtime

validation

scheduling code and/or web requests

transfer files between production servers

href target="_tab"

running asp site in xp

create blog on asp.net website

subtracting 2 times

best asp.net faq for interviews

changeing default browser .net2003

javascript working in ie but not in firefox

send a mail with attachment

server error in '/' application.

  Privacy | Contact Us
All Times Are GMT