Eventhandler is fired more than once - events

I have a problem with two of my EventHandlers, they work the same, so here is one:
private void Form1_Load(object sender, EventArgs e)
{
webBrowserWebsite.Url = new System.Uri(textBoxURL.Text, System.UriKind.Absolute);
webBrowserWebsite.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserWebsite_DocumentCompleted);
}
void webBrowserWebsite_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\CurrentData.wfd");
sw.Write(webBrowserWebsite.Document.Body.InnerText);
sw.Close();
}
The problem is, that the EventHandler fires multiple times, it doesn't stop!
Why is it doing this?
Thanks in advance

The code that you have written won't compile (your StreamWriter in your EventHandler isn't assigned to anything) and without more context as to how you are calling this, it is difficult to say for certain.
But the most likely reason is you are calling Form1_Load multiple times, but using the same webBrowserWebsite object. Each time the form loads, you are adding a new Event Handler. And since you aren't showing any code showing where you removing the event handler, I'm guessing it fires once for each time you call Form_Load.
Depending on your design, you are better off adding the event handler in the constructor so it is only added once regardless of the number of times you load the form.
public Form1()
{
webBrowserWebsite.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserWebsite_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowserWebsite.Url = new System.Uri(textBoxURL.Text, System.UriKind.Absolute);
}
Or remove the event handler in the event handler:
void webBrowserWebsite_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\CurrentData.wfd");
sw.Write(webBrowserWebsite.Document.Body.InnerText);
sw.Close();
webBrowserWebsite.DocumentCompleted -= webBrowserWebsite_DocumentCompleted;
}
Also, since StreamWriter implements IDisposible, you should be putting it inside of a using block or at least calling sw.Dispose() at the end of the method

Related

How does Windows.System.Configuration.Install.Installer work

I am trying to configure my installer so that it will close any instances of the application before installation starts and relaunch the application once installation has finished.
The MS documents provide and example similar to the one below and indicate that the [RunInstaller(true)] annotation specifies whether the Visual Studio Custom Action Installer or the Installutil.exe (Installer Tool) should be invoked when the assembly is installed.
Of course this could mean just about anything...
I am using the Visual Studio Project Installer NuGet package to create the install files (setup.exe and APP.msi files). When configuring the Project Installer there is an option set configure the Custom Actions - I assume this is what the documentation means.
However the Custom Actions has options to add things to the Install, Commit sections - what has to be added to these sections and how does this relate to the Installer class defined below.
This whole area of installation seems to be poorly documented and there seem to be so many options, none of which seem to work properly.
You would think closing any running instances before installing an update and then relaunching after completing the installation would be a no brainer but it seems anything but simple.
Appreciate any assistance with a working example of how this can be achieved.
namespace FocusBracketer
{
[RunInstaller(true)]
public partial class Installer: System.Configuration.Install.Installer
{
public Installer() : base()
{
InitializeComponent();
// Attach the 'BeforeInstall' event.
this.BeforeInstall += new InstallEventHandler(Installer_BeforeInstall);
// Attach the 'Committed' event.
this.Committed += new InstallEventHandler(Installer_Committed);
// Attach the 'Committing' event.
this.Committing += new InstallEventHandler(Installer_Committing);
}
// Event handler for 'BeforeInstall' event.
private void Installer_BeforeInstall(object sender, InstallEventArgs e)
{
Console.WriteLine("");
Console.WriteLine("BeforeInstall Event occurred.");
Console.WriteLine("");
}
// Event handler for 'AfterInstall' event.
private void Installer_AfterInstall(object sender, InstallEventArgs e)
{
Console.WriteLine("");
Console.WriteLine("AfterInstall Event occurred.");
Console.WriteLine("");
System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(this.Context.Parameters["AssemblyPath"]) + #"\FocusBracketer.exe");
}
// Event handler for 'Committing' event.
private void Installer_Committing(object sender, InstallEventArgs e)
{
Console.WriteLine("");
Console.WriteLine("Committing Event occurred.");
Console.WriteLine("");
}
// Event handler for 'Committed' event.
private void Installer_Committed(object sender, InstallEventArgs e)
{
Console.WriteLine("");
Console.WriteLine("Committed Event occurred.");
Console.WriteLine("");
}
// Override the 'Install' method.
public override void Install(IDictionary savedState)
{
base.Install(savedState);
}
// Override the 'Commit' method.
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
}
// Override the 'Rollback' method.
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
}
public static void Main()
{
Console.WriteLine("Usage : installutil.exe Installer.exe ");
}
}
}

ICommentEvent runs TWICE in ONE comment event Sitefinity

I have these code, according to document from sitefinity:
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Initialized += new EventHandler<ExecutedEventArgs>(Bootstrapper_Initialized);
}
public void Bootstrapper_Initialized(object sender, ExecutedEventArgs args)
{
if (args.CommandName == "Bootstrapped")
{
EventHub.Subscribe<ICommentEvent>(evt => CommentsEvent.CommentEventHandler(evt));
}
}
And the handler:
public static void CommentEventHandler(ICommentEvent evt)
{
// My code here
}
The problem is this handler always runs twice when a comment event happens (post a comment or approve a comment).
Could you please tell me why this happens and any possible way to avoid this? (I don't believe static boolean is a good idea).
Thanks
ICommentEvent is a base interface that is implemented by multiple events such as ICommentCreatingEvent, ICommentCreatedEvent, ICommentUpdatingEvent, ICommentUpdatedEvent and some others.
In your case it is fired twice due to firing of both ICommentCreatingEvent and ICommentCreatedEvent.
You can subscribe to just one of them and it should fire just once.

Adding a client-side event handler for TFS GetCompleted

I want to know when (using either Visual Studio, or TF.exe) the client triggers Get Latest Version. Because I want to trigger my scripted build process to behave differently when this has occurred.
I have already tried to create a WinForms application that implements an event handler, as below:
private void Form1_Load(object sender, EventArgs e)
{
var collections = RegisteredTfsConnections.GetProjectCollections();
var tpc = new TfsTeamProjectCollection(collections.First().Uri, CredentialCache.DefaultNetworkCredentials);
var vcServer = tpc.GetService<VersionControlServer>();
vcServer.GetCompleted += VcServer_GetCompleted;
vcServer.Getting += VcServer_Getting;
}
private void VcServer_GetCompleted(object sender, WorkspaceEventArgs e)
{
textBox1.AppendText("VcServer_GetCompleted" + Environment.NewLine);
}
private void VcServer_Getting(object sender, GettingEventArgs e)
{
textBox1.AppendText("VcServer_Getting" + Environment.NewLine);
}
But it would appear that these event handlers only listen to this instance of VersionControlServer, not globally on the client workstation.

Using Events From A Class

I am trying to get a function to be called everytime an event occurs. In the KinectRegion class there is an event called HandPointerGrip: http://msdn.microsoft.com/en-us/library/microsoft.kinect.toolkit.controls.kinectregion.handpointergrip.aspx.
I see that it has declared the event and it seems to me that the event has already been set to be invoked(HandPointerEventArgs)? How do I attach a function to this event?
public Menu()
{
KinectRegion.HandPointerGripEvent+=Hand_Gripped; // why doesn't this work? :(
}
private void Hand_Gripped(object sender, HandPointerEvnetArgs e)
{
MessageBox.Show("I work!"); // I wish this would work
}
Been working hard on this problem and here is something I think will work. Afraid to test it. Learning a lot about routed events, delegates, and events.
namespace ...
{
public delegate void HandPointerEventHandler(object sender, HandPointerEventArgs e);
public partial class thePage : Page
{
public event HandPointerEventHandler HandGripped
{
add {this.AddHandler(KinectRegion.HandPointerGripEvent,value);}
remove {this.RemoveHandler(KinectRegion.HandPointerGripEvent,vlaue);}
}
public thePage()
{
InitializeComponent();
this.HandGripped += new HandPointerEventHandler(OnHandGripped);
}
protected virtual void OnHandGripped(object sender, HandPointerEventArgs e)
{
MessageBox.Show("hello"); //hopefully
}
}
}
The first block of code should work fine. My guess is that the HandPointerGripEvent is hooked up ok, it just never fires.
How are you setting up your KinectRegion?
Are you updating the interration library each frame?
Perhaps this helps?
Kinect SDK 1.7: Mapping Joint/Cursor Coordinates to screen Resolution
KinectRegion.AddHandPointerGripHandler(this.Button1, this.Button1_Click);
Here Button1 is:
< k:KinectTileButton x:Name="Button1" Height="150" Width="150" Content="Click"/ >
The namespaces:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:k="http://schemas.microsoft.com/kinect/2013"
Button1_Click is the method itself, for example:
private void Button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("YOU GOT ME !!!");
}
If you want to add a grip handler for another interface object, you just do:
KinectRegion.AddHandPointerGripHandler(< object name >, < method name >);
And s.o.

Live SDK Windows Phone 7 GetCompleted callback in UI thread?

public class SyncHelper
{
private LiveConnectClient client;
public event EventHandler SyncStarted;
public event EventHandler SyncCompleted;
public SyncHelper(LiveConnectClient client)
{
this.client = client;
}
public void TrySync()
{
Debug.WriteLine("Beginning sync");
OnSyncStarted();
client.GetCompleted += OnGetCompleted;
client.GetAsync("me/skydrive/files");
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
Thread.Sleep(10000);
Debug.WriteLine("Get Completed");
client.GetCompleted -= OnGetCompleted;
OnSyncCompleted();
Debug.WriteLine("Sync completed");
}
private void OnSyncStarted()
{
if (SyncStarted != null)
SyncStarted(this, new EventArgs());
}
private void OnSyncCompleted()
{
if (SyncCompleted != null)
SyncCompleted(this, new EventArgs());
}
}
The function OnGetCompleted is being called in the UI thread and the UI is unresponsive. From whatever I know, I thought these callbacks would work in a different thread and we would have to use the displatcher to post it to the UI thread. Any thoughts? Help!
The GetAsync call is likely using a background thread to do the actual fetch, but then it's trying to help you by calling the Completed callback in the original thread context so you don't have to use a Dispatcher.
Why are you putting in a Sleep(10000) anyway? The callback says "hey, I'm done". At that point you should update the UI if you want. If you need to do further processing that takes significant time, spawn a background thread, threadpool task or use another asynchronous call with another callback.

Resources