WordPress login VB.NET - wordpress

I am trying to create a Visual Basic code to verify the correctness of the wordpress login information
The original topic is here: Wordpress HttpWebrequest vb.net
Now the code gives a good result if the data is correct
But it gives an error if the data is wrong, I want to create an ( if )condition so that if the data is correct it gives an ( ok )message and if it is wrong it gives a message without errors or stops
the code :
Imports CookComputing.XmlRpc
<XmlRpcUrl("localhost/demo2/xmlrpc.php")>
Public Interface createContact
<CookComputing.XmlRpc.XmlRpcMethod("blogger.getUserInfo")>
Function GandiContact(ByVal city As String, ByVal apikey As String, ByVal s As String, ByVal params As XmlRpcStruct) As XmlRpcStruct
End Interface
Public Class Form1
Public clientProtocol As XmlRpcClientProtocol
Private Sub IpAddress()
Dim params As New XmlRpcStruct
Dim proxy = XmlRpcProxyGen.Create(Of createContact)()
clientProtocol = CType(proxy, XmlRpcClientProtocol)
clientProtocol.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Try
Dim response = proxy.GandiContact("1", "USERNAME", "PASSWORD", params)
TxtResult.Text = "USERNAME" & " : " & "PASSWORD"
MsgBox("ok")
Catch ex As Exception
End Try
End Sub

Related

Send mail on session_start

I want to invoke method (to sending a mail) in session_start.
This is my task function:
Public Shared Async Function SendEmailMessage(ByVal MailFrom As String, ByVal MailTo As String, ByVal Subject As String, ByVal HtmlMessage As String) As Task
Dim mail As MailMessage = New MailMessage
mail.From = New MailAddress(MailFrom)
mail.To.Add(MailTo)
mail.Subject = Subject
mail.Body = HtmlMessage
Dim smtp As SmtpClient = New SmtpClient("smtpclient")
smtp.Port = 587
smtp.DeliveryMethod = SmtpDeliveryMethod.Network
smtp.UseDefaultCredentials = True
Await Task.Run(Function() smtp.SendMailAsync(mail))
'Await result
End Function
In global.asax i have this code:
Public Overrides Sub Init()
MyBase.Init()
Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)
Me.AddOnAcquireRequestStateAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler)
End Sub
Private Async Function AsyncSessionStart() As Task
If Not Session.IsNewSession Then Return
Await funzioni.SendEmailMessage("***#***.**", "*****#***", "Object text",
String.Format("E' stato effettuato un tentativo di accesso da {0} del {1} alla WebApp.",
Session("name"), Session("office")))
End Function
this is the reference text that I have read and followed asp-net-async-global-asax
visual studio, however, gives me the following error in this part of the code:
Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)
Value of type Task cannot be converted to TaskEventHandler.
where am i wrong?
Without having tested, I believe that this:
Private Async Function AsyncSessionStart() As Task
should be this:
Private Async Sub AsyncSessionStart(sender As Object, e As EventArgs)
The method you specify to the EventHandlerTaskAsyncHelper constructor should be an asynchronous event handler, which means using the standard event handler parameters (which the link you posted does but you ignored) and declaring it an Async Sub.
You also have to use the AddressOf operator to create a delegate in VB. You may also have to specify the delegate type explicitly:
Dim wrapper = New EventHandlerTaskAsyncHelper(AddressOf AsyncSessionStart)
or:
Dim wrapper = New EventHandlerTaskAsyncHelper(New TaskEventHandler(AddressOf AsyncSessionStart))

Not getting Custom Error Message in REST

I am developing a REST API.
Below is my code:
In IService.vb
<OperationContract(),
WebGet(UriTemplate:="/DCU/{ClientID}",
RequestFormat:=WebMessageFormat.Xml,
ResponseFormat:=WebMessageFormat.Xml,
BodyStyle:=WebMessageBodyStyle.Bare)>
Function GetAllData(ByVal ClientID As String) As List(Of Data)
In Service.vb
Friend Class Service
Implements IService
Public Function GetAllData(ByVal intClientID As String) As System.Collections.Generic.List(Of Data) Implements ILightingGaleService.GetAllDCUs
Dim lstdata As New List(Of Data)()
If IsNumeric(intClientID) Then
Else
Throw New FaultException("Invalid Client ID")
End If
End Class
In Web.Config file
<serviceDebug includeExceptionDetailInFaults="true"/>
I am getting
Request Error:The server encountered an error processing the request. See server logs for more details.
When I am passing a String value in Client ID. Though I have implemented FaultExpcetion i never get "Invalid Client ID" message in POSTMAN or Web Client.
Can anyone help me on how can I get my custom message on POSTMAN or web client?
I was able to resolve this by implementing below:
I generated a class CustomError:
<DataContract> _
Public Class CustomError
Public Sub New(strError As String, strErrorDesc As String, strErrorCode As Long)
ErrorInfo = strError
ErrorDetails = strErrorDesc
ErroCode = strErrorCode
End Sub
<DataMember> _
Public Property ErrorInfo() As String
Get
Return m_ErrorInfo
End Get
Private Set(value As String)
m_ErrorInfo = value
End Set
End Property
Private m_ErrorInfo As String
<DataMember> _
Public Property ErrorDetails() As String
Get
Return m_ErrorDetails
End Get
Private Set(value As String)
m_ErrorDetails = value
End Set
End Property
Private m_ErrorDetails As String
<DataMember> _
Public Property ErroCode() As Long
Get
Return m_ErroCode
End Get
Private Set(value As Long)
m_ErroCode = value
End Set
End Property
Private m_ErroCode As Long
End Class
In Service.vb
Friend Class Service
Implements IService
Public Function GetAllData(ByVal intClientID As String) As System.Collections.Generic.List(Of Data) Implements ILightingGaleService.GetAllDCUs
Dim lstdata As New List(Of Data)()
If IsNumeric(intClientID) Then
Else
Dim ExceptionError As New CustomError("Client ID not found.", "The Client ID is not found in system.", HttpStatusCode.NotFound)
Throw New WebFaultException(Of CustomError)(ExceptionError, HttpStatusCode.NotFound)
End If
End Class
So this will generate a Webexception for my Custom Error Message which I wanted to display on my Client Application:
Now on my client application I used below
Catch ex As WebException
Dim strError = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
lblErrorMsg.Text = strError
End Try
Hope this helps to someone.

Why does RedirectToRoutePermanent add "count=0" to querystring?

I'm using ASP.NET 4.0 Routing and am reading route info from database and adding the routes as below. In a nutshell, my custom object "RouteLookup" contains the route information including the ID of another RouteLookup that it may or may not be redirected to. Here's an example of two RouteLookup entries in the db:
RouteLookupID RouteName RelativePath RequestHandler RouteHandler IsSecure RedirectedToRoute
13 PrivacyRoute about/privacy privacy.aspx NULL 0 0
14 PrivacyRoute1 privacy privacy.aspx NULL 0 13
RouteLookupID 14 is a legacy route that needs to be permanently redirected to RouteLookupID 13. The problem I'm running up against is when I request "http://mydomain.com/privacy" from the browser and watch Fiddler results, it actually redirects TWICE and adds a "count=0" as a querystring parameter! I have NO IDEA where this parameter is coming from as I have no process, httphandler, etc that is adding that explicitly.
What the heck is happening here? Any ideas are greatly appreciated and the rest of the relevant code is below.
I have a class, BaseRoute, which inherits from Route, so I can pass my custom RouteLookup object along with it to be examined in the custom RouteHandler which I've named BaseRouteHandler.
Public Class PageRouter
Private Shared db As New QADBDataContext
''''''' Is called from Global Application_Start
Public Shared Sub MapRoutes(routeColl As RouteCollection)
Dim routeLookups As IEnumerable(Of RouteLookup) = From rt In db.RouteLookups Select rt
For Each rtLookUp As RouteLookup In routeLookups
Dim parameterizedURL As String = BuildParameterizedVirtualPath(rtLookUp)
' Determine handler and route values
If rtLookUp.RouteHandler Is Nothing Then
RouteTable.Routes.Add(rtLookUp.RouteName, New BaseRoute(parameterizedURL, New BaseRouteHandler(), rtLookUp))
Else
RouteTable.Routes.Add(rtLookUp.RouteName, New BaseRoute(parameterizedURL, Activator.CreateInstance(Type.GetType("QA." + rtLookUp.RouteHandler)), rtLookUp))
End If
Next
End Sub
Protected Shared Function BuildParameterizedVirtualPath(rtLookUp As RouteLookup) As String
Dim parameterizedURL As String = rtLookUp.RelativePath
For Each param As RouteParameter In rtLookUp.RouteParameters
parameterizedURL &= "/{" + param.Name + "}"
Next
Return parameterizedURL
End Function
Public Shared Sub RedirectToRoutePermanent(rtData As RouteData)
Dim route As BaseRoute = DirectCast(rtData.Route, BaseRoute)
Dim rtLookup As RouteLookup = route.RouteLookup
Dim newRtLookupID As Integer = rtLookup.RedirectedToRoute
Dim newRtLookup As RouteLookup = (From rt In db.RouteLookups Where rt.RouteLookupID = newRtLookupID).SingleOrDefault
HttpContext.Current.Response.RedirectToRoutePermanent(newRtLookup.RouteName, rtData.Values.Values)
End Sub
End Class
Custom Route class:
Public Class BaseRoute
Inherits Route
Private _routeLookup As RouteLookup = Nothing
Public Sub New(url As String, routeHandler As IRouteHandler, routeLookup As RouteLookup)
MyBase.New(url, routeHandler)
_routeLookup = routeLookup
End Sub
Public ReadOnly Property RouteLookup As RouteLookup
Get
Return _routeLookup
End Get
End Property
End Class
Custom RouteHandler:
Public Class BaseRouteHandler
Implements IRouteHandler
Protected _baseRoute As BaseRoute = Nothing
Protected _rtLookup As RouteLookup = Nothing
Protected Overridable Sub InitializeContext(ByVal requestContext As System.Web.Routing.RequestContext)
_baseRoute = DirectCast(requestContext.RouteData.Route, BaseRoute)
_rtLookup = _baseRoute.RouteLookup
End Sub
Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) _
As System.Web.IHttpHandler Implements System.Web.Routing.IRouteHandler.GetHttpHandler
InitializeContext(requestContext)
EnforceURLStandard(requestContext)
PerformRedirectIfNeeded(requestContext)
Return GetPageHandler(requestContext)
End Function
Protected Overridable Sub PerformRedirectIfNeeded(ByVal requestContext As System.Web.Routing.RequestContext)
If _rtLookup.RedirectedToRoute > 0 Then
PageRouter.RedirectToRoutePermanent(requestContext.RouteData)
End If
End Sub
Protected Sub EnforceURLStandard(ByVal requestContext As System.Web.Routing.RequestContext)
' Test for:
' * Proper protocol
' * www. exists
' * must be all lowercase
Dim scheme As String = HttpContext.Current.Request.Url.GetComponents(UriComponents.Scheme, UriFormat.UriEscaped)
Dim rightSide As String = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort Or UriComponents.PathAndQuery, UriFormat.UriEscaped)
Dim newURL As String = Nothing
If Not rightSide.ToLower().StartsWith("www.") AndAlso Not rightSide.ToLower().StartsWith("localhost") _
AndAlso Not rightSide.ToLower().StartsWith("uat") AndAlso Not rightSide.ToLower().StartsWith("ux") Then
newURL = scheme & "://www." & rightSide
End If
If _rtLookup.IsSecure <> requestContext.HttpContext.Request.IsSecureConnection Then
Dim newScheme As String = If(_rtLookup.IsSecure, "https", "http")
newURL = newScheme & rightSide
End If
Dim pattern As String = "[A-Z]"
If Not String.IsNullOrWhiteSpace(newURL) Then
If Regex.IsMatch(newURL, pattern) Then
newURL = newURL.ToLower()
End If
Else
If Regex.IsMatch(HttpContext.Current.Request.Url.ToString(), pattern) Then
newURL = HttpContext.Current.Request.Url.ToString().ToLower()
End If
End If
If Not newURL Is Nothing Then
HttpContext.Current.Response.RedirectPermanent(newURL, True)
End If
End Sub
Protected Overridable Function GetPageHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
Return TryCast(BuildManager.CreateInstanceFromVirtualPath("/" & _rtLookup.RequestHandler, GetType(Page)), Page)
End Function
End Class
Well, figured out what was happening here. RedirectToRoutePermanent doesn't terminate the request like RedirectPermanent(url, true) does. I rewrote the PageRouter.RedirectToRoutePermanent as such, which resolved the issue:
Public Shared Sub RedirectToRoutePermanent(rtData As RouteData)
Dim route As BaseRoute = DirectCast(rtData.Route, BaseRoute)
Dim rtLookup As RouteLookup = route.RouteLookup
Dim newRtLookupID As Integer = rtLookup.RedirectedToRoute
Dim newRtLookup As RouteLookup = (From rt In db.RouteLookups Where rt.RouteLookupID = newRtLookupID).SingleOrDefault
Dim hostAndPort As String = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped)
Dim newURL As String = Nothing
Dim scheme As String = If(rtLookup.IsSecure, "https", "http")
newURL = scheme & "://" & hostAndPort
newURL &= "/" & newRtLookup.RelativePath
If rtData.Values.Count > 1 Then
For i As Integer = 1 To rtData.Values.Count - 1
newURL &= "/" & rtData.Values(i)
Next
End If
HttpContext.Current.Response.RedirectPermanent(newURL, True)
End Sub

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.

Catching errors or exceptions

I built a mashup of google maps and weather.com and everytime one of these server is not responding my application hangs up too.What do you think I can do to prevent or minimize hanging up of my web apps?Hanging up like you can't navigate away from that page....
I got this code on my app code to access the weather service;
Public Class WeatherIn
Private _path As String
Private _cachedFile As String
Public Sub New(ByVal path As String)
_path = path
_cachedFile = String.Format("{0}\WeatherInCache.xml", _path)
End Sub
Public Function GetWeather(ByVal arg As String) As String
Return _getWebWeather(arg)
End Function
Private Function _getCachedWeather() As String
Dim str As String = String.Empty
Using reader As New StreamReader(_cachedFile)
str = reader.ReadToEnd()
End Using
Return str
End Function
Private Function _getWebWeather(ByVal arg As String) As String
Dim baseUrl As String = "http://xoap.weather.com/weather/local/{0}?cc=*&dayf=5&link=xoap&prod=xoap&par={1}&key={2}"
Dim jane As String = arg
Dim james As String = "api key"
Dim john As String = "another api key"
Dim url As String = String.Format(baseUrl, jane, james, john)
Using client As New WebClient()
Try
Dim xml As New XmlTextReader(client.OpenRead(url))
Dim xslt As New XslCompiledTransform()
xslt.Load(_path + "/Pathto.xslt")
Using writer As New StreamWriter(_cachedFile)
xslt.Transform(xml, Nothing, writer)
End Using
Return _getCachedWeather()
Catch exception As WebException
Dim xmlStr As String = "<errorDoc>"
xmlStr += "<alert>An Error Occurred!</alert>"
xmlStr += [String].Format("<message>{0}</message>", exception.Message)
xmlStr += "</errorDoc>"
Dim doc As New XmlDocument()
doc.LoadXml(xmlStr)
Dim reader As New XmlNodeReader(doc)
Dim xslt As New XslCompiledTransform()
xslt.Load(_path + "/Pathto.xslt")
Dim resultDocument As New XmlDocument()
Using writer As XmlWriter = resultDocument.CreateNavigator().AppendChild()
xslt.Transform(reader, DirectCast(Nothing, XsltArgumentList), writer)
End Using
Return resultDocument.OuterXml
End Try
End Using
End Function
Then I used the class above on my page where I display the weather like this:
'specific zip code or could be retrieved from querystring for dynamic retrieval
var jay="94576"
Dim weather As New WeatherIn(Server.MapPath(String.Empty))
Dim weatherData As String = weather.GetWeather(jay)
Response.ContentType = "text/xml"
Response.CacheControl = "no-cache"
Response.Write(weatherData)
which I retrieve the data and write on the page through javascript.Most of the time its the weather.com that goes down.I got no problem with google map its reliable....anybody got a solution why my page hangs up too if the remote server is not responding?The mashup is running smoothly if the remote server is responding...
When depending on external web services it is best to load asynchronously so that if one of them is slow you can show some kind of loading spinner to the page viewer. If it fails your page could simply report that reading from the web server failed and to try again later.
In this case I would load up the page with the Google map in place and then make an AJAX request for the Weather data.

Resources