Hide Picturebox if image is invalid - vb.net

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

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.

How to get HTML Document height using CEFSHARP?

I'm changing a web browser application to use the CEFSHARP chromium based browser instead of the inbuilt vb.net web browser control and need to query the html document to be able to set the browser control height to the height of the html page. In the VB web browser control I've used the following to set the height.
WebBrowser.Height = WebBrowser.Document.Body.ScrollRectangle.Height
WebBrowser.Height = WebBrowser.RectangleToScreen
How can you get the HTML document properties in CEFSHARP? I have been looking through a number for threads and it seems to be that you need to do a javascript call but I'm unable to find a simple example. Anyone have any experience trying to do this with CEFSHARP?
Below is the code I'm attempting to use to get the height of the HTML document but it doesn't work. I'm fairly sure its the script line that is wrong but cant seem to find the right syntax to just get the document height.
Private Sub WWWBrowser_LoadingState(sender As Object, e As LoadingStateChangedEventArgs) Handles WWWBrowser.LoadingStateChanged
If e.IsLoading = False Then
Dim script = "(function() { var body = document.body, html = document.documentElement; return Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); })();"
Dim task As Task(Of JavascriptResponse) = WWWBrowser.EvaluateScriptAsync(script)
Dim taskResult As String
task.ContinueWith(
Sub(t)
If t.IsFaulted = False 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
End If
End If
End Sub)
MsgBox(task.Result.Result)
End If
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.

VB.NET | HttpWebRequest, How to see if the host is online?

I am coding a whitelist for my application in VB.NET.
I am using the HttpWebRequest Method and HttpWebResponse.
If the Whitelist Host is down, the whitelist is bypassed and the program is available to anyone which is a vulnerability.
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
End Try
Return S
End Function
I want to give the user an error if the website is down, any ideas?
Regards.
What is your error condition? This function alone doesn't prevent anything from happening in the event of an exception. The function still exits with returning a string. So any consuming code would have to look for error conditions and handle them accordingly.
If the request fails, you should meaningfully handle the exception. Two ideas off the top of my head would include:
1) Let the exception bubble up the stack:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Return S
End Function
This would make the attempt to contact the host and, if that attempt failed, throw an exception instead of return a string.
2) Throw a custom exception:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
Throw New SomeCustomException(String.Format("Unable to contact host: {0}", PageURL), ex)
End Try
Return S
End Function
This would provide a more targeted exception instead of whatever comes out of the response reader, would provide useful runtime information about the error for logging and analysis (namely the runtime value of the PageURL), and takes a step toward hiding the implementation details from code outside of this object (since that code doesn't really care about the HttpWebRequest and HttpWebResponse, it just wants to know if the URL is good or not).
Remember that throwing an exception is a perfectly acceptable exit path for a function. It doesn't always have to return a value. An exception is an appropriate way of indicating an error condition. Your current implementation, however, "swallows" the exception and provides no indication to the consuming code that anything went wrong. Instead it returns a "magic value" of String.Empty which consuming code may or may not ignore.
Change your exception handler. The correct way to do this is to just try the request and handle the exception if it fails.

Can I add an Outlook Attachment from a PictureBox image?

I have an image in my VB.NET Picture box. I would like to attach it to the email message I'm sending through Outlook without having to save it to the drive anywhere. Is it possible to do such a thing?
Here's what I have so far (taken from here):
Public Class email
Dim app As Microsoft.Office.Interop.Outlook.Application
Dim appNameSpace As Microsoft.Office.Interop.Outlook._NameSpace
Dim memo As Microsoft.Office.Interop.Outlook.MailItem
Dim outbox As Microsoft.Office.Interop.Outlook.MAPIFolder
Public Sub New(ByVal attachment)
Try
app = New Microsoft.Office.Interop.Outlook.Application
appNameSpace = app.GetNamespace("MAPI")
appNameSpace.Logon(Nothing, Nothing, False, False)
memo = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
memo.To = "notmy#realemailaddress.com"
memo.Subject = "Testing"
memo.Body = "Hello there"
memo.Attachments.Add(attachment, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
memo.Send()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
When I comment out the attachment line it works perfectly fine, otherwise it throws a COMError. I haven't been able to find any real good information about attaching an email that way, or if it's even possible. If I can't do it this way I plan on just saving the file to some random(ish) name in C:\TEMP\, but it would be nicer if I didn't have to worry about that.
Thanks for any help
Here are your options: Attachment Types
The source information here can help also:Attachment Add Function