Why am I getting error: BC30452 Operator '&' is not defined for types 'String' and 'Image', for this code? - vb.net

I have an application which has a server and a client file. On the server side, the server's camera (in my case, this is my camera), get's streamed to the client file, and then the clients camera (in my case, my camera because I'm using this for educational purposes only) get's streamed to the server file.
Right now I'm in the process of writing this program, but I'm getting an error when I'm trying to stream the client's camera.
This is what the client program looks like:
Now, on the Form_Load sub, this code is declared
Public Class videocallfinal
Public xxx As Integer
Public Yy As String = "|U|"
Dim pic As New Drawing.Bitmap(500, 400)
Dim Touchless As New TouchlessLib.TouchlessMgr
Dim camera1 As TouchlessLib.Camera = Touchless.Cameras.ElementAt(0)
Private Sub videocallfinal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
q.Comet.Send("camerastream" & Yy & PictureBox2.Image)
PictureBox2.Image = camera1.GetCurrentImage
Touchless.CurrentCamera = camera1
Touchless.CurrentCamera.CaptureHeight = 130
Touchless.CurrentCamera.CaptureWidth = 130
Me.BringToFront()
Me.Text = "You're currently in a video call with " + videocall.Label6.Text
Label6.Text = videocall.Label6.Text
End Sub
So, as you can see, I'm trying to send the PictureBox image to the server file on this line of code:
q.Comet.Send("camerastream" & Yy & PictureBox1.Image)
Under PictureBox1.Image, I get this error
BC30452 Operator '&' is not defined for types 'String' and 'Image'.
I've done some re-search on this issue, but it's usually with different controls, and I've never dealt with an error like this with a PictureBox.
Can someone explain what I'm doing wrong here?
Thanks!

You can convert the image to a Base64 string by using a MemoryStream to get the bytes. The following untested code, written from the docs for MemoryStream and Image, will do exactly this:
Dim s As New MemoryStream
PictureBox1.Image.Save(s, System.Drawing.Imaging.ImageFormat.Bmp)
Dim asBase64 = System.Convert.ToBase64String(s.ToArray())

Related

VB.net POST method using HTTPclient

Hello I am trying to access a webform with data. However my code does not have error but its not working. It is supposed to send me a text message using the Web API provided by the telco carrier. Any assistance and advise will be greatly appreciated.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim client As New HttpClient
Dim url = $"some url"
Dim data2 = "{""username"": ""someuname"", ""password"":""somepass"", ""msisdn:""some number"", ""content:""Hello, this is a sample broadcast"", ""shortcode_mask:""somemask""}"
Dim payload = Newtonsoft.Json.JsonConvert.SerializeObject(data2)
Dim buffer = Encoding.UTF8.GetBytes(payload)
Dim bytes = New Net.Http.ByteArrayContent(buffer)
bytes.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue("application/json")
Dim request = client.PostAsync(url, bytes)
Catch Ex As Exception
Console.WriteLine()
End Try
End Sub
End Class
There are a few issues in your code. Let me start with the most important one first:
Catch Ex As Exception
Console.WriteLine()
End Try
This code means: If an error occurs, throw away all useful information about the error that could help me find the cause, then write an empty line to the console and pretend nothing bad happened.
Don't do that. Remove the whole try-catch block, then re-run your code again. If you get an exception: That's great, because .NET is now telling you what is wrong with your code! If you understand the error message, use it to fix your code. If you don't understand it, feel free to ask the community on StackOverflow.
Second issue:
This line
Dim request = client.PostAsync(url, bytes)
starts an asynchronous web request. You don't wait for the result, so you don't know whether it succeeded or not.
You're supposed to Await async methods, but if you aren't familiar with the async/await pattern yet, I won't be able to give you all the necessary background in the single StackOverflow answer. Until you have familiarized youself with async/await, you can synchronously wait for the result by accessing the Result property of the Task that has been returned:
Dim response = client.PostAsync(url, bytes).Result
response.EnsureSuccessStatusCode()
Third issue: You JSON-serialize something which is already JSON. If your data is already JSON, just use it as the payload without calling SerializeObject.
Your data2 is a string. When you use the JSON library to serialize it, it probably isn't in the JSON structure that your URL endpoint expects. Create a Type, fill it with data, and pass that to your JsonCoverter
Thank you Heinzi, here is the final working code based on your concepts:
Public Class Form1
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New HttpClient
Dim url = $"some url"
Dim data2 = "
{""username"": ""some uname"", ""password"": ""somepass"", ""msisdn"": ""somenumber"", ""content"": ""Hello, this is a sample broadcast"", ""shortcode_mask"" :""somemask""}"
Dim buffer = Encoding.UTF8.GetBytes(data2)
Dim bytes = New ByteArrayContent(buffer)
bytes.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/json")
Dim request1 = Await client.PostAsync(url, bytes)
Dim response = client.PostAsync(url, bytes).Result
response.EnsureSuccessStatusCode()
End Sub
End Class
I can now receive text messages :)

ActiveReports not allowing overwrite of jpg after report generation. Windows. VB.NET

Currently, I am utilizing ActiveReports to implement a dynamic image via pathname into a report that is generating.
The Images are being automatically generated as .jpg to a server folder. The Active Reports module imports the files using this code.
Sub ActiveReport_ReportStart
Picture1.Image = System.Drawing.Image.FromFile("path\filename.jpg")
End Sub
The problem I am running into is that this report locks out the jpgs from being overwritten.
I am unsure what could be going wrong, but it seems that the report is still using the image files after the report has been generated.
Am I missing a "disconnect" code piece to ensure that an import doesn't allow for continued contact to the file?
I apologize if this is simple, but I can't find anything for this specific instance.
Thank you.
EDIT:
I attempted to get around the lockout by copying them into their own variable. But this didn't work either.
Sub ActiveReport_ReportStart
dim TempImage as Image = Image.FromFile("path\filename")
Picture1.Image = TempImage
End Sub
You can use "Using" block to make sure that the object of the image is disposed as soon as its usage is completed.
Using statement basically marks a boundary for the objects specified in the statement. So when code block using Using – End Using is exited either after normal execution or some exception cause, the framework invokes the Dispose method of these objects automatically.
Here is the suggested code which can be helpful for you in resolving the issue:
Private Sub SectionReport1_ReportStart(sender As Object, e As EventArgs) Handles MyBase.ReportStart
Dim img As Image
Using bmpTemp = New Bitmap("path\filename.jpg")
img = New Bitmap(bmpTemp)
End Using
Picture1.Image = img
End Sub
I was able to get this to work by creating a function that used the Graphics.FromImage method and disposed the original file.
Public Function GetImageFile(ByVal pathfn As String) As Image
Dim tempImg As Image = Image.FromFile(pathfn)
Dim tempBtm As New Bitmap(Width:=img.Width*CorrectFactor, Height:=img.Height*CorrectFactor, Format:=tempImg.PixelFormat)
Using g As Graphics = Graphics.FromImage(bm)
g.DrawImage(tempImg, Point.Empty)
End Using
tempImg.Dispose()
Return tempBtm
End Function
The item that would be placed in the report would be as follows.
Sub ActiveReport_ReportStart
Picture1.Image = GetImageFile("Path\Filename")
End Sub

How do I upload data to a server with valid SSL certificate using a client vb.net program?

I am working on a program and uploads a shipping manifest to a the shippers website. When I try to upload, I get a nondescript error back from their server, and when checking with the shipper, they tell me that "there is an issue with the SSL" I am using.
I've spent quite a bit of time piecing together code that, from what I seem to understand, is supposed to work, but I'm not making any progress. As far as I know everything else is fine with the upload, but there is a problem with my SSL certificate
If I understand what this code is supposed to do correctly, I should get a certificate from the shippers website, which allows certification to my program for a space of time during which I can upload the data. I'm really not sure that this is what my code is doing at all, but the only code examples I have seen show it something like this.
Here's my code with the URLs changed:
'This references a custom class that compiles the manifest I'm going to upload
Dim StringToUpload As String = Compile_Manifest(MyDate, UseTestDB)
Dim webClient As New System.Net.WebClient
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials
'From what I understand,
'this is supposed to set up properties used in next section of code
System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3
System.Net.ServicePointManager.ServerCertificateValidationCallback = _
AddressOf AcceptAllCertifications
'I can see that this reaches the server,
'but I don't know how it relates to the next section of code
'that actually uploads the manifest
Dim ServerRequest As System.Net.WebRequest = _
System.Net.WebRequest.Create("https://www.certify.some-shippper.com:443/somefolder")
Dim ServerResponse As System.Net.WebResponse
ServerResponse = ServerRequest.GetResponse()
ServerResponse.Close()
'This code works for the upload of the manifest,
'and it seems the above code is unrelated and does not use a SSL certificate.
'When this code runs I get the same error back from the shippers server,
'indicating an issue with my SSL, with or without the two sections of code above.
Dim StrResult As String = ""
Dim WrappedString As String = TransmitPLD.WrapPldFile(StringToUpload)
'This references a custom class that wraps the data to upload
'in information from the shipper.
Dim ByesToUpload As Byte() = _
System.Web.HttpUtility.UrlEncodeToBytes(WrappedString, _
System.Text.ASCIIEncoding.ASCII)
Dim Result As Byte() = _
webClient.UploadData("https://www.certify.some-shippper.com:443/somefolder", _
ByesToUpload)
StrResult = System.Web.HttpUtility.UrlDecode(Result, _
System.Text.ASCIIEncoding.ASCII)
MessageBox.Show(StrResult)
So it turns out I went about it the wrong way. I needed to upload my data through System.Net.WebRequest and it takes care of the certificates for me. Not implementing all the parts of the code I needed, it didn't handle the retrieval of the shipper's certificate.
In case anyone else gets confused about the matter like I did, here's my working code for anyone to see, adapt and use. My resource for fixing the code (and by that I mean starting from scratch) was the MSDN page for the WebRequest class, and it has code examples much the same as what I have below in C++, C#, and VB.NET and here is the link.
First there are some global variables that need to be set and class that needs to be created for to store the upload response:
' This is set in the function that Upload function
' and uploads the data in the ReadCallback sub
Private Shared WrappedString As String
' This is used to wait for the callback in the Upload function
Private Shared allDone As New Threading.ManualResetEvent(False)
Friend Class RequestState
' This class stores the request state of the request.
Public request As Net.WebRequest
Public Sub New()
request = Nothing
End Sub ' New
End Class ' RequestState
Then there is a sub needed for the upload part web request which will be called further below in the upload function:
Private Shared Sub ReadCallback(asynchronousResult As IAsyncResult)
Try
Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
Dim myWebRequest As Net.WebRequest = myRequestState.request
' End the request.
Dim streamResponse As IO.Stream = myWebRequest.EndGetRequestStream(asynchronousResult)
' Convert the string into a byte array.
Dim byteArray As Byte() = System.Text.Encoding.ASCII.GetBytes(WrappedString)
' Write the data to the stream.
streamResponse.Write(byteArray, 0, byteArray.Length)
streamResponse.Close()
' Allow the main thread to resume.
allDone.Set()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
End Sub ' ReadCallback
Finally, this is the function that should be called to upload the data, which uses all the code above:
Public Shared Function Upload(ByVal MyDate As Date) As String
Dim StrResult As String = ""
UploadSucess = False
Try
' This is my code that builds the manifest that I want to upload
Dim StringToUpload As String = Compile_PLD200(MyDate)
WrappedString = TransmitPLD.WrapPldFile(StringToUpload)
Dim myWebRequest As Net.WebRequest
myWebRequest = Net.WebRequest.Create("https://www.some.website.com:443/someplace")
' Create an instance of the RequestState and assign
' myWebRequest to it's request field.
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
myWebRequest.ContentType = "multipart/mixed; boundary=BOUNDARY"
myRequestState.request.Method = "POST"
' Start the asynchronous 'BeginGetRequestStream' method call.
Dim r As IAsyncResult = CType(myWebRequest.BeginGetRequestStream(AddressOf ReadCallback, myRequestState), IAsyncResult)
' Pause the current thread until the async operation completes.
allDone.WaitOne()
' Send the Post and get the response.
Dim myWebResponse As Net.WebResponse = myWebRequest.GetResponse()
Dim streamResponse As IO.Stream = myWebResponse.GetResponseStream()
Dim streamRead As New IO.StreamReader(streamResponse)
Dim readBuff(256) As [Char]
Dim count As Integer = streamRead.Read(readBuff, 0, 256)
While count > 0
Dim outputData As New [String](readBuff, 0, count)
Console.WriteLine(outputData)
count = streamRead.Read(readBuff, 0, 256)
StrResult += outputData
End While
' Close the Stream Object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse Resource.
myWebResponse.Close()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
Return StrResult
End Function ' Upload
Again here is the MSDN page for the WebRequest class which has a code example too.
Hope this helps anyone who was stuck like I was. And any criticisms as to the implementation of the code are welcome. This just happen to do what I want, I can't say it is the most efficient implementation.

code that doesn't work...Kill-process , search-for-file , streamwrite on file searched file

can you help me with that code ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\"
For Each app As Process In Process.GetProcesses
If app.ProcessName = "notepad" Then
app.Kill()
End If
Next
Dim result As String
Dim servprop() As String
servprop = System.IO.Directory.GetFiles(x, "server.*")
For Each file In servprop
result = Path.GetFileName(file)
Next
Dim z As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\" & result.ToString
Dim t As StreamWriter = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Close()
End Sub
so... I got a button (button1) that finds if notepad is opened and kills it.
Then it searches for "server.Properties" in "x" location
if server.properties is found , then "result" will get his name (server)
"z" is the file location where streamwriter must write the text from textbox1 .
And it doesn't work... streamwirter is not writing on server.properties ... why ?
mention : I'm just a kid :D and i'm trying to learn by myself visual basic .
If you have only one file called "server.properties" then you could remove all the code that search for this file and write it directly.
Dim z As String
z = System.IO.Path.Combine(x, "server.properties")
Using t = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Flush()
End Using
Regarding the error, encapsulating the writing code with a proper using statement ensures a complete clean-up. Also adding a call to Flush() is probably not necessary, but doesn't hurt.

vb.net: listbox.items.add() throws exception in same class

I'm not even sure I understand this situation enough to come up with a proper title. I come from a modest understanding of VB6 and having to climb a steep learning curve for VB 2010.
I am trying to create a multi-client server program that will communicate with my Enterprise iPhone app. I found a relatively simple example to build upon here: http://www.strokenine.com/blog/?p=218. I have been able to modify the code enough to make it work with my app, but with one glitch: I can't get access to the controls on the form to add items, even though the method is invoked within the form's class. (I tried this on the original code too, and it does the same thing. I don't know how the author managed to get it to work.)
Here's the code segment in question:
Public Class Server 'The form with the controls is on/in this class.
Dim clients As New Hashtable 'new database (hashtable) to hold the clients
Sub recieved(ByVal msg As String, ByVal client As ConnectedClient)
Dim message() As String = msg.Split("|") 'make an array with elements of the message recieved
Select Case message(0) 'process by the first element in the array
Case "CHAT" 'if it's CHAT
TextBox3.Text &= client.name & " says: " & " " & message(1) & vbNewLine 'add the message to the chatbox
sendallbutone(message(1), client.name) 'this will update all clients with the new message
' and it will not send the message to the client it recieved it from :)
Case "LOGIN" 'A client has connected
clients.Add(client, client.name) 'add the client to our database (a hashtable)
ListBox1.Items.Add(client.name) 'add the client to the listbox to display the new user
End Select
End Sub
Under Case "LOGIN" the code tries to add the login ID to the listbox. It throws an exception: "A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll" The listbox (all controls, for that matter) is in the same class, Server.vb and Server.vb [Design].
The data comes in from another class that is created whenever a client logs on, which raises the event that switches back to the Server class:
Public Class ConnectedClient
Public Event gotmessage(ByVal message As String, ByVal client As ConnectedClient) 'this is raised when we get a message from the client
Public Event disconnected(ByVal client As ConnectedClient) 'this is raised when we get the client disconnects
Sub read(ByVal ar As IAsyncResult) 'this will process all messages being recieved
Try
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ex As Exception
Try 'if an error occurs in the reading purpose, we will try to read again to see if we still can read
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ' IF WE STILL CANNOT READ
RaiseEvent disconnected(Me) 'WE CAN ASSUME THE CLIENT HAS DISCONNECTED
End Try
End Try
End Sub
I hope I am making sense with all this. It all seems to bounce back and forth, it seems so convoluted.
I've tried using Me.listbox1 and Server.listbox1 and several other similar structures, but to no avail.
I'm reading a lot about Invoke and Delegates, but would that be necessary if the method and the control are in the same class? Or do I have a fundamental misperception of what a class is?
Many thanks for any help I can get.
Private Delegate Sub UpdateListDelegate(byval itemName as string)
Private Sub UpdateList(byval itemName as string)
If Me.InvokeRequired Then
Me.Invoke(New UpdateListDelegate(AddressOf UpdateList), itemName)
Else
' UpdateList
' add list add code
ListBox1.Items.Add(itemName)
End If
End Sub
Add above, then replace:
ListBox1.Items.Add(client.name)
to
UpdateList(client.name)
Does it work? check the syntax, may have typo as I type it.