TcpClient Error - Thread was being aborted - asp.net

In my ASP.NET(VB) project, I am facing error to get XML response from remote server using TcpClient. The error is Thread was being aborted. The code in which I am facing error is given as follows.
Private Function GetCMSAPIXMLResp(ByVal strReqXml As String, ByVal strAPIIpAddr As String, ByVal strAPIPort As String) As String
Dim strRespXml As String = String.Empty
Try
objClientSocket = New TcpClient()
objClientSocket.Connect(strAPIIpAddr, strAPIPort)
If objClientSocket.Connected = True Then
objNetStrm = objClientSocket.GetStream()
Dim btOutStrm() As Byte = System.Text.Encoding.ASCII.GetBytes(strReqXml)
objNetStrm.Write(btOutStrm, 0, btOutStrm.Length)
objNetStrm.Flush()
If objNetStrm.CanRead Then
Dim lngBuffSize As Long = CLng(objClientSocket.ReceiveBufferSize)
Dim btInStream(lngBuffSize) As Byte
strbldRespXml = New StringBuilder()
Dim iNoBytesRead As Integer = 0
Do
iNoBytesRead = objNetStrm.Read(btInStream, 0, btInStream.Length)
strbldRespXml.AppendFormat("{0}", System.Text.Encoding.ASCII.GetString(btInStream, 0, iNoBytesRead))
Loop While objNetStrm.DataAvailable
strRespXml = Convert.ToString(strbldRespXml)
strRespXml = strRespXml.Replace(vbCrLf, vbNullString)
Else
lblError.Text = "Unable to read"
End If
Else
lblError.Text = "Unable to connect with remote server"
End If
Catch ex As Exception
Throw
Finally
objClientSocket = Nothing
objNetStrm = Nothing
strbldRespXml = Nothing
End Try
Return strRespXml
End Function
Actually, I just want to know at what point the error is getting and Why.
NOTE : Port opening has been done and when I do ping and telnet to remote server, getting positive response.

Related

TCPIP stream can read

I am sending and recieving messages from a unix server, all is fine and working as intended...except when I dont get a response from the server, I can confirm the server did get my message, but for whatever reason on their end they dont respond.
I am using the below code on my read, it gets to numberOfBytesRead = and hangs up my app.
If serverStream.CanRead Then
Dim myReadBuffer As Byte() = New Byte(1024) {}
Dim myCompleteMessage As StringBuilder = New StringBuilder()
Dim numberOfBytesRead As Integer = 0
Do
numberOfBytesRead = serverStream.Read(myReadBuffer, 0, myReadBuffer.Length)
If My.Settings.initCompassLive Then
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
Else
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 2, numberOfBytesRead))
End If
Loop While serverStream.DataAvailable
' MsgBox("You received the following message : " + myCompleteMessage.ToString)
returndata = myCompleteMessage.ToString
Else
MsgBox("Aauth Request Failed: " & returndata)
Exit Sub
End If
I just needed a serverStream.ReadTimeOut = bla bla bla
TYVM
MW

HTTP/2 Image load times - waiting for the last one to finish

This is baffling me. On a new server (Windows Server 2016) my images seem to be loading in synchronously. The browser is attempting to download them all at the same time, but something is stopping the image from loading until the previous one has finished. The time to first byte increases as each image is attempted to be loaded.
EDIT: I have posted my imagehandler code below, but you can see the problem exists when loading .jpg in its native format (see screenshot about half way down).
EDIT 2: I have disabled http/2 and added a screenshot.
My SVG image handler code (problem exists with image.ashx also):
Dim freshness As TimeSpan = New TimeSpan(1, 0, 0, 0)
Dim now As DateTime = DateTime.Now
Response.Cache.SetExpires(now.Add(freshness))
Response.Cache.SetMaxAge(freshness)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.Cache.VaryByParams("colour") = True
Response.Cache.VaryByParams("colour2") = True
Response.Cache.VaryByParams("svg") = True
Response.Cache.VaryByParams("rnd") = True
Response.Cache.VaryByHeaders("rnd") = True
Response.Cache.VaryByHeaders("Type") = True
Dim sSVG As String = Request.QueryString("svg").Split("-")(0)
If sSVG = String.Empty Then
Try
sSVG = Request.ServerVariables("SCRIPT_NAME").Split("-")(0)
Catch ex As Exception
sSVG = "svg"
End Try
End If
Dim xDoc As XDocument = XDocument.Load(Server.MapPath("\images\icons\svg\" & sSVG & ".svg"))
Dim sColour As String = "FFFFFF"
Dim sColour2 As String = "FFFFFF"
Dim sXML As String = xDoc.Document.ToString
If Request.QueryString("Colour") <> String.Empty Then
sColour = Request.QueryString("Colour")
Else
Try
sColour = sSVG.Split("-")(1)
Catch ex As Exception
End Try
End If
If Request.QueryString("Colour2") <> String.Empty Then
sColour2 = Request.QueryString("Colour2")
Else
Try
sColour = sSVG.Split("-")(2)
Catch ex As Exception
End Try
End If
sXML = sXML.Replace("COLOUR2", sColour2)
sXML = sXML.Replace("COLOUR", sColour)
Response.Headers.Add("Vary", "Accept-Encoding")
Response.ContentType = "image/svg+xml"
Response.Write(sXML)
HTTP/2 disabled:

Managing licenses for Office 365 in vb.net

I am trying to run Office365 cmdlets in a vb.net webservice project.The code is:
Public Function ExcutePowershellCommands() As ObjectModel.Collection(Of PSObject)
Try
Dim userList As ObjectModel.Collection(Of PSObject) = Nothing
Dim initialSession As InitialSessionState = InitialSessionState.CreateDefault()
initialSession.ImportPSModule(New String() {"MSOnline"})
Dim O365Password_secureString As New System.Security.SecureString()
Dim O365Password As String = "password"
For Each x As Char In O365Password
O365Password_secureString.AppendChar(x)
Next
Dim credential As New PSCredential("username", O365Password_secureString)
Dim connectCommand As New Command("Connect-MsolService")
connectCommand.Parameters.Add((New CommandParameter("Credential", credential)))
Dim getCommand As New Command("Get-MsolUser")
Using psRunSpace As Runspace = RunspaceFactory.CreateRunspace(initialSession)
psRunSpace.Open()
For Each com As Command In New Command() {connectCommand, getCommand}
Dim pipe As Pipeline = psRunSpace.CreatePipeline()
pipe.Commands.Add(com)
Dim results As ObjectModel.Collection(Of PSObject) = pipe.Invoke()
Dim [error] As ObjectModel.Collection(Of Object) = pipe.[Error].ReadToEnd()
If [error].Count > 0 AndAlso com.Equals(connectCommand) Then
Throw New ApplicationException("Problem in login! " + [error](0).ToString())
Return Nothing
End If
If [error].Count > 0 AndAlso com.Equals(getCommand) Then
Throw New ApplicationException("Problem in getting data! " + [error](0).ToString())
Return Nothing
Else
userList = results
End If
Next
psRunSpace.Close()
End Using
Return userList
Catch generatedExceptionName As Exception
Throw
End Try
End Function
When Connect-MsolService is run, I get this error message:
There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
I can run this function successfully within a windows App. I think some thing might be wrong in IIS. any idea?

Problems With Paypal Express Checkout Integration (WEBREQUEST)

So I was struggling with making head or tail out of the PayPal documentation and always felt that something was not right with my Webrequest.
So I stripped all the code back to basic and simply submitted the request via HTTP and the PLUS side is that I now get a response back from the PayPal sandbox server where ACK=Success and TOKEN=Valid-token-value-here there are some other variables returned too, such as CORRELATIONID and TIMESTAMP.
And hence so I tried some of the webrequest samples and I simply get a blank screen instead of being redirected to Paypal for the (sandbox) customer to complete payment.
So if anyone can post their WebRequest method that would be great.
Here is the code I used for my webrequest, I'm sure its wrong but cannot pinpoint where it is going wrong.
Also, when I run the code on my localhost during debugging, everything works fine and the call is completed with SUCCESS and a TOKEN is received.
When I run it live, I recieve Error Number 5 in the Error exception and also the text `Remote host failed to connect' in the STATUS DESCRIPTION.
THIS IS THE UPDATED CODE
Function MakeWebRequest(ByVal pUseSandbox As Boolean, ByVal pRequestMethod As String, ByVal pReturnUrl As String, ByVal pCancelUrl As String, ByRef pRtnStatus As String, ByRef pRtnStatusId As HttpStatusCode, ByRef pRtnResponseString As String) As Boolean
'
Dim _sxHost As String = Nothing
Dim _sxEndpoint As String = Nothing
Dim _sxNameValCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxResponseCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxCounta As Integer = Nothing
Dim _sxParamsString As String = Nothing
'
'-> Init
_sxParamsString = ""
MakeWebRequest = False
_sxNameValCol = New System.Collections.Specialized.NameValueCollection()
_sxResponseCol = New System.Collections.Specialized.NameValueCollection()
If pUseSandbox Then
_sxHost = "http://www.sandbox.paypal.com"
_sxEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
Else
_sxHost = "http://www.paypal.com"
_sxEndpoint = "https://api-3t.paypal.com/nvp"
End If
'-> Create Request
Try
'-> Key/Value Collection Params
_sxNameValCol.Add("METHOD", "SetExpressCheckout")
_sxNameValCol.Add("USER", _UserName)
_sxNameValCol.Add("PWD", _Password)
_sxNameValCol.Add("SIGNATURE", _Signature)
_sxNameValCol.Add("PAYMENTREQUEST_0_AMT", Format(_Basket.BasketTotalIncDelivery / 100, "0.00"))
_sxNameValCol.Add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale")
_sxNameValCol.Add("PAYMENTREQUEST_0_CURRENCYCODE", "GBP")
_sxNameValCol.Add("RETURNURL", pReturnUrl)
_sxNameValCol.Add("CANCELURL", pCancelUrl)
_sxNameValCol.Add("REQCONFIRMSHIPPING", "0")
_sxNameValCol.Add("NOSHIPPING", "2")
_sxNameValCol.Add("LOCALECODE", "EN")
_sxNameValCol.Add("BUTTONSOURCE", "PP-ECWizard")
_sxNameValCol.Add("VERSION", "93.0")
'-> UrlEncode
For _sxCounta = 0 To _sxNameValCol.Count - 1
If _sxCounta = 0 Then
_sxParamsString = _sxParamsString & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
Else
_sxParamsString = _sxParamsString & "&" & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
End If
Next
'-> Credentials (not used)
'_sxRequest.Credentials = CredentialCache.DefaultCredentials
Try
Dim _sxRequest As WebRequest = DirectCast(System.Net.WebRequest.Create(_sxEndpoint), System.Net.HttpWebRequest)
'-> Convert request to byte-array
Dim _sxByteArray As Byte() = Encoding.UTF8.GetBytes(_sxParamsString)
_sxRequest.Method = "POST" 'Our method is post, otherwise the buffer (_sxParamsString) would be useless
_sxRequest.ContentType = "application/x-www-form-urlencoded" 'We use form contentType, for the postvars
_sxRequest.ContentLength = _sxByteArray.Length 'The length of the buffer (postvars) is used as contentlength
Dim _sxPostDataStream As System.IO.Stream = _sxRequest.GetRequestStream() 'We open a stream for writing the postvars
_sxPostDataStream.Write(_sxByteArray, 0, _sxByteArray.Length) 'Now we write, and afterwards, we close
_sxPostDataStream.Close() 'Closing is always important!
'-> Create Response
Dim _sxResponse As HttpWebResponse = DirectCast(_sxRequest.GetResponse(), HttpWebResponse)
'-> Get Response Status
pRtnStatus = _sxResponse.StatusDescription
pRtnStatusId = _sxResponse.StatusCode
'-> Reponse Stream
Dim _sxResponseStream As Stream = _sxResponse.GetResponseStream() 'Open a stream to the response
'-> Response Stream Reader
Dim _sxStreamReader As New StreamReader(_sxResponseStream) 'Open as reader for the stream
pRtnResponseString = _sxStreamReader.ReadToEnd() 'Read the response string
MakeWebRequest = True
'-> Tidy up
_sxStreamReader.Close()
_sxResponseStream.Close()
_sxResponse.Close()
_sxByteArray = Nothing
_sxPostDataStream = Nothing
_sxRequest = Nothing
_sxResponse = Nothing
_sxResponseStream = Nothing
_sxStreamReader = Nothing
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "response(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "request(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
'-> Tidy Up
_sxHost = Nothing
_sxEndpoint = Nothing
_sxNameValCol = Nothing
_sxResponseCol = Nothing
_sxCounta = Nothing
_sxParamsString = Nothing
'
End Function
OK, so it's now clear that you're not getting any response from the server because your server isn't able to connect to PayPal's servers at all. Hence, you got no server-response and the message Unable to connect to the remote server. When I tested, I got a HTTP 200 response with the following body:
TIMESTAMP=2015-07-07T09:07:39Z&CORRELATIONID=7f4d2313c9696&ACK=Failure&VERSION=93.0&BUILD=17276661&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
Obviously that's because I tested with a blank username and password.
So, something is wrong with your server setup that's preventing you from making outside connections, either at the IIS level or due to your firewall configuration.
Without physically being present at your machine, there's not a lot we can do to track down what's blocking it, but you can try opening HTTP requests to other public websites like Google.com and see if those succeed.

FTPWebRequest: Transfer from one FTP to another FTP, Destination file corrupt

Here's my agonizing problem. I'm transferring from one FTP (a Dev site) to another FTP (a Test site). Spare me the thoughts of changing this process. It's out of my hands. In any case, here's my method:
Public Function TransferFile(originalFile As String, destinationFile As String) As String
Try
'FileStream for holding the file
Dim uploadRequest As FtpWebRequest = WebRequest.Create(destinationFile)
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
uploadRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
uploadRequest.UseBinary = True
uploadRequest.UsePassive = False
'connect to the server
Dim fileRequest As FtpWebRequest = WebRequest.Create(originalFile)
fileRequest.Method = WebRequestMethods.Ftp.DownloadFile
fileRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
fileRequest.UseBinary = True
fileRequest.UsePassive = False
'get the servers response
Dim response As WebResponse = fileRequest.GetResponse()
'retrieve the response stream
Dim stream As Stream = response.GetResponseStream()
CopyStream(stream, uploadRequest.GetRequestStream)
stream.Close()
response.Close()
Return "File transfered"
Catch ex As System.Security.SecurityException
Return ex.Message
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Shared Sub CopyStream(input As Stream, output As Stream)
Dim buffer As Byte() = New Byte(32767) {}
While True
Dim read As Integer = input.Read(buffer, 0, buffer.Length)
If read <= 0 Then
Return
End If
output.Write(buffer, 0, read)
End While
End Sub
This works perfectly for ASPX files and their .vb code behinds. When we try to transfer .DLL files, they show up on the server as 0 bytes, and sometimes actually transfer. The problem is that, despite being the same size as the original, they act as if they are corrupt. Does anyone have a solution?
Just a guess - use BYREF in your sub definition
Public Shared Sub CopyStream(BYREF input As Stream, BYREF output As Stream)
Closing out the output stream and getting a response from the uploadRequest worked.

Resources