Function result in an array of own structure - asp.net

In the Gen class file I have got this structure:
Public Structure StructElements
Public ID As Integer
Public Name As String
End Structure
An then this function:
Public Function FillElements(_param As String, count As Integer) As StructElements
Dim i As Integer = 0
Dim myConn As SqlConnection = New SqlConnection
Dim myCmd As SqlCommand
Dim myReader As SqlDataReader
myConn.ConnectionString = sc.ConfigurationManager.ConnectionStrings("sidConnectionString").ConnectionString
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT * FROM " & _param
Select Case _param
Case = "Scopes"
Dim Scope(count) As StructElements
myConn.Open()
myReader = myCmd.ExecuteReader()
While myReader.Read
Scope(i).ID = myReader.Item(0)
Scope(i).Name = myReader.Item(1).ToString
i += 1
End While
myReader.Close()
myCmd.Dispose()
myConn.Close()
myConn.Dispose()
Return Scope
...
End Function
Then in the edit.aspx codebehind I have:
Public Class edit
...
Public istGen = New Gen()
...
Public iScopes As Integer
Public Scope(iScopes) As StructElements
...
Private Sub edit_Init(sender As Object, e As EventArgs) Handles Me.Init
...
iScopes = istGen.CountElements("Scopes") - 1
ReDim Scope(iScopes)
Scope = istGen.FillElements("Scopes", iScopes)
...
End Sub
End Class
This is the error I get:
Value of type 'Gen.StructElements()' cannot be converted to 'Gen.StructElements'.
I have figured out the problem is with the "Return Scope" of the FillElements function since it's expecting as an output a StructElements and not an array of StructElements (that's what the Scope variable is). How should I change my code in order for the function output to be an array of StructElements?
I have tried to look for an answer on the web but didn't find much. Someone was suggesting to use lists instead of arrays, but that would request to heavily refurbish my code and project, so if there is an easy way to do it I would strongly prefer it.
Thanks in advance for your support.
Regards.

Related

Webservice having trouble pass back to client

I having trouble passing back the result which is multiple row getting from MS-SQL2012 to client. I have tried to google up but still not find the solution. Since I'm new in .NET and this is my first webservice, required an assistant to solve my problem or suggest any better solution.
Result need to pass back to client
Public Class Service1
Inherits System.Web.Services.WebService
Public Class Dealer
Public IDNo, ICFound, POFound As String
End Class
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As String
Dim mylist As List(Of String()) = records.ToList()
Dim datarow As String = ""
Dim result As String = "Done"
For i As Integer = 0 To mylist.Count - 1
Dim m As String() = mylist(i)
For j As Integer = 0 To m.Length - 1
datarow += m(j) + " "
Next
Next
//Insert the array into the database.
Dim objDealer As New Dealer
Dim myConnString = System.Configuration.ConfigurationManager.AppSettings("MM_CONNECTION_STRING_iPRIS")
Dim myConnection1 = New SqlConnection(myConnString)
Dim myCommand = New SqlCommand()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Connection = myConnection1
myCommand.CommandText = "DailyCheckDealer"
myCommand.Parameters.Add("#DataRow", SqlDbType.VarChar, 8000).Value = datarow
myConnection1.Open()
myCommand.ExecuteNonQuery()
myConnection1.Close()
// Get the record(s) after processing and return it back to client
Dim myConnection2 = New SqlConnection(myConnString)
Dim objComm As New SqlCommand("Select IDNo, IDFound, POFound From DailyDealerCheck Order By IDNo", myConnection2)
myConnection2.Open()
Dim sdr As SqlDataReader = objComm.ExecuteReader()
If sdr.Read() Then
objDealer.IDNo = sdr("IDNo").ToString()
objDealer.ICFound = sdr("IDFound").ToString()
objDealer.POFound = sdr("POFound").ToString()
End If
myConnection2.Close()
Return objDealer
End Function
End Class
You're getting your data and putting it into objDealer which is an instance of type Dealer. You then actually have Return objDealer
Clrearly you want to return an instance of Dealer. However your function is declared as returning a string. That shouldn't even compile! Change the declaration to this:
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As Dealer
That will allow it to return a Dealer not a string.
EDIT - to return more than one Dealer:
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As List(Of Dealer)
' code left out
Dim myConnection2 = New SqlConnection(myConnString)
Dim objComm As New SqlCommand("Select IDNo, IDFound, POFound From DailyDealerCheck Order By IDNo", myConnection2)
' Create list of Dealers for return
Dim dealerList as New List(Of Dealer)
myConnection2.Open()
Dim sdr As SqlDataReader = objComm.ExecuteReader()
If sdr.Read() Then
objDealer.IDNo = sdr("IDNo").ToString()
objDealer.ICFound = sdr("IDFound").ToString()
objDealer.POFound = sdr("POFound").ToString()
' Add the latest to the list
dealerList.Add(objDealer)
End If
myConnection2.Close()
' Return list of dealers
Return dealerList
End Function

Handle DBNull in an object initializer

In my asp.net web service, I have an object class which get data from database, but I counter the following problem when some data is null in database:
(1) If I don't handle the NULL value in database and use the code as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
.Address = dr("ADDRESS") _
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.
(2) if I handle the NULL in database as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
If dr("ADDRESS") = System.DBNull.Value Then
.Address = ""
Else
.Address = dr("ADDRESS") _
End if
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
Compiler Error Message: BC30985: Name of field or property being initialized in an object initializer must start with '.'.
I want to know how to handle the DBNull value for string and date in an object initializer.
You can use Convert.ToString
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim registerDate As Date
If Date.TryParse(Convert.ToString(dr("REGISTER_DATE")), registerDate ) = False Then
'Do what you need to do if the cell is not a valid date time value
End If
detail = New customerInfo() With { _
.CustomerID = Convert.ToString(dr("CUSTOMER_ID")), _
.CustomerName = Convert.ToString(dr("CUSTOMER_NAME")), _
.RegisterDate = registerDate.ToString("dd/MM/yyyy"), _
.Address = Convert.ToString(dr("ADDRESS"))
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Edited based on OP's comment below.
While the other methods would work, I think a re-usable extension method with generics support would be ideal.
You can pass the work off to the extension method and check if the value is equal to the value of DBNull.Value
Public Module DataRowExtensions
<System.Runtime.CompilerServices.Extension>
Public Function GetValueOrDefault(Of TExpectedType)(dr As DataRow, propertyName As String) As TExpectedType
If DBNull.Value.Equals(dr(propertyName)) Then
Return Nothing
End If
Return DirectCast(dr(propertyName), TExpectedType)
End Function
End Module
You can see this DotNetFiddle to see it in action with various data types.
Do make note that the extension method Field<T> does exist and is similar, but it doesn't handle DBNull values.
You can't use an if statement inside an object initializer like that.
You have to instantiate the object, then set the properties in separate lines.
detail = New customerInfo()
'Then in separate lines, populate the properties individually
If dr("ADDRESS") = System.DBNull.Value Then
detail.Address = ""
Else
detail.Address = dr("ADDRESS")

Value of type ... cannot be converted to

I keep receiving the following error whenever I try to run my code. Are there any suggestions on what may be causing me to not be able to convert? It seems as though both types are the same, so I'm a little confused on this one.
Value of type 'System.Collections.Generic.List(Of CVE)' cannot be converted to 'System.Collections.Generic.List(Of CVE)'
Error is occurring here:
Dim cveList As List(Of CVE)
cveList = CVERepository.GetInstance.ReadAllCVEs
Here's the CVERepository class:
Public Class CVERepository
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance As CVERepository
Get
Static Instance As CVERepository = New CVERepository
Return Instance
End Get
End Property
Public Function ReadAllCVEs() As List(Of CVE)
Dim objAdapter As OleDb.OleDbDataAdapter
Dim dtCVE As New DataTable()
Dim strSQL As String
Dim strConn As String
Dim dvCVE As DataView
strConn = ConnectStringBuild()
strSQL = "Select * From CVE"
objAdapter = New OleDb.OleDbDataAdapter(strSQL, strConn)
objAdapter.Fill(dtCVE)
dvCVE = dtCVE.DefaultView
Dim cveList As New List(Of CVE)
'Put it into an object list to make it more managable.
For index = 0 To dvCVE.Count - 1
Dim cve As New CVE
cve.ID = dvCVE(index)("CVEID")
cve.PublishedDate = dvCVE(index)("PublishedDate")
cve.Availability = dvCVE(index)("Availability")
cve.CVSSScore = dvCVE(index)("CVSSScore")
cve.Confidentiality = dvCVE(index)("Confidentiality")
cve.Integrity = dvCVE(index)("Integrity")
cve.Summary = dvCVE(index)("Summary")
cveList.Add(cve)
Next
Return cveList
End Function
Public Shared Function ConnectStringBuild() As String
'Grabbing connection string from web.config
Return System.Configuration.ConfigurationManager.ConnectionStrings("CVEConnectionString").ConnectionString
End Function
End Class
Any suggestion on the error?
just a little change
Dim cveList As List(Of CVE)
cveList.AddRange(CVERepository.GetInstance.ReadAllCVEs)

Returning multiple values from a function in an parcial class in VB

Hi Please can someone show me how to return multiple values from a function? I have my function in a seperate file within App_Code and here it is:
Public Function GetQuoteStatus(ByVal QuoteID As String) As String
Dim quoteStatus As String
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = ConfigurationManager.AppSettings("quotingSystemConnectionString")
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Status FROM Quote WHERE QuoteID =" & QuoteID & ";"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
quoteStatus = lrd("Status")
End While
Catch ex As Exception
Finally
con.Close()
End Try
Return quoteStatus
End Function
To get the returned quoteStatus from within another vb file in my site I would normally use:
Dim statusHelper As New quoteStatusHelper()
Dim quoteStatus As String = statusHelper.GetQuoteStatus("QuoteID")
However this is all good and well for one returned value but what If I wanted to return multiple values... How do I access them?
Many thanks!
You could use
Public Function GetQuoteStatus(ByVal QuoteID As String) As String()
This let you return a string array, so there is no limit to data you can have.
The cons is you have to parse the array.
You could even use
Public Function GetQuoteStatus(ByVal QuoteID As String,
Byref Second As String) As String
This let you return a string as result and set the value of another var (Second); you can use more than one Byref variables to return multiple values...
The cons is that you have to statically declare your function and modifiy all previous calls. In this case the use of refactoring is reccomended!
EDITED:
You could even return a class for example.
Declare a class that fits your needs (with all the fields, getters, setters and constructors) and inside your function you could create an instance of that class, fill every field and return this class.
Easy to implement, easy to use.
EDITED AGAIN:
Public Class MyClass
Public Property Val1 As String
Public Property Val2 As String
Public Property Val3 As String
Public Sub New(ByVal newVal1 As String, ByVal newVal2 As String, ByVal newVal3 As String)
Val1 = newVal1
Val2 = newVal2
Val3 = newVal3
End Sub
End Class
Public Function GetInfo() As MyClass
Dim mc As New MyClass("test1", "test2", "test3")
Return mc
End Function
You may return multiple values using ByRef and arrays (see #Marco post). You may also return/pass an object for your purpose.
For instance,
Public Class Info
Public Property No As Integer
Public Property Name As String
End Class
....
Public Function GetInfo() As Info
Dim inf As New Info
inf.No = 10
inf.Name = "A"
Return inf
End Function
....
I believe that the "correct/best" way to deal with a single function that needs to return a couple of discrete (typically primitive) types is a Tuple(Of T1, T2, T3, T4, T5, T6, T7, TRest).
Something like this
Public Function MyExampleMethod() As Tuple(Of String, Integer, Guid)
Return New Tuple(Of String, Integer, Guid)("Value1", 2, Guid.NewGuid)
End Function

How to hide a node from appearing on menu not on breadcrumb (using SqlSiteMapProvider)

I am using wicked code sqlsitemapprovider or it's VB version. Most of the things are going OK! But when I wanted to hide some of the nodes from appearing on menu while staying shown on sitemappath I cannot figure it out. I tried to change the sqlsitemapprovider code but was unsuccessfull. I have found David Sussman's (from sp.net) answer. but it was for a .sitemap file. So how can I manage to do the same with the sql sitemap provider mentioned above.
I added a column named visible to my SiteMap table it's type is bit and then I have done these changes (Sorry for such long code):
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
''' <summary>
''' Summary description for SqlSiteMapProvider
''' </summary>
<SqlClientPermission(SecurityAction.Demand, Unrestricted:=True)> _
Public Class SqlSiteMapProvider
Inherits StaticSiteMapProvider
Private Const _errmsg1 As String = "Basamak no bulunamadı"
Private Const _errmsg2 As String = "Çift Basamak No"
Private Const _errmsg3 As String = "Üst Basamak Bulunamadı"
Private Const _errmsg4 As String = "Hatalı Üst Basamak"
Private Const _errmsg5 As String = "Bağlantı dizesi bulunamadı veya boş"
Private Const _errmsg6 As String = "Bağlantı dizesi bulunamadı"
Private Const _errmsg7 As String = "Bağlantı dizesi boş"
Private Const _errmsg8 As String = "Hatalı sqlCacheDependency"
Private Const _cacheDependencyName As String = "__SiteMapCacheDependency"
Private _connect As String
'Database connection string
Private _database As String, _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 As Integer, _indexTitle As Integer, _indexUrl As Integer, _indexDesc As Integer, _indexRoles As Integer, _indexParent As Integer, _indexvisible As Boolean
Private _nodes As New Dictionary(Of Integer, SiteMapNode)(16)
Private ReadOnly _lock As New Object()
Private _root As SiteMapNode
'Added...Declare an arraylist to hold all the roles this menu item applies to
Public roles As New ArrayList
Public Overloads 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 doesnt 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 config("securityTrimmingEnabled") IsNot 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
Public Overloads Overrides Function BuildSiteMap() As SiteMapNode
SyncLock _lock
' Return immediately if this method has been called before
If _root IsNot 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)
ElseIf Not [String].IsNullOrEmpty(_database) AndAlso Not String.IsNullOrEmpty(_table) Then
dependency = New SqlCacheDependency(_database, _table)
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")
_indexvisible = reader.GetOrdinal("visible")
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 dependency IsNot 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
Protected Overloads Overrides Function GetRootNodeCore() As SiteMapNode
SyncLock _lock
BuildSiteMap()
Return _root
End SyncLock
End Function
' 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 = IIf(reader.IsDBNull(_indexTitle), Nothing, reader.GetString(_indexTitle).Trim())
'Dim url As String = IIf(reader.IsDBNull(_indexUrl), Nothing, reader.GetString(_indexUrl).Trim())
'Dim url As String = ReplaceNullRefs(reader, _indexUrl)
Dim url As String = String.Empty
If Not (reader.IsDBNull(_indexUrl)) Then
url = reader.GetString(_indexUrl).Trim()
Else
url = ""
End If
'Eliminated...see http://weblogs.asp.net/psteele/archive/2003/10/09/31250.aspx
'Dim description As String = IIf(reader.IsDBNull(_indexDesc), Nothing, reader.GetString(_indexDesc).Trim())
'Added line below and 'ReplaceNUllRefs' func
Dim description As String = ReplaceNullRefs(reader, _indexDesc)
'Changed variable name from 'roles' to 'rolesN' and added line 230 to dump all roles into an arrayList
Dim rolesN As String = IIf(reader.IsDBNull(_indexRoles), Nothing, reader.GetString(_indexRoles).Trim())
Dim rolelist As String() = Nothing
If Not [String].IsNullOrEmpty(rolesN) Then
rolelist = rolesN.Split(New Char() {","c, ";"c}, 512)
End If
roles = ArrayList.Adapter(rolelist)
Dim visible As Boolean = ReplaceNullRefs(reader, _indexvisible)
' 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
Private Function ReplaceNullRefs(ByVal rdr As SqlDataReader, ByVal rdrVal As Integer) As String
If Not (rdr.IsDBNull(rdrVal)) Then
Return rdr.GetString(rdrVal)
Else
Return String.Empty
End If
End Function
Private Function GetParentNodeFromDataReader(ByVal reader As DbDataReader) As SiteMapNode
' Make sure the parent ID is present
If reader.IsDBNull(_indexParent) Then
'**** Commented out throw, added exit function ****
Throw New ProviderException(_errmsg3)
'Exit Function
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
Private Sub OnSiteMapChanged(ByVal key As String, ByVal item As Object, ByVal reason As CacheItemRemovedReason)
SyncLock _lock
If key = _cacheDependencyName AndAlso reason = CacheItemRemovedReason.DependencyChanged Then
' Refresh the site map
Clear()
_nodes.Clear()
_root = Nothing
End If
End SyncLock
End Sub
End Class
and I get this error:
*Özel Durum Ayrıntıları: System.IndexOutOfRangeException: visible
Kaynak Hatası:
Satır 154: _indexRoles = reader.GetOrdinal("Roles")
Satır 155: _indexParent = reader.GetOrdinal("Parent")
Satır 156: _indexvisible = reader.GetOrdinal("visible")
Satır 157:
Satır 158: If reader.Read() Then
Kaynak Dosya: D:\Websites\kaihl\App_Code\SqlSiteMapProvider.vb Satır: 156*
What I want is to tell sqlsitemapprovider to include an attribute within each sitemapnode called visible="true/false". Since this will be an extra attribute for sitemappath and menu (I think) this code would be doing the hiding job in menu not in breadcrumb (according to David Sussman's reply to a similar files .sitemap based thread as I linked above in my question):
Protected Sub Menu1_MenuItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemDataBound
Dim node As SiteMapNode = CType(e.Item.DataItem, SiteMapNode)
' check for the visible attribute and if false
' remove the node from the parent
' this allows nodes to appear in the SiteMapPath but not show on the menu
If Not String.IsNullOrEmpty(node("visible")) Then
Dim isVisible As Boolean
If Boolean.TryParse(node("visible"), isVisible) Then
If Not isVisible Then
e.Item.Parent.ChildItems.Remove(e.Item)
End If
End If
End If
End Sub
how to achieve this? thank you.
Update: I have found something very close at this page but still unable to deploy the solution.
Dim atts As NameValueCollection = Nothing
Dim attributeString As String = reader("attributes").ToString().Trim()
If Not String.IsNullOrEmpty(attributeString) Then
atts = New NameValueCollection()
Dim attributePairs() As String = attributeString.Split(";")
For Each attributePair As String In atts
Dim attributes() As String = attributePair.Split(":")
If attributes.Length = 2 Then
atts.Add(atts(0), attributes(1))
End If
Next
End If
Dim node As New SiteMapNode(Me, id.ToString(), url, title, description, rolelist, _
atts, Nothing, Nothing)
At last I have found a solution. And it is here. Thanks so much to Kadir ÖZGÜR, Sanjay UTTAM, David Sussman.
Checkout this link. he overides the IsAccessibleToUser property on the SiteMapprovider to selectivly show nodes based on the role of the current user. you caould change the condiftion to suit your needs.

Resources