How to trim a message recieved from tcpClient.GetStream() - visual-studio-2010

I have the following code which recieves input from an agent application I have also developed.
I am trying to trim down all the additional whitespace that comes from the agent but regardless of what I do, the result still has a length of 8192. here is what I have so far...
Private Sub HandleClientComm(ByVal client As Object)
Dim tcpClient As TcpClient = DirectCast(client, TcpClient)
Dim clientStream As NetworkStream = tcpClient.GetStream()
Dim message As Byte() = New Byte(8191) {}
Dim bytesRead As Integer
Dim result As String
While True
message = New Byte(8191) {}
bytesRead = 0
Try
bytesRead = clientStream.Read(message, 0, 8191) 'blocks until a client sends a message
Catch
bytesRead = 0
End Try
result = ""
result = System.Text.Encoding.Default.GetString(message).ToString.Trim
Logger(result.Length)
Logger("""" & result & """", "RECV")
the result.Length = 8192 and the result itself is still a large string with trailing whitespace. I have tried many things to try and get rid of it..
result = CType(result,String).Trim
result = trim(result)
The result never changes, and now I'm stuck.
Any help, appreciated of course!
Thanks

It was null bytes... This fixed it.
result = result.Trim(result.Trim(chr(0)))

Related

How to add data in UDT of SAP B1 in SDK?

I have a problem of adding record in UDT of SAP B1 in SDK.
ALL MY CODES
Public Class SystemForm
Private oCompany As SAPbobsCOM.Company
Private WithEvents SBO_Application As SAPbouiCOM.Application
Private Sub SetApplication()
Dim SboGuiApi As SAPbouiCOM.SboGuiApi
Dim sConnectionString As String
SboGuiApi = New SAPbouiCOM.SboGuiApi()
sConnectionString = Command()
SboGuiApi.Connect(sConnectionString)
SBO_Application = SboGuiApi.GetApplication()
End Sub
Public Sub New()
MyBase.New()
SetApplication()
End Sub
Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
If pVal.FormTypeEx = "UDO_FT_RPRL" AndAlso pVal.ActionSuccess = False AndAlso pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED AndAlso pVal.ItemUID = "2" AndAlso pVal.FormMode = 3 Then
Dim oUsrTbl As SAPbobsCOM.UserTable
Dim Res As Integer
oCompany = New SAPbobsCOM.Company
oUsrTbl = oCompany.UserTables.Item("#TODD")
oUsrTbl.Code = "1"
oUsrTbl.Name = "189"
oUsrTbl.UserFields.Fields.Item("U_Amount").Value = 4000
Res = oUsrTbl.Add()
If Res = 0 Then
SBO_Application.MessageBox("Added")
Else
SBO_Application.MessageBox("Error, failed to add Record")
End If
End If
End Sub
End Class
I tried to do research but not help
Actually what I want to do is if I click on Add button of UDO then it updates my UDT called #TODD, but if I click Add button above codes bring the following error message " Addon 9000058 failed with exception; Event Type: 1".
Please anyone can help me
You are missing a call to the Connect() method of DIAPI after creating the instance oCompany. Before calling this you need to set the connection context, either by specifying the server and login, or getting the session context from your UI-API connection. Assuming your UI-API object is called SBO_Application:
Dim Cookie as String = oCompany.GetContextCookie()
Dim conStr as String = SBO_Application.Company.GetConnectionContext(Cookie)
oCompany.SetSboLoginContext(conStr)
oCompany.Connect()
(untested code)
Obviously you'll probably want to check the Connect call succeeds before continuing.
This is the code I am using which connects and in my case sets up an 'oCompany' object that can be used for transactions and 'DoQuery' queries.
SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company();
oCompany.CompanyDB = "DATABASE_NAME";
oCompany.Server = "FTHANA01:30015"; // Your server name goes here
oCompany.LicenseServer = "FTHANA01:30000";
oCompany.SLDServer = "FTHANA01:40000";
oCompany.DbUserName = "SAPSYSTEM";
oCompany.DbPassword = psw1;
oCompany.UserName = "SAP Username";
oCompany.Password = psw2;
// We are using a SAP Hana database
oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB;
oCompany.UseTrusted = true;
int ret = oCompany.Connect();
string errMsg = oCompany.GetLastErrorDescription();
int ErrNo = oCompany.GetLastErrorCode();
if (ErrNo != 0)
(we have an error)
else
(success)
Database login credentials and user login credentials are both needed.

Visual Basic split function

Ok so now I'm not getting an error but instead of everything being posted in the listbox it only contains the first line of text from the .txt file. This is the code I changed it too:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim inFile As IO.StreamReader
If IO.File.Exists("StudentList.txt") = True Then
inFile = IO.File.OpenText("StudentList.txt")
For index As Integer = 0 To inFile.Peek = -1
Dim splits = inFile.ReadLine.Split(","c)
Member(index).ID = splits(0)
Member(index).lastName = splits(1)
Member(index).firstName = splits(2)
Member(index).middleName = splits(3)
Member(index).grade = splits(4)
Member(index).period = splits(5)
ListBox1.Items.Add(Member(index).ID.PadLeft(10) & " " & Member(index).lastName & " " & Member(index).firstName)
Next
inFile.Close()
Else
MessageBox.Show("error", "error", MessageBoxButtons.OK)
End If
End Sub
The problem is that you're trying to assign a string array to a Member. That is, you have:
Member(index) = infile.ReadLine.Split(",", c);
You need to assign each field:
Dim splits = infile.ReadLine.Split(",", c);
Member(index).ID = splits(0);
Member(index).lastName = splits(1);
... etc.
Update after OP edit
I suspect the problem now is that your For loop is executing only once, or index isn't being incremented. I don't know where you came up with that wonky infile.Peek = -1 thing, but I suspect it doesn't work the way you think it does. Use something more conventional, like this.
Dim index As Integer = 0
For Each line As String In File.ReadLines("StudentList.txt")
Dim splits = line.Split(",", c)
Member(index).ID = splits(0)
' etc.
ListBox1.Add(...)
Index = Index + 1
Next

Writing GetResponseStream to file is taking long

I have made a SSRS Bulk reporter that queries a report from SSRS using a HTTPWebRequest and a HTTPWebResponse to get the stream and save it as a file to a PDF.
However, the client has complained that this is taking long. I have tested it, and this function is taking +- 15.5seconds. If I put a break in-between the GetResponseStream and the file-writer, and I wait for about 3 seconds before stepping to the next part, it shaves 4 seconds off the total time?
Can anyone explain this/or give some advise as to make it a bit faster?
This is the function:
Public Function ExportReport(ByVal QueryStringParameters As String, ByVal FileName As String) As String
Dim PDFName As String = ReportFolderPath & FileName & ".pdf"
'Create a http request or connecting to the report server.
Dim ReportHTTPRequest As HttpWebRequest = Nothing
'Create a http response to catch the data stream returned from the http request.
Dim ReportHTTPResponse As HttpWebResponse = Nothing
'Create a stream to read the binary data from the http reponse.
Dim ReportStream As Stream = Nothing
Dim ReportFileStream As FileStream = Nothing
'Create an array of bytes to get the binary data from the stream.
Dim ReportBytes As Byte()
Dim ReportBuffer As Integer = 204800
Dim ReportBytesRead As Integer = 0
'Create a webrequest to get the report with all the report parameters included.
ReportHTTPRequest = WebRequest.Create(ReportServerURL & QueryStringParameters)
ReportHTTPRequest.Credentials = CredentialCache.DefaultCredentials
'Get the response from the request.
ReportHTTPResponse = ReportHTTPRequest.GetResponse()
'Read the binary stream from the http response.
ReportStream = ReportHTTPResponse.GetResponseStream()
ReportBytes = New Byte(ReportBuffer) {}
ReportBytesRead = ReportStream.Read(ReportBytes, 0, ReportBuffer)
ReportFileStream = New FileStream(PDFName, FileMode.Create)
Do While ReportStream.CanRead And ReportBytesRead > 0
ReportFileStream.Write(ReportBytes, 0, ReportBytesRead)
ReportBytesRead = ReportStream.Read(ReportBytes, 0, ReportBuffer)
Loop
ReportHTTPResponse.Close()
ReportStream.Close()
ReportFileStream.Close()
Return PDFName
End Function
a magic thing that worked for me, try a buffer size of 32768

debug not stepping into while trying to deserialize with XMLSerializer? visual studio 11

I'm attempting to deserialize an object and when I click 'step into' on this first line of code, I get returned to the form as if I clicked continue. The If Else statements never execute.
c = CType(x.Deserialize(mobjClient.GetStream), Cereal)
If c.text.Length > 0 Then
RaiseEvent LineReceived(Me, c.text)
Else
RaiseEvent CardReceived(Me, c)
End If
here is the code that precludes that
Dim x As New XmlSerializer(GetType(Cereal))
Dim c As New Cereal
Stepping through the serializing code from the client side seems to work fine. Here is my Cereal class in case you all need it. mobjClient.getStream is a TcpClient Stream.
<Serializable> Public Class Cereal
Public id As Integer
Public cardType As Type
Public attacker As String
Public defender As String
Public placedOn As String
Public attack As Boolean
Public placed As Boolean
Public played As Boolean
Public text As String
Public Sub New()
End Sub
End Class
This is how I fixed it..... Finally figured out how to correctly serialize and deserialize data.
Dim c as New Cereal
c.text = "Testing...."
Dim bf As New BinaryFormatter
Dim ms As New MemoryStream
Dim b() As Byte
'serializes the Cereal to the created memory stream
bf.Serialize(ms, c)
'converts and moves into the byte array
b = ms.ToArray()
ms.Close()
'send the byte array
SyncLock mobjClient.GetStream
mobjClient.GetStream.Write(b, 0, b.Length)
End SyncLock
and here is the deserialization...
Dim intCount As Integer
Try
SyncLock mobjClient.GetStream
'returns the number of bytes to know how many to read
intCount = mobjClient.GetStream.EndRead(ar)
End SyncLock
'if no bytes then we are disconnected
If intCount < 1 Then
MarkAsDisconnected()
Exit Sub
End If
Dim bf As New BinaryFormatter
Dim c As New Cereal
'when data first comes on the stream it is sent to arData, then this puts into memory stream
Dim ms As New MemoryStream(arData)
'cut off the memory stream at the end of the data
ms.SetLength(intCount)
'deserialize to the created Cereal, giving us a replica of what was sent
c = bf.Deserialize(ms)
ms.Close()
'starts the listener again
mobjClient.GetStream.BeginRead(arData, 0, 3145728, AddressOf DoRead, Nothing)
If c.text IsNot Nothing Then
DisplayText(c.text)
ElseIf c.OppUserID IsNot Nothing Then
OnConnected(c.OppUserID, c.OppGender)
ElseIf c.command IsNot Nothing Then
OnCommandReceived(c)
ElseIf c.hasDeck = True Or c.hasBsDeck = True Or c.hasHand = True Then
OnDeckReceived(c)
ElseIf c.discard = True Then
OnDiscard(c)
Else
OnCardReceived(c)
End If
Catch e As Exception
MarkAsDisconnected()
End Try
The serializer is marked with DebuggerStepTrough. Manually place a breakpoint on your custom code if you want to break there.

Using ItextSharp I am getting Unbalanced begin/end text operators. But they are Matched

I working on a app that uses ItextSharp to generate PDF files for students to print name tags and parking permits... However it keeps throwing: Unbalanced begin/end text operators. at the doc.close()
The blocks appear to be properly openned and closed.. Below is the function:
Function ID_and_Parking(ByVal id As Integer) As ActionResult
Dim _reg_info As reg_info = db.reg_info.Single(Function(r) r.id = id)
Dim _conf_info As conf_info = db.conf_info.Single(Function(f) f.id = 0)
Dim _LastName As String = _reg_info.last_name
Dim _Employer As String = _reg_info.business_name
Dim _Class_1 As String = _reg_info.tues_class
Dim _Class_2 As String = _reg_info.wed_class
Dim _Class_3 As String = _reg_info.thur_class
Dim _Class_4 As String = _reg_info.fri_class
Dim _BeginDate As String = _conf_info.conf_start_date
Dim _endDate As String = _conf_info.conf_end_date
If IsDBNull(_reg_info.tues_class) Then
_Class_1 = ""
End If
If IsDBNull(_reg_info.wed_class) Then
_Class_2 = ""
End If
If IsDBNull(_reg_info.thur_class) Then
_Class_3 = ""
End If
If IsDBNull(_reg_info.fri_class) Then
_Class_4 = ""
End If
'Dim pdfpath As String = Server.MapPath("PDFs")
'Dim imagepath As String = Server.MapPath("Images")
Dim pdfpath As String = "C:\temp\"
Dim imagepath As String = "C:\temp\"
Dim doc As New Document
doc.SetPageSize(iTextSharp.text.PageSize.A4)
doc.SetMargins(0, 0, 2, 2)
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfpath + "/Images.pdf", FileMode.Create))
doc.Open()
Dim cb As PdfContentByte = writer.DirectContent
cb.BeginText()
cb.SetTextMatrix(100, 400)
cb.ShowText(_LastName)
cb.EndText()
doc.Add(New Paragraph("JPG"))
Dim jpg As Image = Image.GetInstance(imagepath + "/Asads_Tags.jpg")
jpg.Alignment = iTextSharp.text.Image.UNDERLYING
jpg.ScaleToFit(576, 756)
doc.Add(jpg)
Catch dex As DocumentException
Response.Write(dex.Message)
Catch ioex As IOException
Response.Write(ioex.Message)
Catch ex As Exception
Response.Write(ex.Message)
Finally
doc.Close()
End Try
Return RedirectToAction("Index")
End Function
Anyone know where I could be going wrong at??????
The Try Catch block is what caused the unbalanced start/end exception.....Once I moved the doc.close() up to the bottom of try the error went away... Oh well maybe someone else will need the insight... –

Resources