Making code execute in Sync VB.net | WPF - wpf

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.

Related

Pausing & Resuming in Media Player

Currently im building a media player in Wpf VB.net. Im Stuck at play and pause button. It can pause but once i click play, the song started from beginning.I want it to resume from where i pause. Need your help guys.Below is my code
Private Sub btnPlay_Click(sender As Object, e As RoutedEventArgs) Handles btnPlay.Click
mplayer.Open(New Uri(ImagePath & iPodList.SelectedValue, UriKind.RelativeOrAbsolute))
If btnPlay.Content = "Play" Then
mplayer.Play()
btnPlay.Content = "Pause"
ElseIf btnPlay.Content = "Pause" Then
mplayer.Pause()
btnPlay.Content = "Play"
End If
End Sub
Whatever mplayer is, I would assume that the fact that you call Open on it every time you click that Button would be the issue. If you want to pause and resume what is already playing then don't open something new.

Adding a DocumentWindow to a DocumentTabStrip causes the application to hang indefinitely

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

Unable to handle the new window

I have a situation(mentioned below) due to which my selenium script is failing. Can someone help me?
I have a webpage where there is a save button, clicking on save button opens a new popup window. My requirement is to switch to the new window and click on one of the buttons(in the new window) which will automatically close the window and navigates to some other page. I have written a code which actually works fine but sometimes due to the application problem the new window is not getting closed. And due to this my script is failing. Here is the code I have used.
public void test() {
// i have two pages gets involved in this scenario
driver.get("some url"); // user is in page 1
// clicking on save button
driver.findElement(By.xpath("some xpath")).click(); // a new window opens
Set<String> winIDS = driver.getWindowHandles();
if (winIDS.size() > 1) {
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.findElement(By.xpath("some xpath")).click();
//after clicking on this button the user is navigated to page2
}
// after clicking on the button in the new window the new window gets closed and the user is navigate to page 2 as mentioned before.
// To validate if that has happened i am using the below code so that my test case flow wont be stopped. But
// the code is getting hanged at the new window as the app fails to perform the button click action on the new window.
winIDS = driver.getWindowHandles();
if(winIDS.size() > 1)
{
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.close();
//i m making the test failed here as the new window is not closed.
}
}
Looking at your code, I can see that you do twice the iteration to next window:
it.next();
String childWindow = **it.next();**
The second it.next() is obsolet.
Hope this solvs your issue.

WebBrowser Fails with MP3 URL

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?

VB.net GetProcess Options

I currently have the following code that runs an external Virtual Application(created with Cameyo), when the Run Button is clicked. I also have a Timer that checks ever second to see if the Process(virtual exe program) is still open. In theory the GetProcessByName should find the program listed in the Task Manager right? However it doesn't! I even tried using GetProcessByName to Kill the process (one another button clicked), but the processs is not killed.
Could it be because I virtualized the program that I want GetProcessByName to recognize? Therefore the name of the Task in the Task Manager is not correct?.
Example
The program started: SmartDefrag.virtual.exe
It runs
The Task Manager shows it as SmartDefrag.exe
Use GetProcessByName("SmartDefrag.exe") to Disable Run Button if process SmartDefrag.exe running.
Does not Disable Run Button.
Could I use TITLE OF PROCESS? Or will the PID be the same everytime the process opens? Any other options?
Code:
Private Sub SMDFRunAppMainButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SMDFRunAppMainButton.Click
' LoadingSMDFMainButton.Visibility = Windows.Visibility.Visible
Dim downloadlocation As String = (currentpath & "\1stAidApps\SMDF\SmartDefrag.virtual.exe")
My.Settings.FileLoad = downloadlocation
Try 'Errors on Cancel
dp1Timer = New DispatcherTimer
dp1Timer.Interval = TimeSpan.FromMilliseconds(1000)
AddHandler dp1Timer.Tick, AddressOf TickMe1
dp1Timer.Start()
fileload = My.Settings.FileLoad
Process.Start(fileload)
Catch ex As Exception
MessageBox.Show("Failed to launch. Please try again.", "Launch Failed")
End Try
End Sub
Private Sub TickMe1()
Dim p() As Process
p = Process.GetProcessesByName("SmartDefrag.exe")
If p.Count > 0 Then
LoadingSMDFMainButton.Visibility = Windows.Visibility.Hidden
SMDFRunAppMainButton.IsEnabled = False
Else
SMDFRunAppMainButton.IsEnabled = True
End If
End Sub
GetProcessByName doesn't take the full path, but rather the "name" of the process. This will likely need to be GetProcessByName("SmartDefrag").
From the documentation for GetProcessByName:
The process name is a friendly name for the process, such as Outlook, that does not include the .exe extension or the path.

Resources