How to check if website is up? - vb.net

I'm learning about vb.net and was wondering how I would check for a website, if it is up, set a public shared, if it is down, use a different public shared?
I currently have the code as
Public Shared domain As String = "domain"
But I'm confused as how to make it check the site when I launch the application and then run the check.
--- Edit this is what I have now,
Dim URL As String = "https://www.personalblog.com"
Public Shared Function IsWebpageOnline(ByVal URL As String) As Boolean
Try
Dim req As WebRequest = WebRequest.Create(URL)
Dim res As WebResponse = req.GetResponse()
Catch ex As Exception
Return False
End Try
Return True
End Function
If IsWebpageOnline = 1 Then
Public Shared domain As String = "blog.com"
Else
Public Shared domain As String = "backupblog.com"
End If

You can use this function to check a webpage is online or not.
Public Shared Function IsWebpageOnline(ByVal URL As String) As Boolean
Try
Dim req As WebRequest = WebRequest.Create(URL)
Dim res As WebResponse = req.GetResponse()
Catch ex As Exception
Console.WriteLine(ex.Message)
Return False
End Try
Return True
End Function
It will try to make a get request to web server and then return a bool value
But I must suggest, switch to C# while its early.

Related

User not verified after migrating from Authy to Verify

We had earlier asked a question regarding migrating the data from Authy to Verify API. We were following the steps provided in this URL.
(https://www.stackoverflow.com/questions/74302235/migrate-authy-totp-to-verify)
However, when we are migrating the user, the user is not verified even after the migration. Here is the code which we are using
Dim oAuthy = New clsAuthy(apiKey, False)
'Fetch details from authy to migrate to verify
Dim authyDetails As clsAuthySecret = oAuthy.GetAuthyDetails(item("TwilioAuthyId"))
oAuthy = Nothing
'Migrate data to verify API
With oVerify
.GenerateQRCode(item("UserName"), item("UserId").ToString(), authyDetails.Secret)
.VerifyToken(.FactorID, authyDetails.OTP, item("UserId").ToString())
FactorId = .FactorID
VerifyUrl = .QrUrl
End With
Public Function GetAuthyDetails(ByRef AuthyID As String) As clsAuthySecret
Dim apiResponse As clsAuthySecret
Dim url = String.Format("{0}/protected/json/users/{1}/secret/export", Me.baseUrl, AuthyID, Me.apikey)
Try
client.Headers.Set("X-Authy-API-Key", Me.apikey)
Dim response = client.DownloadString(url)
apiResponse = JsonConvert.DeserializeObject(Of clsAuthySecret)(response)
apiResponse.RawResponse = response
Catch ex As WebException
apiResponse = New clsAuthySecret()
apiResponse.Status = AuthyStatus.BadRequest 'bad request
apiResponse.Message = ex.Message
'apiResponse.RawResponse = ex.Response.ToString()
End Try
If (apiResponse.Success) Then
apiResponse.Status = AuthyStatus.Success
End If
Return apiResponse
End Function
Public Function GenerateQRCode(ByVal Email As String,
ByVal UserID As String,
ByVal Secret As String
) As Task(Of Boolean)
Try
TwilioClient.Init(_accountSID, _authToken)
Dim newFactor = NewFactorResource.Create(friendlyName:=Email,
factorType:=NewFactorResource.FactorTypesEnum.Totp,
pathServiceSid:=_serviceSID,
pathIdentity:=UserID.ToLower(),
bindingSecret:=Secret)
_factorID = newFactor.Sid
_qrUrl = JObject.Parse(newFactor.Binding.ToString())("uri")
Catch ex As Exception
_responseMessage = ex.Message
Return False
End Try
Return True
End Function
Public Function VerifyToken(ByVal FactorID As String,
ByVal Token As String,
ByVal UserID As String
) As Task(Of Boolean)
Try
TwilioClient.Init(_accountSID, _authToken)
Dim factor = FactorResource.Update(authPayload:=Token,
pathServiceSid:=_serviceSID,
pathIdentity:=UserID.ToLower(),
pathSid:=FactorID)
If factor.Status.ToString = "verified" Then
Return True
Else
Return False
End If
Catch ex As Exception
_responseMessage = ex.Message
Return False
End Try
End Function
Is there anything we are missing from our end? Following is the response as shown in the image link below
https://i.stack.imgur.com/lhTkE.png

What is wrong with my code (VB. NET async wait and httplistener)

I am trying to run a httplistener in order to receive a call back from an web application
However the never goes past context = Await httpListener.GetContextAsync
I can telnet to the port of the listener and it responds.
Class SSO
Public Sub AuthorizeAsync()
Me.oAccessToken = Operations.AuthorizeAsync.Result
End Sub
'
Class Operations
Shared Async Function AuthorizeAsync() As Task(Of SSO.AccessToken)
Dim AccessToken As SSO.AccessToken
Dim AuthorizationCodeTask As Task(Of String)
Dim cts As New System.Threading.CancellationTokenSource
AuthorizationCodeTask = Operations.RunCallbackListenAsync(cts.Token)
Try
OpenAutorizationUrl()
Dim t As String
t = Await AuthorizationCodeTask
AccessToken = GetAccessToken(t)
Catch ex As Exception
logger.LogException(ex)
Throw ex
End Try
Return AccessToken
End Function
Private Shared Async Function RunCallbackListenAsync(ByVal cts As System.Threading.CancellationToken) As Task(Of String)
Dim retval As String = Nothing
Dim blGo As Boolean = True
Dim httpListener As New System.Net.HttpListener
httpListener.Prefixes.Add(My.Settings.APICallBack)
httpListener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous
httpListener.Start()
If httpListener.IsListening Then
Dim request As System.Net.HttpListenerRequest
Dim context As System.Net.HttpListenerContext
context = Await httpListener.GetContextAsync
While Not cts.IsCancellationRequested And blGo
context = Await httpListener.GetContextAsync
Try
If cts.IsCancellationRequested Then
context.Response.Abort()
End If
request = context.Request
Catch ex As Exception
logger.LogException(ex)
End Try
blGo = False
End While
If Not IsNothing(request) Then
retval = ProcessRequest(request)
Else
Throw New ApplicationException("RunCallbackListenAsync: The request is Nothing")
End If
httpListener.Close()
Else
Throw New ApplicationException("RunCallbackListenAsync: listener is not listening")
End If
Return retval
End Function
End class
what could by causing the blocking at context = Await httpListener.GetContextAsync?

Check if URL has valid page

I want to check if URL has valid page (not 404, just 200).
Code I've tried:
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(myurl), HttpWebRequest)
request.KeepAlive = True
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If response.StatusCode = HttpStatusCode.OK Then
MsgBox("OK")
End If
Yet every URL that I enter leaves OK response, even if I enter http://mywebsite.com/blahblah.
It's not same on all websites (works fine with example.com), but it doesn't work on my website. Why?
In my browser I see 404 page, but code says it's OK.
Edit: Just to mention that my website has Cloudflare on.
Try this out and see if it work's for you... As mentioned above in my comment's:
A 404 just means the page isn't found on the server, status will return ok even if a page isn't found and the server was reached and responded
Public Class WebPage
Public Property PageSource As String = String.Empty
Public Property Status As HttpStatusCode = HttpStatusCode.NotFound
Public Property WebError As String = String.Empty
End Class
Public Shared Function GetWebPage(ByVal Website As String) As WebPage
Dim web As New WebPage() With {.Status = HttpStatusCode.OK}
Try
Using source As New System.Net.WebClient()
web.PageSource = source.DownloadString(Website)
End Using
Return web
Catch exweb As WebException
If exweb.Status = WebExceptionStatus.ProtocolError AndAlso exweb.Message.Contains("404") Then
web.Status = HttpStatusCode.NotFound
Else
web.Status = HttpStatusCode.BadRequest
End If
web.WebError = exweb.Message
Catch ex As Exception
web.Status = HttpStatusCode.NotFound
web.WebError = ex.Message
End Try
Return web
End Function
Usage Example
Dim webObj As WebPage = GetWebPage("THESITE")
If Not String.IsNullOrEmpty(webObj.WebError) Then
MessageBox.Show(webObj.WebError)
ElseIf webObj.Status = HttpStatusCode.OK Then
MessageBox.Show("OK")
End If
This will do what you want.
Function URLExists(url As String) As Boolean
Dim Request As Object
Dim ff As Integer
Dim rc As Variant
On Error GoTo EndNow
Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")
With Request
.Open "GET", url, False
.send
rc = .StatusText
End With
Set Request = Nothing
If rc = "OK" Then URLExists = True
Exit Function
EndNow:
End Function

how to get source code from link with user name and password in vb or c#

i try to get code source from my facebook account bet i get only the login page code source...
i assumes its happens because problem with cookie
my code...
'download data from url and return string of the source code
Public Shared Function getSourceCode(address As String) As String
Dim reader As StreamReader = Nothing
'Address of URL
Dim URL As String = address
' Get HTML data
Dim client As WebClient = New WebClient()
Try
client.Proxy = Nothing
Dim data As Stream = client.OpenRead(URL)
reader = New StreamReader(data)
Catch
'error
End Try
If reader IsNot Nothing Then Return reader.ReadToEnd
Return ""
End Function

vb.net OpenWeatherMap using HttpWebRequest

I am unable to get the HttpWebRequest to work properly with OpenWeatherMap.
When I try out the URL from the browser I get the data. However, when I am sending it from the program I'm getting a message with code id. Like this:
"message":"","cod":"404"
What Am I doing wrong?
VB.NET Code:
Private Shared AppID As String = "add_app_id_Here"
Public Shared Function GetWeather(ByVal location As String) As List(Of WeatherDetails)
Dim url = String.Format _
("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&type=accurate&mode=xml&units=metric&cnt=3&appid={1}",
location, AppID)
Try
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
request.AuthenticationLevel = Net.Security.AuthenticationLevel.None
Dim response As WebResponse = request.GetResponse()
'The body of the request is sent here
Dim responseReader As New StreamReader(response.GetResponseStream())
Dim responseInfo As String = responseReader.ReadToEnd()
responseReader.Close()
response.Close()
If Not (responseInfo.Contains("message") And responseInfo.Contains("cod")) Then
Dim xEl = XElement.Load(New System.IO.StringReader(responseInfo))
Return GetWeatherInfo(xEl)
Else
Return New List(Of WeatherDetails)
End If
Catch ex As Exception
Return New List(Of WeatherDetails)
End Try
End Function
After breaking my head I found that his method HttpWebRequest is not tolerant to special characters or non printable characters.
Thus in the URL I had to hardcode the "%27" character and it solved the problem.