My application has a webbrowser control that works fine with most sites, but is having trouble with pages intended to play MP3s.
The code below sends the URLs to webViewer, my WebBrowser control. Regular pages work, however, one like this does not, and results in the browser displaying a white page with the "x" shown in the image at the top left. The page does load properly in Internet Explorer and displays a QuickTime player that plays the file.
Private Sub NavigateTo(ByVal webAddress As String)
Try
If String.IsNullOrEmpty(webAddress.Trim()) Then
MsgBox("This link is under construction...")
Return
Else
If webAddress.Contains("http://") = False Then webAddress = "http://" & webAddress
Dim navPage As New Uri(webAddress)
webViewer.Source = navPage
End If
Catch ex As Exception
MsgBox("The URL for this button is invalid. Please contact AzTech IT for help.", MsgBoxStyle.OkOnly, "Satellite Tablet Application")
ErrorHandler.Helpers.LogMessage(ex.Message)
End Try
End Sub
Is there a workaround for this issue?
Related
I have an Windows Forms application that stores PDF files as byte arrays in the database (not my first choice, but I didn't set up the database...). I want the user to be able to view one of these stored files by clicking a basic "view document" button.
With the code I have right now, the bytes are written to a file on disk, then opened using an external process (default PDF reader on user's machine). The problem is that if they click the "view document" button again before closing the file, an exception is thrown because an open file can't be overwritten.
Since I've used Process.Start() to open the file, I've tried various ways of killing the process, but I can't find a way to get the process by the filename (rather than whatever reader program opens the file, which is unknown to the app).
The relevant code inside the click handler is basic:
File.WriteAllBytes("document.pdf", PDFBytes)
Process.Start("document.pdf")
(PDFBytes is the byte array, document.pdf is just the path I'm using to store the file before it's opened. It'll get overwritten every time the user clicks the "view document" button, which is fine).
Expected result: user can click "view document" to open the PDF multiple times, and the file will close and reopen with each subsequent click without problems.
Actual result: first click opens the document just fine, next click (without closing the file first) throws "System.IO.IOException: The requested operation cannot be performed on a file with a user-mapped section open."
If I am understanding the issue this might help
Dim tempFileName As String
Dim pathToFile As String
Try
tempFileName = IO.Path.GetTempFileName
pathToFile = IO.Path.ChangeExtension(tempFileName, "pdf")
IO.File.WriteAllBytes(pathToFile, PDFBytes)
Process.Start(pathToFile)
IO.File.Delete(tempFileName)
Catch ex As Exception
'todo
End Try
edit:
delete old pdfs
Dim tdir As String = IO.Path.GetTempPath
Dim di As New IO.DirectoryInfo(tdir)
Dim fis() As IO.FileSystemInfo = di.GetFileSystemInfos
Dim ctDel As Integer = 0
For Each fi As IO.FileSystemInfo In fis
If fi.CreationTime.AddDays(28) < Date.Now Then 'older than 28 days
Try
If fi.Extension = ".pdf" Then
IO.File.Delete(fi.FullName)
ctDel += 1
End If
Catch ex As Exception
'todo
' Stop
End Try
End If
Next
I am designing an application in WPF where if you click on a button it will load that application. Example, you press spotify it will load spotify.
Thing is, sometimes there is delays for when the application (Spotify) opens which is normal! So I am adding a loading section so it will hide the logo, and my loading panel will appear in its place!
Works and looks great but I have an issue! Some reason, the gui wont update with my loading but instead my application loads first and then a few moments after it will update GUI with my loading bar. I want it so as soon as a user presses the button then they will instantly see this loading appear and then will disappear once application has successfully loaded in.
Button code:
Dim syncTask As New Task(Of Long)(Function()
MPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Button Info
LoadPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Load
Dim LPro = Process.Start(SpotifyGlobalDir)
Console.WriteLine("Loading App")
LPro.WaitForInputIdle()
Dim ProcessCheck = Process.GetProcessesByName("Spotify")
Do
Thread.Sleep(2000)
Loop Until ProcessCheck.Count > 0
Console.WriteLine("App loaded")
' LoadPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Load
'MPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Button Info
Return True
End Function)
syncTask.RunSynchronously()
I think I might need some multithreading? But if i do that i get errors as I need to invoke the visibility changes which I dont know how to do?
Try to call Process.Start and Thread.Sleep on background thread but set the Visibility properties of the elements on the UI thread:
MPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Button Info
LoadPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Load
Task.Run(Sub()
Dim LPro = Process.Start(SpotifyGlobalDir)
Console.WriteLine("Loading App")
LPro.WaitForInputIdle()
Dim ProcessCheck = Process.GetProcessesByName("Spotify")
Do
Thread.Sleep(2000)
Loop Until ProcessCheck.Count > 0
End Sub) _
.ContinueWith(Sub(t)
Console.WriteLine("App loaded")
LoadPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Load
MPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Button Info
End Sub, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext())
The UI thread cannot both display the controls and sleep at the same time. A single thread can only do one single thing at a time.
I have a Winforms application with a primary form that contains (among other things) a Telerik DocumentTabStrip. These tabs are used to hold user controls or web pages (via a web browser control). It has worked fine for quite a while, but I'm running into an issue now.
I recently switched the web browser control from the built-in .NET web browser based on IE to CefSharp. Since doing so, I've noticed that occasionally when trying to add the DocumentWindow to the DocumentTabStrip, the call will hang indefinitely (in debug) or crash outright (running the app normally). This only appears to happen when opening a DocumentWindow that contains the browser control, not any other user controls. The actual call itself is below.
I'm at a bit of a loss as to how to even begin to debug this, since there's no error that gets received - it just hangs inside the Controls.Add() method indefinitely. Any advice would be appreciated.
Private dts As New Telerik.WinControls.UI.Docking.DocumentTabStrip
Try
dts.InvokeIfRequired(Sub()
Dim docWindow As Telerik.WinControls.UI.Docking.DocumentWindow = Nothing
Dim ctrl As ucBaseControl = Nothing
Dim browser As ucBrowser = Nothing
Dim isBrowser As Boolean = False
docWindow = New Telerik.WinControls.UI.Docking.DocumentWindow
docWindow.BackColor = Color.FromArgb(89, 89, 89)
'Do various stuff to determine the type of control to load (ctrl or browser), then setup the applicable control
If isBrowser Then
'Place the browser into the Document Window.
If Not IsNothing(browser) Then
browser.Dock = DockStyle.Fill
docWindow.Controls.Add(browser)
End If
Else
'Place the ctrl into the Document Window.
ctrl.Dock = DockStyle.Fill
docWindow.Controls.Add(ctrl)
End If
'Add the DocumentWindow to the DocumentTabStrip
' Ensure DockWindow not disposed due to lag in bringing up
If IsNothing(docWindow) OrElse docWindow.IsDisposed Then
Exit Sub
End If
Try
docWindow.Padding = New Padding(0)
dts.TabStripElement.Children(0).Children(1).Padding = New Padding(0)
dts.Controls.Add(docWindow) 'This is where the issue is. It only happens sporadically here.
Catch ex As Exception
'Code to log any exceptions here. In the problem described here, no exception is ever generated, though.
End Try
'Bring the control to the front and focus it, here...
End Sub)
Catch ex As Exception
'Error handling code here'
End Try
I'm assuming InvokeIfRequired is an extension method you've created for Controls. Note that if it relies on Invoke, that is a synchronous call, instead use BeginInvoke (see: What's the difference between Invoke() and BeginInvoke())
No exception was ever thrown because you were suffering from deadlock
I am using WPF control for CefSharp. I need to know when the request I made receives a response with http status code 404.
I've noticed that CefSharp has LoadError event, but that only fires when the domain cannot be resolved altogether (i.e. if I go to www.sdfhjkhajsdf.com). It doesn't work for when the domain exists, but the page your requesting doesn't.
This is a pretty old question. CefSharp has had lots of great updates, so I hope this helps others searching like me. Don't hate me because my snippets are in VB.NET. ;)
This is what I'm doing to log anything that is not 200 response. For my application, I open a new form of the requested page, so I limit my focus to the initial page request by looking at the ReferrerUrl property. Obviously, you could drop that part to be alerted to all requests.
When you initially implement your ChromiumWebBrowser you need to set a RequestHandler to your implementation.
Me.chromeBrowser = New CefSharp.WinForms.ChromiumWebBrowser(uri)
Me.chromeBrowser.RequestHandler = New CefBasicRequestHandler()
Me.Controls.Add(Me.chromeBrowser)
CefSharp released a default implementation that you can use and just override OnResourceResponse.
Imports System.Security.Cryptography.X509Certificates
Imports CefSharp
Public Class CefBasicRequestHandler
Inherits CefSharp.Handler.DefaultRequestHandler
Private Shared ReadOnly Logger As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
Public Overrides Function OnResourceResponse(browserControl As IWebBrowser, browser As IBrowser, frame As IFrame, request As IRequest, response As IResponse) As Boolean
If String.IsNullOrWhiteSpace(request.ReferrerUrl) Then ' this is the first request of the page
Dim method As String = "OnResourceResponse()."
Dim requestOverview As String = $"[{response.StatusCode}] [{request.Url}]"
Logger.Info($"{method} {requestOverview}")
If response.StatusCode <> 200 Then
Logger.Warn($"{method} {requestOverview}")
End If
End If
Return MyBase.OnResourceResponse(browserControl, browser, frame, request, response)
End Function
End Class
I have tried to use a webbrowser in my VB program to load a web page and the table on the web page. It works but VERY slowly and a lot of the time it freezes.
I found some sample code that reads the web page without a web browser. It reads the text on the web page and puts it into a Rich Text Box called WebText.
This code works really quick and never locks up but it does not read the text that is in the table on the webpage.
The code I am using calls the function below:
WebText.Text = GetHTMLCode("http://xfinitytv.comcast.net/tv-listings")
Function GetHTMLCode(ByVal strURL) As String
Dim strReturn ' As String
Dim objHTTP ' As MSXML.XMLHTTPRequest
If Len(strURL) = 0 Then Exit Function
objHTTP = CreateObject("MSXML2.XMLHTTP")
objHTTP.open("GET", strURL, False)
objHTTP.send() 'Get it.
strReturn = objHTTP.responseText
objHTTP = Nothing
GetHTMLCode = strReturn
End Function
I am new to programming (hoping to get better with time). If I write something that sounds like I do not know what I am talking about it is probably because I don't. Any help would be appreciate.
Thanks,
Chris