Add Image to ListView using base64 - vb.net

I have server and client
I want that when the client connects to the server, the connected one has an image on the listview
The thing is that on the client side
I cannot use imagelist and resources
I want to add image with base64 code
But I can't do it
I tried to do it with the given client side code
Function getImage() As String
Try
Dim float2= Convert.FromBase64String("base64code")
Using flag8 = New MemoryStream(float2, 0, imageBytes.Length)
Return Image.FromStream(flag8 , True)
End Using
Catch ex As Exception
Return "-"
End Try
End Function

Related

Is there a way to retrieve text from a webpage to a TextBox in VB.NET?

Let say I have a TextBox1 and a SaveButton. A website "www.example.com/code1.text" with just a content:
303981
How to retrieve this 303981 to a TextBox?
Do we need a WebBrowser1?
Please help me I'm self learning and beginner also.
Look at the System.Net.WebClient type.
Using wc As New WebClient()
TextBox1.Text = wc.DownloadString("www.example.com/code1.text")
End Using
You need to place a webbrowser control on your form. I would use CefSharp for this
(see: https://www.youtube.com/watch?v=6d-AgfFzr70)
then you can do something like:
settings = New CefSettings
CefSharp.Cef.Initialize(settings)
browser = New ChromiumWebBrowser("www.google.com")
Which loads google.com, just change it to the page you want to load.
Now check your website and see if you can get that textbox value by javascript from the console (F12). Check the source if you can access it with it's ID or that you need to use it's class.
for example:
document.getElementsByClassName('textboxclass')[0].value;
if you manage to get the right value back in your browser console, you can go ahead in your program and do somethinh like:
Dim task As Task(Of JavascriptResponse) = browser.EvaluateScriptAsync(code)
where code contains your javascript.
you may do something like:
task.ContinueWith(
Sub(t)
Try
If t.IsFaulted = False And t.Result IsNot Nothing Then
Dim response = t.Result 'Error: Result is not a member of Task'
If response.Success And response.Result IsNot Nothing Then
taskResult = response.Result
Else
taskResult = "bad result"
End If
End If
Catch ex As Exception
'Dbg("!!!!!!!!!!!!!!! Exception: " & ex.ToString)
taskResult = ex.ToString
End Try
End Sub)
to get the result in a string.

Hide Picturebox if image is invalid

I am creating reports using Telerik Reporting Tool and has some image on it. I display the Image in the picturebox using a URL that came from the clients but there are instances where the given URL is invalid so it will display an error message in the report. I want to just hide the picturebox whenever the Image is not available so that the error will not appear in the report. how can I do it? thanks in advance :)
Do a webrequest on your website.
For example:
Public Sub Run()
Dim myReportImage As Image = GetControl("ReportImage")
myReportImage.Visible = CheckWebImage()
' or
myReportImage.Enabled = CheckWebImage()
End Sub
Private Function CheckWebImage() As Boolean
Dim url As New System.Uri("http://www.url.com/yourImage.jpg")
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(url)
Dim response As System.Net.WebResponse
Try
response = req.GetResponse()
response.Close()
request = Nothing
Msgbox("Website Found!")
Return True
Catch ex As Exception
request = Nothing
Msgbox("Website not found. Check the url and internet connection")
Return False
End Try
End Sub

Move files only if they are image format

i just would like to be sure whether i missed something in my code or not. I want to validate before moving my files from one folder to another that file is image. I prepared this function and usegae like below. Can you please tell me is it ok? Do i need some dispose or anything else or its just quit enought. many thanks, cheers.
Function IsValidImage(filename As String) As Boolean
Try
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
img.Dispose()
Catch generatedExceptionName As OutOfMemoryException
' Image.FromFile throws an OutOfMemoryException
' if the file does not have a valid image format or
' GDI+ does not support the pixel format of the file.
'
Return False
End Try
Return True
End Function
If IsValidImage("c:\path\to\your\file.ext") Then
'do something
'
Else
'do something else
'
End If
Let the file path be "D:\web\sample\Image\my.Image.png" then you can check whether the file is an image file or not using the following code:
Dim filepath As String = "D:\web\sample\Image\my.Image.png"
Dim imageExtensions() As String = {"bmp", "gif", "jpg", "png", "psd", "psp", "thm", "tif", "yuv"}
Dim pat As String = "\\(?:.+)\\(.+)\.(.+)"
Dim r As Regex = New Regex(pat)
Dim m As Match = r.Match(filepath)
If imageExtensions.Contains(m.Groups(2).Captures(0).ToString()) Then
MsgBox("valid Image")
End If
You are on the right way, but you should make up your mind what you want to whant to gain:
If you want to develop a method telling you wheter the content of a file is considered a .Net recognized picture image, your approach is totally fine.
I start with your (slightly) overworked code:
Function IsValidImage(filename As String) As Boolean
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
' the file could be opened as image so it is valid
Return True
End Using
Catch notValidException As OutOfMemoryException
' Image.FromFile throws an OutOfMemoryException
' if the file does not have a valid image format or
' GDI+ does not support the pixel format of the file.
'
Return False
End Try
' Every other Exception is considered not to be able too look whether the
' file is an Image or not, so it should be thrown to outside
End Function
Don't misjudge this approach as using Exception for control flow, you are only reacting to the one thrown if the content of the file is not usable for creating an Image. This let's the decision on the framework whether the file is valid for an Imageor not.
Let's refine your Method a little bit, so that you can determine wheter the image in the file does not exceed a given size:
Function IsValidImage(filename As String, maxSize As Size) As Boolean
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
' Returns True if the image is smaller or equal than maxSize
Return img.Size.Width <= maxSize.Width AndAlso
img.Size.Height <= maxSize.Height
End Using
Catch notValidException As OutOfMemoryException
Return False
End Try
End Function
Also this is not a misuse of Exceptions. It is a practice of fail fast: if I can't get an Image the file is not an Image. Otherwise I check the dimension on the opened Image, making my outcome dependent on operations done with it.
Misusing an Exception for control flow could, but must not be the following:
Sub CheckImage(filename As String)
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
End Using
Catch notValidException As OutOfMemoryException
Throw New FileIsNoImageException()
End Try
End Sub
Try
CheckImage("c:\path\to\your\file.ext")
'do something
'
Catch invalid As FileIsNoImageException
'do something else
'
End Try
Even this approach has a valid usage if you consider a file not beeing an Image as an error.
But normaly you would do this in functions which give you the Image as return value.
But this is a tottaly no go:
Sub CheckImage(filename As String)
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
Throw New FileIsImageException() ' DON'T DO SUCH A CRAP
End Using
Catch notValidException As OutOfMemoryException
Throw New FileIsNoImageException()
End Try
End Sub
Try
CheckImage("c:\path\to\your\file.ext")
Catch valid As FileIsImageException
'do something
'
Catch invalid As FileIsNoImageException
'do something else
'
End Try
#Tim, I beg your pardon, but I can't hear this Exception use is a bad practice tale any more.

How to put noone image in image column of datagridview

I have to put an image to specific column of datagridview but not in every row.
If getExists(myTable, CInt(reader.GetValue(0)), dbConn) Then
.Cells("myCol").Value = Image.FromFile("C:\myPath\myIco_16x16.ico")
Else
.Cells("myCol").Value = "" ' error here
End If
With this code I get error while executing probably because I'm try to put a string in image column. Second I try is:
.Cells("myCol").Value = Nothing
This don't cause error but put "error image" picture (with red X) to grid.
Is here a way to put no one image (blank) to datagridview's image column without loading a "blank image" from file or resource?
I've had to do this in the past and just used a 1 pixel transparent PNG. The performance was acceptable in my application even with 18 image columns and ~2000 rows and the background color of the cell shows through it just fine.
You should be able to create a 1x1 pixel transparent PNG fairly easily using a free program such as "Paint.Net".
You could just create a temporary blank bitmap and assign this to rather than loading an image from file.
Friend Function BlankImage() As Image
Try
Dim oBM As New Bitmap(1, 1)
oBM.SetPixel(0, 0, Color.Transparent)
Return oBM
Catch ex As Exception
Return Nothing
End Try
End Function
Slightly better method that can improve performance:
Friend Function BlankImage() As Image
Static oBM As New Bitmap(1, 1)
Try
If oBM Is Nothing Then
oBM.SetPixel(0, 0, Color.Transparent)
End If
Return oBM
Catch ex As Exception
Return Nothing
End Try
End Function

Creating instances of forms inside a thread

i am trying to create a new instance of a form if its not allready been created the only problem is is that the instance creation is inside a thread.
Private Sub doRead(ByVal ar As System.IAsyncResult)
Dim totalRead As Integer
Try
totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
End Try
If totalRead > 0 Then
'the readBuffer array will contain everything read from the client.
Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
messageReceived(receivedString)
End If
Try
client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
MessageBox.Show(ex.ToString)
End Try
End Sub
The problem lies when the form is created on the line .showDialog() it stops here untill the application is closed. ive tryed using .show() but then the new "Convo window just hangs"
Private Sub messageReceived(ByVal message As String)
Dim data() As String = message.Split("|"c)
Select Case data(0)
Case "MESSAGE"
Dim chatDialog As New RichTextBox
Try
If conversations.ContainsKey(data(1)) Then
Dim convoWindow As ChatWindow
convoWindow = New ChatWindow
convoWindow = conversations.Item(data(1))
chatDialog = convoWindow.RichTextBox1
Else
Try
Dim convoWindow As New ChatWindow()
conversations.Add(data(1), convoWindow)
convoWindow = conversations.Item(data(1))
convoWindow.ShowDialog()
chatDialog = convoWindow.RichTextBox1
AppendTextChatWindows(data(2), chatDialog)
Thanks
Houlahan