background worker dont work - background

I want to read a text file from the Internet and I want while reading the file a picturebox, that is a gif animation, show and after the reading is finished picturebox hide.
I use background worker. I have a lable that shows the state, but when I click BtnCheck Button bg doesn't work and the lable doesn't change.
My code:
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void BtnCheck_Click(object sender, EventArgs e)
{
PbLoading.Visible = true;
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
LbleState.Text = "Reading txt File...";
webClient1 = new WebClient();
if (CheckForInternetConnection())
{
try
{
Stream stream = webClient1.OpenRead(TxtWebAdrss);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
reader.Close();
LbleState.Text = "Reading Finished .";
}
catch
{
LbleState.Text = "Error reading";
}
}
else LbleState.Text = "Internet not connected!";
}

You may just need to do a bit more research into this class. You should perform UI changes on the UI thread.
There are three event handlers that you can use and these are,
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
The following link should help,
http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker(v=vs.110).aspx

Related

Webcam motion Detection using AForge C#

I am using code for motion detection webcam using Aforge. When running the program, it can run perfectly, but when edit libel1 "motion Detection" and libel2 "no motion Detection" it cannot running. Why?
The code I'm using for motion detection:
public Form1()
{
InitializeComponent();
}
FilterInfoCollection fic;
VideoCaptureDevice Device;
MotionDetector motionDetector;
float f;
private void Form1_Load(object sender, EventArgs e)
{
motionDetector = new MotionDetector(new TwoFramesDifferenceDetector(), new MotionAreaHighlighting());
fic = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo item in fic)
{
comboBoxDevice.Items.Add(item.Name);
}
comboBoxDevice.SelectedIndex = 0;
}
private void BtnStart_Click(object sender, EventArgs e)
{
Device = new VideoCaptureDevice(fic[comboBoxDevice.SelectedIndex].MonikerString);
videoSourcePlayer1.VideoSource = Device;
videoSourcePlayer1.Start();
}
private void BtnStop_Click(object sender, EventArgs e)
{
videoSourcePlayer1.Stop();
}
private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
if (motionDetector == null) return;
f = motionDetector.ProcessFrame(image);
if (f >0)
{
label1.ForeColor = Color.Red;
label1.Text = "Motion Detected";
}
else
{
label1.ForeColor = Color.Green;
label1.Text = "No Motion Detected";
}
}
private void timer_Tick(object sender, EventArgs e)
{
label3.Text = "Value: " + f.ToString();
}
}
}
I think you want to change a label in your UI when you detect a motion. If you want to change a label in UI, you can't run the change function in the same thread. So, you can change it by defining another thread. Just make sure you prevent race conditions.
// Changing UI Labels (Make thread)
Label1.Invoke((MethodInvoker)delegate {
// What do you want to change?
Label1.Text = "Detecting Motions";
});

Duplicated output from process.OutputDataReceived

I'm having an issue with duplicated content from redirected output.
In my forms I have two buttons: Run and Clear.
public partial class BatchRun : Form
{
Process process = new Process();
public BatchRun()
{
InitializeComponent();
}
private void RunBTN_Click(object sender, EventArgs e)
{
//initiate the process
this.process.StartInfo.FileName = sMasterBATname;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
this.process.StartInfo.RedirectStandardInput = true;
this.process.Start();
this.process.BeginOutputReadLine();
}
public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
{
BeginInvoke(new MethodInvoker(() =>
{
Label TestLBL = new Label();
TestLBL.Text = text.TrimStart();
TestLBL.AutoSize = true;
TestLBL.Location = new Point(10, CMDpanel.AutoScrollPosition.Y + CMDpanel.Controls.Count * 20);
CMDpanel.Controls.Add(TestLBL);
CMDpanel.AutoScrollPosition = new Point(10, CMDpanel.Controls.Count * 20);
}));
}
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
}
}
This works great if I want to run process only once i.e. close the forms once process has completed.
However, I need to allow user to rerun the same process or run a new one hence I have added a clear button the clear various controls etc.
The problem I'm having is that after clicking clear button, I want to click run button again without closing which should then run the sMAsterBAT file(CMD).
StandardOutputHandler seems to be including content of the previous run as well as the new one resulting in duplicated labels in my CMDpanel.
Is this stored in some kind of buffer? If so, How do i clear it to allow me a rerun?
Could someone explain why this is happening and how to resolve it please.
Spoke to someone at work who fixed it for me. So easy lol
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
this.process = new Process(); // this line resolved my issue!!
}
}

Improve software responsiveness when slider is manipulated in windows phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

Play audio in background by use BackgroundCapableMedia

In the windows8 Developer preview we can use this code to play audio in background:
mediaElement.AudioCategory = AudioCategory.Media;
In the windows8 Customer perview, It seems that we should use AudioCategory.BackgroundCapableMedia instead of AudioCategory.Media
mediaElement.AudioCategory=AudioCategory.BackgroundCapableMedia;
and I also Declare a background task in appxmanifest
<Extension Category="windows.backgroundTasks" EntryPoint="TestApp.App">
<BackgroundTasks>
<Task Type="audio" />
</BackgroundTasks>
</Extension>
but it didn't work for me and the MediaElement will throw an "MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED“ exception in MediaFailed EventHandler
How should I do?
You also need to set up these event handlers:
using Windows.Media;
MediaControl.PlayPressed += MediaControl_PlayPressed;
MediaControl.PausePressed += MediaControl_PausePressed;
MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
MediaControl.StopPressed += MediaControl_StopPressed;
-
void MediaControl_StopPressed(object sender, object e)
{
myMediaPlayer.Stop();
}
void MediaControl_PlayPauseTogglePressed(object sender, object e)
{
}
void MediaControl_PausePressed(object sender, object e)
{
myMediaPlayer.Pause();
}
void MediaControl_PlayPressed(object sender, object e)
{
myMediaPlayer.Play();
}
I think that should have it working.

DOTMsn is not firing the SingedIn event

I have just started building a app using “XihSolutions.DotMSN.dll” version: 2.0.0.40909,
My problem is that it is not firing the “Nameserver_SignedIn” event. Not sure if I am doing something wrong.
your help will be really helpful.
void Nameserver_SignedIn(object sender, EventArgs e)
{
throw new Exception("User Signed In");
}
private string message = string.Empty;
void NameserverProcessor_ConnectionEstablished(object sender, EventArgs e)
{
message = "Connected";
SetMessage();
}
void SetMessage()
{
if (tbMessage.InvokeRequired)
tbMessage. Invoke(new ThreadStart(SetMessage));
else
tbMessage.Text += Environment.NewLine+ message;
}
private void btnSingIn_Click(object sender, EventArgs e)
{
if (messenger.Connected)
{
// SetStatus("Disconnecting from server");
messenger.Disconnect();
}
// set the credentials, this is ofcourse something every DotMSN program will need to
// implement.
messenger.Credentials.Account = tbUserName.Text;
messenger.Credentials.Password = tbPwd.Text;
// inform the user what is happening and try to connecto to the messenger network.
//SetStatus("Connecting to server");
messenger.Connect();
}
You might use MSNPSharp instead - DotMSN is old and may not support the current MSN protocol. There link is here:
http://code.google.com/p/msnp-sharp/