How to use web client in VB .Net - vb.net

Greatings, ive got a piece of code and i keep getting an error when executing the code in VB. The error says " 'Captcha' is not declared." . Enyone?## Heading ##
The code:
With New Net.WebClient
Try
Dim b() As Byte = .UploadFile(New System.Uri("127.0.0.1"), Captcha.Path)
Captcha.Solution = System.Text.Encoding.ASCII.GetString(b).Split(CChar("|"))(5).ToString
Catch ex As Exception
Result.FailMessage = "Could not retrieve captcha response; " & ex.Message
Exit Try
End Try
End With

Related

Why I am getting Object reference not set to an instance of an object in Google Drive Api.?

I tried integrating google API in my VB.NET project.
I am getting the error Object reference not set to an Instance of an object.
But if I run the same thing again it works.
My code:
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
request.Upload()
Dim responsefile = request.ResponseBody
MsgBox(responsefile.Id.ToString) '-----Error catch here
Catch e As Exception
MsgBox("An error occurred: " + e.Message)
Return Nothing
End Try
NOTE : The same thing I run 2nd time in and it works well.
What should I do?
try this;
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
request.Upload()
Dim responsefile = request.ResponseBody
If responsefile.Id.ToString IsNot Nothing Then
MsgBox(responsefile.Id.ToString) '-----Error catch here
Else
request.Upload()
responsefile = request.ResponseBody
MsgBox(responsefile.Id.ToString)
End If
Catch e As Exception
MsgBox("An error occurred: " + e.Message)
Return Nothing
End Try

How do I connect VB.Net Winforms App to ServiceM8

It appears that I am able to get the temp-token, but when I try to convert to a permanent token I get "BAD REQUEST". Any help would be appreciated.
Code is hooked to WebBrowser1.Navigated
Dim strTempToken As String = ""
If WebBrowser1.Url.ToString.ToUpper.StartsWith("HTTPS://GO.SERVICEM8.COM/DASHBOARD?&S_AUTH=") Then
Try
Dim arrURL As Array = Split(WebBrowser1.Url.ToString, "&")
strTempToken = arrURL(1).ToString.Replace("s_auth=", "")
Catch ex As Exception
MessageBox.Show("Fail-1." & ex.Message)
End Try
If strTempToken.Length > 0 Then
Try
Dim hc As New System.Net.Http.HttpClient
Dim req As New System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://www.servicem8.com/oauth/access_token")
req.Headers.Add("client_id", strClientID)
req.Headers.Add("client_secret", strClientSecret)
req.Headers.Add("code", strTempToken) '
Dim res As System.Net.Http.HttpResponseMessage = Await hc.SendAsync(req)
My.Computer.FileSystem.WriteAllText(strKeyPath & "servicem8-perm-key.txt", res.RequestMessage.RequestUri.ToString, False)
MessageBox.Show("Success")
WebBrowser1.Url = New Uri("")
Catch ex As Exception
MessageBox.Show("Fail-2." & ex.Message)
End Try
End If
End If

How to log Catch exception to a text file

I have a vb.net program that runs a Try Catch. What i'd like to have happen, if there is an exception is have it log that exception to a text file. I have:
Catch ex As Exception
MsgBox(ex.Message)
My.Application.Log.WriteException(ex, TraceEventType.Error, "Exception " & "with argument " & "C:\Log.txt" & ".")
End Try
But it's not sending the exception to the logfile. What am I missing?
Adding a timestamp in the log file
Catch ex As Exception
IO.File.AppendAllText("C:\Log.txt", String.Format("{0}[{1}]{2}", Environment.NewLine, DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss"), ex.ToString()))
End Try
I think the example here: http://msdn.microsoft.com/en-us/library/dsxzceby(v=vs.90).aspx might have mislead you a bit. I find it a bit odd.
I think this is probably better:
Public Sub SomeMethodWhichMightGenerateException(byval someArg as String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception with argument " & someArg & ".")
End Try
End Sub
fileName is just a random variable in the msdn example and nothing to to do with where the Exception is logged...
Look here http://msdn.microsoft.com/en-us/library/7fx0fexe(v=vs.90).aspx to see where My.Application.Log.WriteException writes data to.
Alternatively you could do something like this:
Catch ex As Exception
IO.File.AppendAllText("C:\Log.txt", String.Format("{0}{1}", Environment.NewLine, ex.ToString()))
End Try
As others have said, however, you're probably better off using an existing error logging framework.
Public Function logerrors(ByVal [error] As String)
Dim filename As String = "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt"
Dim filepath As String = HttpContext.Current.Server.MapPath(Convert.ToString("~/ErrorLog/") & filename)
If File.Exists(filepath) Then
Using stwriter As New StreamWriter(filepath, True)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
End Using
Else
Dim stwriter As StreamWriter = File.CreateText(filepath)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
stwriter.Close()
End If
Return [error]
End Function

System.Net.Mail VB.NET 3.5 System.Net.Mail.SmtpException

I have searched the net thoroughly for a solution to this and have yet to find one.
I'm trying to establish a simple mail client to send text documents as raw text through SMTP. To do this I am using the System.Net.Mail library under VB.Net version 3.5
Whenever I try to send a message, I receive a System.Net.Mail.SmtpException.
I have tried using different mail providers, under different settings and have yet to solve this problem. This problem has been tested on 3 separate computers, all with different specifications.
The code is as follows:
Private Sub SendEmailMessage()
Try
If My.Computer.Network.IsAvailable Then
If DataValid() Then
'Data is valid, send the eMail.
Dim MailReceiver As String = txtReceiver.Text
'Create the eMail Message.
'Dim message As New MailMessage(from:=txtMailAddress.Text, to:=MailReceiver, subject:="(MTG) <CARD> " & ID, body:="<p>" & ConstructedFileString() & "<p>")
Dim message As New MailMessage
Dim MessageFrom As New MailAddress(txtMailAddress.Text)
Dim MessageTo As New MailAddress(MailReceiver)
With message
.From = MessageFrom
.To.Add(MailReceiver)
.Subject = "(MTG) CARD " & ID
.IsBodyHtml = True
.Body = "<p>" & ConstructedFileString() & "<p>"
End With
'Establish eMail Client
Dim emailClient As New SmtpClient()
Dim emailCredentials As New Net.NetworkCredential
With emailCredentials
.UserName = txtMailAddress.Text
.Password = txtPassword.Text
.Domain = "gmail.com"
End With
With emailClient
.Host = txtHostServer.Text
.Port = txtPort.Text
.Credentials = emailCredentials
.EnableSsl = chkSSL.Checked
.Timeout = 5000
End With
'Dim MailDomain As String = ""
'Dim PositionAt As Byte = 0
'PositionAt = txtMailAddress.Text.IndexOf("#")
'For i = PositionAt + 1 To Len(txtMailAddress.Text)
' MailDomain = MailDomain & txtMailAddress.Text.Chars(i)
'Next
'Debug.Print(MailDomain)
If My.Computer.Network.Ping(hostNameOrAddress:=emailClient.Host) Then
'Send the message.
emailClient.Send(message)
Else
'Could not ping, do not send.
ErrorOut("Could not reach the eMail Server.")
End If
Else
'Data is not valid, do not send the eMail.
End If
Else
ErrorOut("No network could be found. Check your network configurations.")
End If
Catch ex As Security.SecurityException
'Security exception
ErrorOut("A Security Exception was raised.")
Catch ex As Net.NetworkInformation.NetworkInformationException
'Network info exception
ErrorOut("Exception raised when retrieving network information.")
Catch ex As Net.NetworkInformation.PingException
'Ping exception
ErrorOut("Exception raised when pinging the network.")
Catch ex As Net.Mail.SmtpFailedRecipientException
'Recipient exception
ErrorOut("Mail Recipient Exception raised.")
Catch ex As Net.Mail.SmtpException
'Mail Server Exception
ErrorOut("Mail Server Exception raised")
Catch ex As Exception
'Generic Exception raised.
ErrorOut("General Exception raised", True)
End Try
End Sub
Any help on this matter is greatly appreciated, thanks.
Stack trace:
System.Net.Mail.SmtpException: The operation has timed out.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at NetProj.EmailDialog.SendEmailMessage() in ...
I believe this is the famous SSL issue with System.Net.Mail
http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx
It was there in framework 3.5 not sure about 4.0 if they fixed it or not.

Creating and appending text to txt file in VB.NET

Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.
For some reason, though it is creating the text file I am getting an error saying process cannot access file.
And when I run the program it is writing text, but how can I make it write on a new line?
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
If (Not File.Exists(strFile)) Then
Try
fs = File.Create(strFile)
sw = File.AppendText(strFile)
sw.WriteLine("Start Error Log for today")
Catch ex As Exception
MsgBox("Error Creating Log File")
End Try
Else
sw = File.AppendText(strFile)
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
End If
Try this:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:
Dim strFile As String = $#"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in Occured at-- {DateTime.Now}{Environment.NewLine}")
Got it all down to two lines of code :)
This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :)
Remember to add exception handling code.
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Dim fileExists As Boolean = File.Exists(filePath)
Using writer As New StreamWriter(filePath, True)
If Not fileExists Then
writer.WriteLine("Start Error Log for today")
End If
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
End Using
You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.
You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
If (Not File.Exists(strFile)) Then
sw = File.CreateText(strFile)
sw.WriteLine("Start Error Log for today")
Else
sw = File.AppendText(strFile)
End If
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
Catch ex As IOException
MsgBox("Error writing to log file.")
End Try
Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)
File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
While I realize this is an older thread, I noticed the if block above is out of place with using:
Following is corrected:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Using writer As New StreamWriter(filePath, True)
If File.Exists(filePath) Then
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End If
End Using
End Sub
Try it this way:
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
if File.Exists(filePath) then
Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End Using
end if