How do I connect VB.Net Winforms App to ServiceM8 - vb.net

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

Related

"Response received is incomplete"

So I reversed the syntax of this send sms code from c# to vb net so I can reuse it.
The code works sometimes, but for some reason it would often give me the "response received is incomplete" exception.
I was thinking perhaps my code is processing commands faster than my GSM device, could handle, so I tried increasing the timeout response for the serial port, still ends up with this exception.
What do you think is the problem and what would you recommend I do to solve it?
Public Class SmsHelper
Public receiveNow As AutoResetEvent
#Region "Open and Close Ports"
'Open Port
Public Function OpenPort(portName As String, baudRate As Integer, dataBits As Integer, readTimeout As Integer, writeTimeout As Integer) As SerialPort
receiveNow = New AutoResetEvent(False)
Dim port As New SerialPort()
Try
port.PortName = portName
'COM1
port.BaudRate = baudRate
'9600
port.DataBits = dataBits
'8
port.StopBits = StopBits.One
'1
port.Parity = Parity.None
'None
port.ReadTimeout = readTimeout
'300
port.WriteTimeout = writeTimeout
'300
port.Encoding = Encoding.GetEncoding("iso-8859-1")
port.NewLine = vbCrLf
AddHandler port.DataReceived, AddressOf port_DataReceived
port.Open()
port.DtrEnable = True
port.RtsEnable = True
Catch ex As Exception
Throw ex
End Try
Return port
End Function
' Send AT Command
Public Function SendATCommand(port As SerialPort, command As String, responseTimeout As Integer, errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & Convert.ToString(vbCrLf))
Dim input As String = ReadResponse(port, responseTimeout)
Console.WriteLine("Received data is " & input)
If (input.Length = 0) OrElse ((Not input.EndsWith(vbCr & vbLf & "> ")) AndAlso (Not input.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
Finally
End Try
End Function
'Receive data from port
Public Sub port_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
receiveNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function ReadResponse(port As SerialPort, timeout As Integer) As String
Dim serialPortData As String = ""
Try
Do
If receiveNow.WaitOne(timeout, False) Then
Dim data As String = port.ReadLine()
serialPortData += data
Else
'Console.WriteLine("SerialPortData data is " & serialPortData)
If serialPortData.Length > 0 Then
Console.WriteLine("SerialPortData is " & serialPortData.ToString)
Throw New ApplicationException("Response received is incomplete.")
Else
Throw New ApplicationException("No data received from phone.")
End If
End If
Loop While Not serialPortData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "> ") AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "ERROR" & vbCr & vbLf)
Catch ex As Exception
Throw ex
End Try
Return serialPortData
End Function
Shared readNow As New AutoResetEvent(False)
Public Function SendMessage(port As SerialPort, phoneNo As String, message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = SendATCommand(port, "AT", 3000, "No phone connected")
Dim command As String = "AT+CMGF=1" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to set message format.")
' AT Command Syntax - http://www.smssolutions.net/tutorials/gsm/sendsmsat/
command = (Convert.ToString("AT+CMGS=""") & phoneNo) + """" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to accept phoneNo")
'wait(2)
command = message & Char.ConvertFromUtf32(26)
recievedData = SendATCommand(port, command, 3000, "Failed to send message")
Console.WriteLine("Received data is " & recievedData)
If recievedData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
Private Shared Sub DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
readNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
#End Region
End Class

Simple retrieve data from webpage

I am trying to retrieve data from webpage. On the webpage, there is only sentence. What is the correct way to retrieve the sentence ? I have tried this without any luck
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://example.org")
MsgBox(result)
OK, I think you're not getting the results from your HTTP call. Here's what I did - sorry it's C#, you'll have to translate but this is probably close to what you need:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader rdr = new StreamReader(receiveStream, Encoding.UTF8);
try
{
//Check that page downloaded OK
if (response.StatusCode == HttpStatusCode.OK)
{
//Do something
}
}
catch (Exception xx)
{
//handle error
}
finally
{
response.Close();
}
I used to do it with this:
Imports System.Net
Imports System.IO
Imports System.IO.Compression
And:
Dim urlUri As New System.Uri("http://www.example.org/")
Dim strResult as string = String.Empty
Dim webHTTP As HttpWebRequest
Try
webHTTP = WebRequest.Create(urlUri)
webHTTP.KeepAlive = False
Catch ex As Exception
Throw New Exception("An error occured while trying to create the request:" & vbCrLf & ex.Message)
Exit Sub
End Try
Dim WebResponse As HttpWebResponse
Try
WebResponse = webHTTP.GetResponse()
Catch ex As Exception
Throw New Exception("An error occured while retrieving the response:" & vbCrLf & ex.Message)
Exit Sub
End Try
Dim responseStream As Stream
Try
responseStream = WebResponse.GetResponseStream()
Catch ex As Exception
Throw New Exception("An error occured while retrieving the response stream:" & vbCrLf & ex.Message)
Exit Sub
End Try
If (WebResponse.ContentEncoding.ToLower().Contains("gzip")) Then
responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
ElseIf (WebResponse.ContentEncoding.ToLower().Contains("deflate")) Then
responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
End If
Dim CHUNK_SIZE As Long = 3072
Dim read(CHUNK_SIZE) As [Char]
Dim reader As StreamReader
Try
reader = New StreamReader(responseStream, Encoding.Default)
Catch ex As Exception
Throw New Exception("An error occured while creating the streamreader:" & vbCrLf & ex.Message)
Exit Sub
End Try
Dim count As Integer = reader.Read(read, 0, CHUNK_SIZE)
Do While count > 0
Dim str As New [String](read, 0, count)
strResult &= str
ReDim read(CHUNK_SIZE)
count = reader.Read(read, 0, CHUNK_SIZE)
Loop
reader.Close()
responseStream.Close()
WebResponse.Close()
Messagebox.Show(strResult)

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

Failure sending email

My test case is getting failed at assert.fail(), I am not having any clue what wrong it is going and where it is getting failed. Any idea to make this test case pass
Below is the test case
<Test()> _
Public Sub SendFtpFailureEmailShouldPassWithProcessingInfosAndSendEmail()
Dim em As EmailNotification = New EmailNotification()
Try
Dim pfis As ProcessingFileInfos = New ProcessingFileInfos(New FileInfo(AppSettingsReader.SchemaLocation), "Ftp")
Dim pfi1 As ProcessingFileInfo = New ProcessingFileInfo(New FileInfo("Test1.xml"))
pfi1.ContainsErrors = True
pfi1.Message = "File Failed"
pfi1.FileProcessStatus = "F"
pfi1.Channel = "Ftp"
pfis.Add(pfi1)
Dim pfi2 As ProcessingFileInfo = New ProcessingFileInfo(New FileInfo("Test2.xml"))
pfi2.ContainsErrors = True
pfi2.Message = "File Failed on Bad Data"
pfi2.FileProcessStatus = "F"
pfi2.Channel = "Ftp"
pfis.Add(pfi2)
Dim result As String = em.CreateFtpFailureEmail(pfis)
Assert.IsNotEmpty(result, "result is invalid")
Dim emailDetails As Email = New Email() With {.Body = result, _
.FromEmail = AppSettingsReader.TPLFromEmail, _
.FromEmailName = AppSettingsReader.TPLFromEmailName, _
.SmtpHost = AppSettingsReader.SmtpHost, _
.Subject = "FTP Failure Report", _
.ToEmail = "runu.ali#cdsglobal.co.uk"}
em.SendEmail(emailDetails)
Catch ex As Exception
Assert.Fail(ex.Message)
End Try
End Sub
sending mail code below:
Public Sub SendEmail(ByVal emailObj As Email)
Try
If emailObj Is Nothing Then
Throw New ArgumentNullException("emailObj", "emailObj cannot be null or empty")
End If
Dim em As New Net.Mail.MailMessage()
em.From = New MailAddress(emailObj.FromEmail, emailObj.FromEmailName)
em.To.Add(New MailAddress(emailObj.ToEmail))
em.Subject = emailObj.Subject
em.Body = emailObj.Body
em.IsBodyHtml = True
Dim SmTP As SmtpClient = New SmtpClient()
SmTP.Host = emailObj.SmtpHost
SmTP.Send(em)
Catch ex As SmtpException
Throw
Catch ex As FormatException
Throw
End Try
End Sub

Timeoutexception on TCP not handled

I took this code from a website since VS 2010 doesn't support the timeout for the TCP connections:
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
Dim wh As System.Threading.WaitHandle = ar.AsyncWaitHandle
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function
And it works fine, but everytime, it gives me this on the debug output:
"A first chance exception of type 'System.TimeoutException' occurred in"
Even if I'm catching all the exceptions. Is there a way to get rid of this exception message as it is handled?
I've tried this:
Dim connectDone As New System.Threading.AutoResetEvent(False)
TCPClient.BeginConnect(IPAddress, TCPPort, New AsyncCallback(Sub(ar As IAsyncResult)
TCPClient.EndConnect(ar)
connectDone.Set()
End Sub), TCPClient)
'client.BeginConnect("127.0.0.1", 80, new AsyncCallback(delegate( IAsyncResult ar ) { client.EndConnect( ar ); connectDone.Set(); }), client);
If Not connectDone.WaitOne(2000) Then
Debug.WriteLine("TIMEOUT")
Return False
End If
Return True
But it gives me InvalidOperationException on the beginconnect line:
BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult
Dim wh As System.Threading.WaitHandle
Try
ar = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
wh = ar.AsyncWaitHandle
Cath ex as Exception
'Code to catch exception
End Try
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function