in VB.NET unsupported media type on XML-API request with CookComputing.XmlRpcV2 - vb.net

I have the following function in a VB.NET program that was working for a connection with an outsource system XML-API for years with no problems.
Recently, the responsible team for the specific API moved their system to another address (and probably another system) and claim that there is no change and I will just have to make a change in the address that I connect to.
I changed the address and firstly I had some connectivity problems with the new address ("An existing connection was forcibly closed by the remote host") and discovered that I had to compile my code to an earlier .NET Framework version in order to connect because the authentication protocol from their side was changed to TLS v1.2 instead of TLS v1.1 that they were using in the old address.
Now I get an exception “unsupported media type” from CookComputing.XmlRpcV2 when I try to communicate (fetch data) from the new API.
With some googling, I found that the specific exception has to do with content-type header of the request.
The strange thing is that using Postman I can succesfully get a response with both the old and new address using the same content-type (application/xml). The response from the API team was that their system is set to accept and produce the following content types: text/plain, text/html, and application/xml, so I don't think that the problem is with the content-type header.
Does anyone have any ideas on what else should I try ?
Imports CookComputing.XmlRpc
Imports System.Net
Public Shared Function CommunicateWithApi(ByVal pTest As Boolean,
ByVal pCommand As String,
ByVal pInParamsArray As ArrayList,
ByRef pOutParamsArray As ArrayList,
ByRef pErrorMessage As String) As Boolean
Try
Dim _Api = XmlRpcProxyGen.Create(Of IActionAid)()
If pTest Then
_Api.Url = "https://test.blabla.org/servlet/B2BNK"
Else
_Api.Url = "https://live.blabla.org/servlet/B2BNK"
End If
_Api.XmlEncoding = System.Text.Encoding.GetEncoding("ISO-8859-7")
_Api.XmlRpcMethod = pCommand
_Api.UseIndentation = False
_Api.UseIntTag = True
Dim pParams() As Object = pInParamsArray.ToArray
Dim Response() As Object = {}
Response = _Api.FetchData(pParams)
For i As Integer = 0 To Response.Count - 1
pOutParamsArray.Add(Response(i))
Next
Return True
Catch fex As XmlRpcFaultException
MsgBox((String.Format("Fault Response: {0} ", fex.FaultCode)) + fex.FaultString, MsgBoxStyle.Critical)
pErrorMessage = String.Format("{0:00000000000000000000},{1}", fex.FaultCode, fex.FaultString)
Return False
Catch webEx As WebException
MsgBox("WebException: " + webEx.Message, MsgBoxStyle.Critical)
pErrorMessage = String.Format("70000000000000000000,{0}", webEx.Message)
If webEx.Response IsNot Nothing Then
webEx.Response.Close()
End If
Return False
Catch xmlRpcEx As XmlRpcServerException
MsgBox("XmlRpcServerException: " + xmlRpcEx.Message, MsgBoxStyle.Critical)
pErrorMessage = String.Format("80000000000000000000,{0}", xmlRpcEx.Message)
Return False
Catch defEx As Exception
MsgBox("Exception: " + defEx.Message, MsgBoxStyle.Critical)
pErrorMessage = String.Format("90000000000000000000,{0}", defEx.Message)
Return False
End Try
End Function

Related

vb.net WebClient.DownloadString fails with exception

I am working on a program in VS 2017 coding in VB.Net. The program downloads Web pages using Net.WebClient.DownloadString and then parses the data. It worked fine for a year or more then one day I started getting an exception when downloading the pages.
The ex.Message is: 'The underlying connection was closed: An unexpected error occurred on a send.'
The ex.InnerException.Message is: 'Unable to write data to the transport connection: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.'
I have VS 2017 installed on 2 other PC's at this location and on 1 at another location. They all continue to run the code without exception. It is only an issue on this PC.
The code is below (I changed the Web address but it fails for any valid URL).
Any ideas why this fails on my main PC only?
Public Function DownloadData() As Boolean
Dim strURL As String = "https://www.google.com/"
Dim strOutput As String
Try
Using WC As New Net.WebClient
strOutput = WC.DownloadString(strURL)
If strOutput.Length > 0 Then
If ParseData(strOutput) = True Then
Return True
End If
Else
Return False
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message, "Error")
End Try
End Function

Is requiring captcha for API a design flaw?

And the reason is simple
It now asks for Captcha.
So I can access
https://c-cex.com/t/api_pub.html?a=getmarketsummaries on browser, do captca and I can accept that.
But my program cannot.
This is the code that failed
Public Shared Function downloadString1(url As String, post As String, otherHeaders As Tuple(Of String, String)()) As String
Dim wc = New CookieAwareWebClient()
For Each oh In otherHeaders
wc.Headers.Add(oh.Item1, oh.Item2)
Next
Dim response = String.Empty
For i = 1 To 1
Try
If post = "" Then
response = wc.DownloadString(url)
Else
If post.Contains("=") Then
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
End If
response = wc.UploadString(url, post)
End If
Catch ex As Exception
Dim a = 1
End Try
If response = "" Then
Sleep(1000)
Else
Exit For
End If
Next
Return response
End Function
And API should be used as program.
Is there a work around?
Or should I just complain to c-cex support about their API.
Is this a design flaw?
Note: Let me show you screenshot
An API can't really ask for a CAPCHA as that's a mechanism to challenge that a user is human. By definition almost, an API will not be. If you need any challenge it would be authentication and authorisation which is typically done with a key, client cert or username/password.
If that URL is indeed designed as an API then I agree it's a design flaw. It didn't actually ask me for a capcha though when I used it.

VB Authenticate User In Outlook Web App

I currently have a mail system using Microsoft's exchange server (OWA). I am trying to authenticate a user and send an email using pure Visual Basic code.
I have been trying to use a library called Aspose, however; I have no idea if I'm on the right track. I can not get it to work and I am not sure (since this is a company mail server) whether it's the server or it's my code.
Currently I have,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Create instance of ExchangeClient class by giving credentials
Dim client As Aspose.Email.Exchange.ExchangeClient = New Aspose.Email.Exchange.ExchangeClient("https://MAILSERVER.com/username/", "username", "password", "https://MAILSERVER.com/")
' Create instance of type MailMessage
Dim msg As Aspose.Email.Mail.MailMessage = New Aspose.Email.Mail.MailMessage()
msg.From = "username#MAILSERVER.com"
msg.To = "receivingemail#gmail.com"
msg.Subject = "test"
msg.HtmlBody = "test"
' Send the message
Try
client.Send(msg)
Console.WriteLine("made it")
Catch ex As Exception
Console.WriteLine("failed")
End Try
End Sub
I have obviously changed the username, password, and server name fields to generic ones but with (what I think is the right credentials) the output is always failed.
Can anybody help me out please?
Here is what I use:
Public Shared Function SendEMail(MailMessage As System.Net.Mail.MailMessage) As String
ErrorMess = ""
' Default the from address, just in case is was left out.
If MailMessage.From.Address = "" Then
MailMessage.From = New Net.Mail.MailAddress("donotreply#MAILSERVER.com")
End If
' Check for at least one address
If MailMessage.To.Count = 0 AndAlso MailMessage.CC.Count = 0 AndAlso MailMessage.Bcc.Count = 0 Then
ErrorMess = "No Addresses Specified"
Return ErrorMess
End If
' Create a SMTP connedction to the exchange 2010 load balancer.
Dim SMTPClient As New System.Net.Mail.SmtpClient("MAILSERVER.com")
Try
Dim ValidUserCredential As New System.Net.NetworkCredential
ValidUserCredential.Domain = "MAILSERVER.com"
ValidUserCredential.UserName = My.Resources.EmailUserName
ValidUserCredential.Password = My.Resources.EmailPassword
SMTPClient.UseDefaultCredentials = False
SMTPClient.Credentials = ValidUserCredential
SMTPClient.Send(MailMessage)
Return "Mail Sent"
Catch ex As Exception
ErrorMess = ex.Message & " " & ex.InnerException.ToString
Return ErrorMess
End Try
End Function
The ExchangeClient class is used to connect to Exchange server using the WebDav protocol and is used with Exchange Server 2003 and 2007. For OWA, you need to use the IEWSClient interface as shown in the following sample code. It has an Office365 test account that you can use to send a test email (the test account is solely for testing purpose and is not property of Aspose. I just created it for assisting you in testing the functionality). Please try it and if you face any problem, you may share the porblem on Aspose.Email forum for further assistance.
' Create instance of IEWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "UserTwo#ASE1984.onmicrosoft.com", "Aspose1234", "")
' Create instance of type MailMessage
Dim msg As New MailMessage()
msg.From = "UserTwo#ASE1984.onmicrosoft.com"
msg.[To] = "receiver#gmail.com"
msg.Subject = "Sending message from exchange server"
msg.IsBodyHtml = True
msg.HtmlBody = "<h3>sending message from exchange server</h3>"
' Send the message
client.Send(msg)
I work with Aspose as Developer evangelist.

ObjectDisposedException obtaining user name in SignalR event

I'm logging current SignalR connections in a sql server database. Records are added via the OnConnected and OnReconnected events and removed via the OnDisconnected event.
On deploying to our staging server I am now experiencing an intermittent issue fetching the username of the disconnected user.
This is using SignalR v2.0.3
Public Overrides Function OnDisconnected() As Threading.Tasks.Task
Try
Dim username As String = String.Empty
Try
username = Me.Context.User.Identity.Name ' this is where the error occurs
Catch ex As Exception
_logger.LogWarning(ex, EventLogEntryType.Warning)
End Try
Dim connId = Me.Context.ConnectionId
Dim referer = Me.Context.Headers("Referer")
_connService.RemoveConnection(connId)
Dim msg = New With {.username = username, .connectionId = connId, .referer = referer}
Dim hub = GlobalHost.ConnectionManager.GetHubContext(Of IncidentsHub)()
hub.Clients.All.disconnectionEvent(msg)
Catch ex As Exception
_logger.LogWarning(ex, EventLogEntryType.Error)
End Try
Return MyBase.OnDisconnected()
End Function
I have had to wrap the offending line in an additional try/catch and accept that sometimes there will be no username returned.
The exception seen is:
MOAE - System.ObjectDisposedException: Safe handle has been closed
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.GetName()
at System.Security.Principal.WindowsIdentity.get_Name()
at MyProject.IncidentsHub.OnDisconnected() in C:\Projects\...\IncidentsHub.vb:line 95
Can anyone tell me why this is occurring and if there is a more reliable way to obtain this information?

vb.net Handling the server response when trying to read xml from some page

I have the following function which i use to get html source from my website
Public Function GetPageHTML(ByVal URL As String, _
Optional ByVal TimeoutSeconds As Integer = 10) _
As String
' Retrieves the HTML from the specified URL,
' using a default timeout of 10 seconds
Dim objRequest As Net.WebRequest
Dim objResponse As Net.WebResponse
Dim objStreamReceive As System.IO.Stream
Dim objEncoding As System.Text.Encoding
Dim objStreamRead As System.IO.StreamReader
Try
' Setup our Web request
objRequest = Net.WebRequest.Create(URL)
objRequest.Timeout = TimeoutSeconds * 1000
' Retrieve data from request
Try
objResponse = objRequest.GetResponse 'some times it gives an error server unavailable 503
Catch ex As WebException
MsgBox(ex.Message)
End Try
objStreamReceive = objResponse.GetResponseStream
objEncoding = System.Text.Encoding.GetEncoding( _
"utf-8")
objStreamRead = New System.IO.StreamReader( _
objStreamReceive, objEncoding)
' Set function return value
GetPageHTML = objStreamRead.ReadToEnd()
' Check if available, then close response
If Not objResponse Is Nothing Then
objResponse.Close()
End If
Catch
' Error occured grabbing data, simply return nothing
Return ""
End Try
End Function
some times the objResponse gives error "503 Server unavailable" and many other errors like 403 and so on, how can i handle each of those errors independently?
how can i make this function retry the request after sometime? problem is the try statement doesn't seem to handle this and i am not sure why i don't see the exception MsgBox but it shows the error on the debugger.
Cast the response as a HttpWebResponse object and do a Select Case of it's StatusCode Property. You'll have to clean and finish this up, but here is an example:
Select Case CType(objResponse, Net.HttpWebResponse).StatusCode
Case Net.HttpStatusCode.InternalServerError
'This is sloppy, but a quick example for one of your sub-questions.
System.Threading.Thread.Sleep(10000)
'Try again.
objResponse = objRequest.GetResponse
Case Net.HttpStatusCode.BadRequest
'Error Handling
Case Net.HttpStatusCode.OK
'Proceed as normal.
Case Else
'Error Handling
End Select