UWP MediaEnded event handler for MediaPlayerElement Throws System.ArgumentException - c#

First off I'm fairly new to UWP so if this question is stupid, my apologies.
What I'm attempting to do is set the event handler for when the song has finnished so that I can start the next one. However when launching I get thrown the following error after the program has started Exception thrown: 'System.ArgumentException' in System.Private.CoreLib.ni.dll
An exception of type 'System.ArgumentException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code
Delegate to an instance method cannot have null 'this'.
This error traces back to mediaPlayer.MediaPlayer.MediaEnded += MediaPlayer_MediaEnded1;
I suspect that I'm incorrectly setting the handler.
<MediaPlayerElement x:Name="mediaPlayer" AreTransportControlsEnabled="True" Margin="0,0,0,0"/>
Here is my code
List<Song> songs = new List<Song>();
//private MediaPlayerElement PlayMusic = new MediaPlayerElement();
private int curSongIndex = 0;
private IReadOnlyList<StorageFile> files;
public MainPage(){
this.InitializeComponent();
slist.ItemClick += Slist_ItemClick;
mediaPlayer.MediaPlayer.MediaEnded += MediaPlayer_MediaEnded1;
}
private void MediaPlayer_MediaEnded1(Windows.Media.Playback.MediaPlayer sender, object args) {
playNextSong();
}
private void Play(Song song) {
mediaPlayer.Source = MediaSource.CreateFromStorageFile(song.File);
mediaPlayer.MediaPlayer.Play();
AlbumArt.Source = song.Art;
}
private void Slist_ItemClick(object sender, ItemClickEventArgs e) {
for(int i = 0; i < songs.Count; i++) {
if (e.ClickedItem.Equals(songs[i])) {
Play(songs[i]);
curSongIndex = i;
}
}
}

Related

Why does subscription to Application.ThreadException swallow the exception?

Suppose I have an exception throw in the message loop:
private void timer1_Tick(object sender, EventArgs e)
{
throw new Exception("yehaaaa!!!!");
}
By default, this throws & displays the generic error dialog to user. (that's what I want)
However if I add the following subscription to Application.ThreadException:
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
//_raygunClient.Send(e.Exception);
}
Then the exception is swallowed.
Why?
& how can I have it throw to the user normally?
It's all right there in the reference source:
internal void OnThreadException(Exception t) {
if (GetState(STATE_INTHREADEXCEPTION)) return;
SetState(STATE_INTHREADEXCEPTION, true);
try {
if (threadExceptionHandler != null) {
threadExceptionHandler(Thread.CurrentThread, new ThreadExceptionEventArgs(t));
}
else {
if (SystemInformation.UserInteractive) {
ThreadExceptionDialog td = new ThreadExceptionDialog(t);
If there is a handler it is invoked otherwise some standard code is run. If you want to show the standard dialog, use ThreadExceptionDialog and handle the DialogResult the same way. In my own code there is something to this effect, which seems to work:
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Exception exception = e.Exception;
_Logger.Error(e.Exception, "An unhandled forms application exception occurred");
// Show the same default dialog
if (SystemInformation.UserInteractive)
{
using (ThreadExceptionDialog dialog = new ThreadExceptionDialog(exception))
{
if (dialog.ShowDialog() == DialogResult.Cancel)
return;
}
Application.Exit();
Environment.Exit(0);
}
}

System.InvalidCastException when using Webbrowser and Background worker class C#

public void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < idscount; i++)
{
if (bgw.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
bgw.ReportProgress(i + 1);
webBrowser1.Document.GetElementById("txtIDCardNo").SetAttribute("Value", "\"" + value + "\"");
webBrowser1.Document.GetElementById("btnIDCard").InvokeMember("click");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WaitElement);
System.Threading.Thread.Sleep(200);
}
}
}
I end up in "An exception of type 'System.InvalidCastException' occurred in System.Windows.Forms.dll but was not handled in user code". I am not able to understand, If I run same code without background worker class it works but inside background worker class it doesnt. Please help me out.

Exception when closing Form (thread + invoke)

I have just started to learn about threads and methodinvoking in c#, but I have come across a problem which I couldn't find the solution of.
I made a basic C# form program which keeps updating and displaying a number, by starting a thread and invoke delegate.
Starting new thread on Form1_load:
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Threading.Thread(DoThisAllTheTime);
t.Start();
}
Public void DoThisAllTheTime (which keeps updating the number) :
public void DoThisAllTheTime()
{
while(true)
{
if (!this.IsDisposed)
{
number += 1;
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
this.Invoke(yolo);
}
}
}
Now when I click the X button of the form, I get the following exception:
'An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll
Can't update a deleted object'
While I actually did check if the form was disposed or not.
EDIT: I added catch (ObjectDisposedException ex) to the code which fixed the problem.
Working code:
public void DoThisAllTheTime()
{
while(true)
{
number += 1;
try {
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
this.Invoke(yolo);
}
catch (ObjectDisposedException ex)
{
t.Abort();
}
}
}
Your call to this.IsDisposed is always out of date. You need to intercept your form closing event and stop the thread explicitly. Then you won't have to do that IsDisposed test at all.
There are many ways you can do this. Personally, I would use the System.Threading.Tasks namespace, but if you want to keep your use of System.Threading, you should define a member variable _updateThread, and launch it in your load event:
_updateThread = new System.Threading.Thread(DoThisAllTheTime);
_updateThread.Start();
Then in your closing event:
private void Form1_Closing(object sender, CancelEventArgs e)
{
_stopCounting = true;
_updateThread.Join();
}
Finally, replace the IsDisposed test with a check on the value of your new _stopCounting member variable:
public void DoThisAllTheTime()
{
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
while(!_stopCounting)
{
number += 1;
this.Invoke(yolo);
}
}
Just put this override in your form class:
protected override void OnClosing(CancelEventArgs e) {
t.Abort();
base.OnClosing(e);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Thread.CurrentThread.Abort();
}

WIA Scanning throws exception while using ADF Scanner

I am using the ADF Scanner library by Gideon (http://adfwia.codeplex.com/) and have hit a small problem. While I can scan a file it throws an exception when saving. I'll post the full code:
private void button1_Click(object sender, EventArgs e)
{
ADFScan _scanner;
int[] _colors = { 1, 2, 4 };
int count = 0;
_scanner = new ADFScan();
_scanner.Scanning += new EventHandler<WiaImageEventArgs>(_scanner_Scanning);
_scanner.ScanComplete += new EventHandler(_scanner_ScanComplete);
ScanColor selectedColor = ScanColor.Color;
// ScanColor selectedColor = (ScanColor)_colors[comboBox1.SelectedIndex];
int dpi = 300;
_scanner.BeginScan(selectedColor, dpi);
}
void _scanner_ScanComplete(object sender, EventArgs e)
{
MessageBox.Show("Scan Complete");
}
void _scanner_Scanning(object sender, WiaImageEventArgs e)
{//e.ScannedImage is a System.Drawing.Image
int count = 0;
string filename = "C:\\test.jpg";
e.ScannedImage.Save(filename, ImageFormat.Jpeg);//FILES ARE RETURNED AS BITMAPS
}
The program begins to scan without an issue, and in fact can scan multiple pages at the same time (what I needed!) The exception thrown is this one
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
Huh? Anyone with experience with this can help me? Thanks a lot in advance =)

NAudio NullReferenceException when using a Start/Stop button

I have a GUI form with a checkbox button for Start/Stop. When the program starts, clicking Start and Stop works once. When I try and click Start again after I stop the recording, I get a NullReferenceException.
An unhandled exception of type 'System.NullReferenceException' occurred in NAudio.dll
Additional information: Object reference not set to an instance of an object.
at this line in my Program.cs file:
Application.Run(new GUI());
Here is my Start/Stop button in my GUI form:
public GUI()
{
InitializeComponent();
InitializeAudio();
}
private void btnStartStop_CheckedChanged(object sender, EventArgs e)
{
if (btnStartStop.Checked)
{
waveInDevice.StartRecording();
waveOutDevice.Play();
btnStartStop.Text = "Stop";
}
else
{
btnStartStop.Text = "Start";
waveInDevice.StopRecording();
waveOutDevice.Stop();
}
}
private void InitializeAudio()
{
buffer = new BufferedWaveProvider(waveInDevice.WaveFormat);
buffer.DiscardOnBufferOverflow = true;
waveInDevice.DataAvailable += new EventHandler<WaveInEventArgs>(waveInDevice_DataAvailable);
waveOutDevice.Init(buffer);
}

Categories

Resources