Converting a list to an array for a web service - asp.net

I'm currently trying to convert my searchList in the web app from a list to an array so that it can be consumed in the web method. Right now, I'm using a web reference which only allows arrays to be passed and returned. I'd like to just simply convert the list to an array, but it looks like that won't work. I've tried looking online but each scenario I've found hasn't been similar enough to where I'm able to solve this. Any idea on the best way to do this?
Web App
Protected Function SearchCustomer()
Dim searchList As List(Of prxCustomerWebService1.Customer)
Dim objCustomerWS As New prxCustomerWebService1.CustomerWS
searchList = Cache("CustomerData")
'arr = searchList.ToArray
If (ddlSearchSpecs.Text = "Contains") Then
searchList = objCustomerWS.GetContains(tbSearch.Text, ddlSearchFields.Text, searchList)
ElseIf (ddlSearchSpecs.Text = "Starts With") Then
searchList = objCustomerWS.GetStartsWith(tbSearch.Text, ddlSearchFields.Text, searchList)
Else
searchList = objCustomerWS.GetExact(tbSearch.Text, ddlSearchFields.Text, searchList)
End If
If searchList.Count = 0 Then
lMessage.Text = "No Customers Found"
End If
Return searchList
End Function
Web Method
<WebMethod(description:="Gets customers that contain a specific value")> _
Public Function GetContains(ByVal sStringContains As String, ByVal sPropertyName As String, ByVal oListOfCustomers List(Of Customer))
oListOfCustomers()
Return CustomerFactory.GetContains(sStringContains, sPropertyName, oListOfCustomers)
End Function
Logic
Public Shared Function GetContains(ByVal sStringContains As String, ByVal sPropertyName As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim propertyInfo As PropertyInfo
propertyInfo = GetType(Customer).GetProperty(sPropertyName)
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
Try
For iIndex = 0 To oListOfCustomers.Count - 1
If (propertyInfo.GetValue(oListOfCustomers.Item(iIndex)).ToString.Trim.ToLower.Contains(sStringContains.ToLower) = True) Then
oNewListOfCustomers.Add(oListOfCustomers.Item(iIndex))
End If
Next
Catch ex As Exception
Return True
End Try
End If
Return oNewListOfCustomers
End Function

Related

Function result in an array of own structure

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.

Using browscap.ini with VB.Net

Since 2013 now (more than 3 years), I have been using http://www.useragentstring.com/ in my main VB.Net project to get browser name/version and OS name/version from user agent string to add statistics to my local web application.
But, recently, in last months, this web site has been unreliable with a lot of down times. So to avoid missing data in my statistics, I searched for a local solution instead of an online one. I found http://browscap.org/ is an old web site (since 1998) that still upload updated user agent information to this day (browscap.ini). It is designed for PHP, but I found a C# implementation there: https://www.gocher.me/C-Sharp-Browscap .
But as a VB.Net developper, I did not find any VB implementation for it. I googled a lot but with no success. Does anyone get one for VB.NET?
I finally get to convert the C# solution to VB.NET with some head scratching.
Public Class CompareByLength
Implements IComparer(Of String)
Private Function Compare(ByVal x As String, ByVal y As String) as Integer _
Implements IComparer(Of String).Compare
If x Is Nothing Then
If y Is Nothing Then
Return 0
Else
Return 1
End If
Else
If y Is Nothing Then
Return -1
Else
Dim retval As Integer = x.Length.CompareTo(y.Length)
If retval <> 0 Then
Return -retval
Else
return -x.CompareTo(y)
End If
End If
End If
End Function
End Class
Public Class BrowsCap
Private Declare Function GetPrivateProfileSectionNames Lib "kernel32.dll" Alias "GetPrivateProfileSectionNamesA" (ByVal lpReturnedString As Byte(), ByVal nSize As Integer, ByVal lpFileName As String) As Integer
Private Declare Function GetPrivateProfileSection Lib "kernel32.dll" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedBuffer As Byte(), ByVal nSize As Integer, ByVal lpFileName As String) As Integer
Private Declare Function GetPrivateProfileString Lib "kernel32.dll" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedBuffer As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
Private path As String
Private sections As String()
Private Function GetSectionNames() As String()
Dim maxsize As Integer = 500
Do
Dim bytes(maxsize) As Byte
Dim size As Integer = GetPrivateProfileSectionNames(bytes, maxsize, path)
If size < maxsize - 2 Then
Dim Selected As String = Encoding.ASCII.GetString(bytes, 0, size - (IIf(size > 0, 1, 0)))
Return Selected.Split(New Char() {ControlChars.NullChar})
End If
maxsize = maxsize * 2
Loop
End Function
Public Sub IniFileName(ByVal INIPath As String)
path = INIPath
sections = GetSectionNames()
Array.Sort(sections, New CompareByLength())
End Sub
public Function IniReadValue(ByVal Section As String, ByVal Key As String) As String
Dim temp As New StringBuilder(255)
Dim i As Integer = GetPrivateProfileString(Section, Key, "", temp.ToString(), 255, path)
Return temp.ToString()
End Function
Private Function findMatch(ByVal Agent As String) As String
If sections IsNot Nothing Then
For Each SecHead As String In sections
If (SecHead.IndexOf("*", 0) = -1) And (SecHead.IndexOf("?", 0) = -1) And (SecHead = Agent) Then
If IniReadValue(SecHead, "parent") <> "DefaultProperties" Then
Return SecHead
End If
End If
Next
For Each SecHead As String In sections
Try
If (SecHead.IndexOf("*", 0) > -1) Or (SecHead.IndexOf("?", 0) > -1) Then
if Regex.IsMatch(Agent, "^" + Regex.Escape(SecHead).Replace("\*", ".*").Replace("\?", ".") + "$") Then
Return SecHead
End If
End If
Catch ex As Exception
'Console.WriteLine(ex)
End Try
Next
Return "*"
End If
Return ""
End Function
Public Function getValues(ByVal Agent As String) As NameValueCollection
Dim match As String = findMatch(Agent)
Dim col As NameValueCollection = New NameValueCollection()
Do
Dim entries() As string
Dim goon As Boolean = true
Dim maxsize As Integer = 500
While goon
Dim bytes(maxsize) As Byte
Dim size As Integer = GetPrivateProfileSection(match, bytes, maxsize, path)
If size < maxsize - 2
Dim section As String = Encoding.ASCII.GetString(bytes, 0, size - IIf(size > 0, 1, 0))
entries = section.Split(New Char() {ControlChars.NullChar})
goon = False
End If
maxsize = maxsize * 2
End While
match = ""
If entries.Length > 0 Then
For Each entry As String In entries
Dim ent As String() = entry.Split(New Char() {"="C})
If ent(0) = "Parent" Then
match = ent(1)
else if col(ent(0)) is nothing Then
col.Add(ent(0), ent(1))
End If
Next
End If
Loop While match <> ""
Return col
End Function
End Class
And here is how to use it:
Dim dict As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
Dim bc As New BrowsCap
bc.IniFileName(Server.MapPath("/App_Data/lite_asp_browscap.ini"))
Dim Entry As NameValueCollection = bc.getValues(Request.UserAgent)
For Each s As String In Entry.AllKeys
dict.Add(s, Entry(s))
Next
' dict("Browser") will contains browser name like "IE" or "Chrome".
' dict("Version") will contains browser version like "11.0" or "56.0".
' dict("Platform") will contains OS name and version like "Win7".
The only thing left to do is to refresh my browscap.ini (or lite_asp_browscap.ini) sometimes (like once a week).

Cannot refer to an instance member of a class from a shared method

How you get a public shared function outside of a Protected Sub, use the values from within a protected sub to postBack to the same webpage. The postback reply works, but the query of the function fails at (Line 44 Char 17 "fqdom = dom & ".forest.local")
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Partial Class _Default
Inherits System.Web.UI.Page
Dim dom As String
Dim Group1 As String
Dim Group2 As String
Dim usrname As String
Dim fqdom As String
Dim netdom As String
Private Function GetDataFromArrayList() As ArrayList
Dim DomainList As New ArrayList()
DomainList.Add(New ListItem("d1", "dom1"))
DomainList.Add(New ListItem("d2", "dom2"))
Return DomainList
End Function
Protected Sub Selection_Changed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
For Each item As ListItem In GetDataFromArrayList()
DropDownList1.Items.Add(item)
Next
End If
End Sub
Public Shared Function GetGroups() As ArrayList
Dim groupList As New ArrayList()
Dim usrname As String
Dim fqdom As String
'Dim netdom As String
Dim groupCheck As String
fqdom = dom & ".forest.local"
Dim entry As System.DirectoryServices.DirectoryEntry
Dim searcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Try
entry = New System.DirectoryServices.DirectoryEntry("LDAP://" & fqdom)
searcher = New DirectorySearcher()
searcher.SearchRoot = entry
searcher.Filter = "(samAccountName=" & usrname & ")"
searcher.PropertiesToLoad.Add("memberOf")
result = searcher.FindOne()
Dim groupCount As Integer = result.Properties("memberOf").Count
For groupCounter As Integer = 0 To groupCount - 1
groupCheck = CStr(result.Properties("memberOf")(groupCounter))
groupCheck = groupCheck.Remove(groupCheck.LastIndexOf(",CN="))
groupCheck = groupCheck.Replace("CN=", "")
groupList.Add(groupCheck)
Next groupCounter
Catch ex As Exception
End Try
Return groupList
End Function
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim name As Boolean = False
If Not TextBox1.Text = String.Empty Then
name = True
End If
If name = False Then
StatusLabel.Text = "Update Status: Please Enter Name"
ElseIf name = True Then
Group1 = "groupb1"
Group2 = "groupb2"
Try
form1.Visible = False
Dim groups As New ArrayList()
groups = GetGroups()
Dim group As String
For Each group In groups
'NameLabel.Text = group
If (group.Contains(Group1)) Then
Group1.Text = "User: " & usrname & " is in group1"
End If
If (group.Contains(Group2)) Then
Group1.Text = "User: " & usrname & " is in group2"
End If
Next
fqdn.Text = "Domain: " & dom & ".forest.local"
NameLabel.Text = "User: " & usrname
Catch ex As Exception
End Try
Else
StatusLabel.Text = "Upload status: Error Please Retry later"
End If
End If
End Sub
End Class
Remove the Shared keyword from the method, so replace
Public Shared Function GetGroups() As ArrayList
with
Public Function GetGroups() As ArrayList
You cannot use instance variables like dom from within a Shared method.
You could also make those fields Shared. But that's not a good idea in ASP.NET since it could cause locks and concurrency issues and every request shared the same values(even of different users).
It's also not necessary since you want to use that method from a page method(button-click), so you need an instance of the page anyway.
If you need to persist a value across postback you can use a different way like using ViewState, Session or a HiddenField.

convert from httppostedfile to htmlinputfile

how do I convert an httppostedfile to an htmlinputfile? I'm working with an old mess of an app and so far have been able to refactor it so it makes a bit of sense, but this particular mess is too tangled to be worth the effort :S.
Thanks, as usual, for the help
relevant code:
collection:
Imports System.IO
Imports System.Web.UI.HtmlControls
Public Class ArchivosCollection
Inherits CollectionBase
Default Public Property Item(ByVal index As Integer) As HtmlInputFile
Get
Return MyBase.List(index)
End Get
Set(ByVal Value As HtmlInputFile)
MyBase.List(index) = Value
End Set
End Property
Public Function Add(ByVal oArchivo As HtmlInputFile) As Integer
Return MyBase.List.Add(oArchivo)
End Function
Public Function getDataSource() As DataTable
Dim dt As New DataTable
Dim oArchivo As HtmlInputFile
Dim fila As DataRow
Dim orden As Integer = 0
dt.Columns.Add("documento", GetType(System.String))
dt.Columns.Add("tipo", GetType(System.String))
For Each oArchivo In list
If Not oArchivo.Disabled Then
fila = dt.NewRow()
fila("documento") = Trim(Path.GetFileName(oArchivo.PostedFile.FileName))
fila("tipo") = Trim(oArchivo.PostedFile.ContentType)
dt.Rows.Add(fila)
End If
Next
Return dt
End Function
Public Function ExisteArchivo(ByVal Nombre As String) As Boolean
For Each oArchivo As HtmlInputFile In list
If Not oArchivo.Disabled Then
If Path.GetFileName(oArchivo.PostedFile.FileName) = Nombre Then
Return True
End If
End If
Next
Return False
End Function
Public Function EliminarArchivo(ByVal Nombre As String) As Boolean
For Each oArchivo As HtmlInputFile In list
If Not oArchivo.Disabled Then
If Path.GetFileName(oArchivo.PostedFile.FileName) = Nombre Then
oArchivo.Disabled = True
Return True
End If
End If
Next
End Function
End Class
old code:
Private Sub btnAgregarDocumento_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDocumento.Click
Try
If Not (Me.fleDocumento.PostedFile Is Nothing) Then
If Trim(Me.fleDocumento.PostedFile.FileName) = "" Then
Throw New Exception(rm.GetString("errorDebeEscogerUnArchivo"))
End If
If Not Servicios.isValidUploadType(Me.fleDocumento.PostedFile.FileName, ConfigurationManager.AppSettings("Filtros Upload")) Then
Throw New Exception(rm.GetString("errorExtensionNovalida"))
End If
Dim oArchivosOT As ArchivosCollection
If Session("oArchivosOT") Is Nothing Then
oArchivosOT = New ArchivosCollection
Else
oArchivosOT = Session("oArchivosOT")
End If
If oArchivosOT.ExisteArchivo(Path.GetFileName(Me.fleDocumento.PostedFile.FileName)) Then
Throw New Exception(rm.GetString("errorArchivoYaExiste"))
End If
oArchivosOT.Add(Me.fleDocumento)
Me.dgDocumentos.DataSource = oArchivosOT.getDataSource()
Me.dgDocumentos.DataBind()
Session("oArchivosOT") = oArchivosOT
If Request.QueryString("desde") = "proy" Then
ClientScript.RegisterStartupScript(Page.GetType, "msg", "<script>window.opener.document.Form1.refGridDocs.click();</script>")
End If
Else
Throw New Exception(rm.GetString("errorDebeEscogerUnArchivo"))
End If
Catch exc As Exception
ClientScript.RegisterStartupScript(Page.GetType, "msg", Servicios.MsgBox(exc.Message))
End Try
End Sub
new code (partial):
Dim archivos As HttpFileCollection = Request.Files
Dim colArchivos As ArchivosCollection = IIf(Session("oArchivosOT") Is Nothing, New ArchivosCollection(), Session("oArchivosOT"))
Dim i
For i = 0 To archivos.Count
colArchivos.Add(DirectCast(archivos(i), HtmlInputFile))
Next
Session("oArchivosOT") = colArchivos
The PostedFile property of the HtmlInputFile object is a HttpPostedFile object - you can simply access it for each HtmlInputFile.

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